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
e2824fdc70184d820e7fd76a0b87ba57c8c584fa
39
module BankJob VERSION = "0.0.1" end
9.75
19
0.666667
0108eefc069b614ced74e944e5abfe9500de9020
349
namespace :elasticsearch do desc 'reindex all orgs in search' task reindex: :environment do Organization.pluck(:id).each_slice(1000) do |ids| args = ids.map { |id| ['Organization', id] } Sidekiq::Client.push_bulk('class' => SearchIndexJob, 'args' => args) puts "[#{Time.now.utc}] Queued #{ids.size} ids." end end end
31.727273
74
0.647564
ac1e8fdd6a9da741da47664600af59004a5aa854
120
# Loads mkmf which is used to make makefiles for Ruby extensions require 'mkmf' # Do the work create_makefile('basic')
20
64
0.766667
1d8d18e1f618daeea1f39185c7fa9eb47fa950bb
2,534
class ServicesController < ApplicationController before_action :set_service, except: [:index, :new, :create] before_action :authenticate_user!, except: [:show] before_action :is_authorised, only: [:listing, :pricing, :description, :photo_upload, :expertise_area, :location, :update] def index @service = current_user.services @services = @service.all end def new @service = current_user.services.build end def create @service = current_user.services.build(service_params) if @service.save redirect_to listing_service_path(@service), notice: "Saved..." else flash[:alert] = "Something went wrong..." render :new end end def show @photos= @service.photos @traveler_reviews = @service.traveler_reviews end def listing set_service end def pricing end def description end def photo_upload @photos = @service.photos end def expertise_area end def location end def update new_params= service_params new_params = service_params.merge(active: true) if is_ready_service if @service.update(new_params) flash[:notice] = "Saved..." else flash[:alert] = "Something went wrong..." end redirect_back(fallback_location: request.referer) end # -------RESERVATIONS ------------ def preload today = Date.today reservations = @service.reservations.where("start_date >= ? OR end_date >= ?", today, today) render json: reservations end def preview start_date = Date.parse(params[:start_date]) end_date = Date.parse(params[:end_date]) output = { conflict: is_conflict(start_date, end_date, @service) } render json: output end private def is_conflict(start_date, end_date, service) check = service.reservations.where("? < start_date AND end_date < ?", start_date, end_date) check.size > 0? true : false end def set_service @service = Service.find(params[:id]) end def service_params params.require(:service).permit(:gender,:city, :language, :price, :guide_name, :summary, :has_outdoors,:has_shopping,:has_museum,:has_monuments, :has_food,:has_night, :time_spent,:active) end def is_authorised redirect_to root_path, alert: "You don't have permission" unless current_user.id == @service.user_id end def is_ready_service [email protected] && [email protected]? && [email protected]_name.blank? && [email protected]? && [email protected]? end end
22.625
193
0.677585
28c65cedba80bdf8846912389f55534f5d66d544
1,224
# 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/androidmanagement_v1/service.rb' require 'google/apis/androidmanagement_v1/classes.rb' require 'google/apis/androidmanagement_v1/representations.rb' module Google module Apis # Android Management API # # The Android Management API provides remote enterprise management of Android # devices and apps. # # @see https://developers.google.com/android/management module AndroidmanagementV1 VERSION = 'V1' REVISION = '20191001' # Manage Android devices and apps for your customers AUTH_ANDROIDMANAGEMENT = 'https://www.googleapis.com/auth/androidmanagement' end end end
34
82
0.748366
6272ef6f27834dd7b5b4e705e5313a3484098cc8
888
# -*- encoding: utf-8 -*- require 'spec_helper' describe ActiveFedora::RDF do describe ActiveFedora::RDF::Fcrepo do it "registers the vocabularies" do namespaces = [ "info:fedora/fedora-system:def/model#", "info:fedora/fedora-system:def/view#", "info:fedora/fedora-system:def/relations-external#", "info:fedora/fedora-system:" ] namespaces.each do |namespace| vocab = RDF::Vocabulary.find(namespace) expect(vocab.superclass).to be(RDF::StrictVocabulary) end end end describe ActiveFedora::RDF::ProjectHydra do it "registers the vocabularies" do namespaces = [ "http://projecthydra.org/ns/relations#" ] namespaces.each do |namespace| vocab = RDF::Vocabulary.find(namespace) expect(vocab.superclass).to be(RDF::StrictVocabulary) end end end end
28.645161
61
0.64527
e91dc7c711592841145a1b289e105b84ade3080a
325
module Gws::Addon::Discussion::Todo extend ActiveSupport::Concern extend SS::Addon included do attr_accessor :in_discussion_forum belongs_to :discussion_forum, class_name: "Gws::Discussion::Forum" scope :discussion_forum, ->(discussion_forum) { where(discussion_forum_id: discussion_forum.id) } end end
27.083333
101
0.763077
61341c22b60dfd2a2abe7fdb4063fe3df14e10e6
2,138
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Signalr::Mgmt::V2018_03_01_preview module Models # # The core properties of ARM resources. # class Resource include MsRestAzure # @return [String] Fully qualified resource Id for the resource. attr_accessor :id # @return [String] The name of the resouce. attr_accessor :name # @return [String] The type of the service - e.g. # "Microsoft.SignalRService/SignalR" attr_accessor :type # @return [String] the name of the resource group of the resource. def resource_group unless self.id.nil? groups = self.id.match(/.+\/resourceGroups\/([^\/]+)\/.+/) groups.captures[0].strip if groups end end # # Mapper for Resource class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'Resource', type: { name: 'Composite', class_name: 'Resource', model_properties: { id: { client_side_validation: true, required: false, read_only: true, serialized_name: 'id', type: { name: 'String' } }, name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'name', type: { name: 'String' } }, type: { client_side_validation: true, required: false, read_only: true, serialized_name: 'type', type: { name: 'String' } } } } } end end end end
26.073171
72
0.494855
21ab4540aa490de5c9012026024b8af4f329312d
2,243
require 'socket' class Bud::BudServer < EM::Connection #:nodoc: all def initialize(bud, channel_filter) @bud = bud @channel_filter = channel_filter @filter_buf = {} @pac = MessagePack::Unpacker.new super end def receive_data(data) # Feed the received data to the deserializer @pac.feed_each(data) do |obj| recv_message(obj) end # apply the channel filter to each channel's pending tuples buf_leftover = {} @filter_buf.each do |tbl_name, buf| if @channel_filter accepted, saved = @channel_filter.call(tbl_name, buf) else accepted = buf saved = [] end unless accepted.empty? @bud.inbound[tbl_name] ||= [] @bud.inbound[tbl_name].concat(accepted) end buf_leftover[tbl_name] = saved unless saved.empty? end @filter_buf = buf_leftover begin @bud.tick_internal if @bud.running_async rescue Exception => e # If we raise an exception here, EM dies, which causes problems (e.g., # other Bud instances in the same process will crash). Ignoring the # error isn't best though -- we should do better (#74). puts "Exception handling network messages: #{e}" puts e.backtrace puts "Inbound messages:" @bud.inbound.each do |chn_name, t| puts " #{t.inspect} (channel: #{chn_name})" end @bud.inbound.clear end @bud.rtracer.sleep if @bud.options[:rtrace] end def recv_message(obj) unless (obj.class <= Array and obj.length == 3 and @bud.tables.include?(obj[0].to_sym) and obj[1].class <= Array and obj[2].class <= Array) raise Bud::Error, "bad inbound message of class #{obj.class}: #{obj.inspect}" end # Deserialize any nested marshalled values tbl_name, tuple, marshall_indexes = obj marshall_indexes.each do |i| if i < 0 || i >= tuple.length raise Bud::Error, "bad inbound message: marshalled value at index #{i}, #{obj.inspect}" end tuple[i] = Marshal.load(tuple[i]) end obj = [tbl_name, tuple] @bud.rtracer.recv(obj) if @bud.options[:rtrace] @filter_buf[obj[0].to_sym] ||= [] @filter_buf[obj[0].to_sym] << obj[1] end end
29.513158
95
0.625502
28eda08df051059652371c5f3cbf178ae4902ba3
4,320
# frozen_string_literal: true # # Copyright:: 2020, Chef Software, Inc. # Author:: Tim Smith (<[email protected]>) # # 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. # module RuboCop module Cop module Chef module ChefStyle # Use the platform_family?() helpers instead of node['os] == 'foo' for platform_families that match one-to-one with OS values. These helpers are easier to read and can accept multiple platform arguments, which greatly simplifies complex platform logic. All values of `os` from Ohai match one-to-one with `platform_family` values except for `linux`, which has no single equivalent `plaform_family`. # # @example # # # bad # node['os'] == 'darwin' # node['os'] == 'windows' # node['os'].eql?('aix') # %w(netbsd openbsd freebsd).include?(node['os']) # # # good # platform_family?('mac_os_x') # platform_family?('windows') # platform_family?('aix') # platform_family?('netbsd', 'openbsd', 'freebsd) # class UnnecessaryOSCheck < Base extend AutoCorrector MSG = "Use the platform_family?() helpers instead of node['os] == 'foo' for platform_families that match 1:1 with OS values." # sorted list of all the os values that match 1:1 with a platform_family UNNECESSARY_OS_VALUES = %w(aix darwin dragonflybsd freebsd netbsd openbsd solaris2 windows).freeze def_node_matcher :os_equals?, <<-PATTERN (send (send (send nil? :node) :[] (str "os") ) ${:== :!=} $str ) PATTERN def_node_matcher :os_eql?, <<-PATTERN (send (send (send nil? :node) :[] (str "os") ) :eql? $str ) PATTERN def_node_matcher :os_include?, <<-PATTERN (send $(array ...) :include? (send (send nil? :node) :[] (str "os"))) PATTERN def on_send(node) os_equals?(node) do |operator, val| return unless UNNECESSARY_OS_VALUES.include?(val.value) add_offense(node, message: MSG, severity: :refactor) do |corrector| corrected_string = (operator == :!= ? '!' : '') + "platform_family?('#{sanitized_platform(val.value)}')" corrector.replace(node, corrected_string) end end os_eql?(node) do |val| return unless UNNECESSARY_OS_VALUES.include?(val.value) add_offense(node, message: MSG, severity: :refactor) do |corrector| corrected_string = "platform_family?('#{sanitized_platform(val.value)}')" corrector.replace(node, corrected_string) end end os_include?(node) do |val| array_of_plats = array_from_ast(val) # see if all the values in the .include? usage are in our list of 1:1 platform family to os values return unless (UNNECESSARY_OS_VALUES & array_of_plats) == array_of_plats add_offense(node, message: MSG, severity: :refactor) do |corrector| platforms = val.values.map { |x| x.str_type? ? "'#{sanitized_platform(x.value)}'" : x.source } corrected_string = "platform_family?(#{platforms.join(', ')})" corrector.replace(node, corrected_string) end end end # return the passed value unless the value is darwin and then return mac_os_x def sanitized_platform(plat) plat == 'darwin' ? 'mac_os_x' : plat end # given an ast array spit out a ruby array def array_from_ast(ast) vals = [] ast.each_child_node { |x| vals << x.value } vals.sort end end end end end end
41.941748
405
0.60162
e8a89b4725609b25e8229e60315c64cb36ff9eb6
1,338
module Applicants class CreateStudentService def initialize(applicant) @applicant = applicant @course = applicant.course end def create(tag) Applicant.transaction do student = create_new_student(tag) # Make sure the tag is in the school's list of founder tags. # This is useful for retrieval in the school admin interface. unless tag.in?(school.founder_tag_list) school.founder_tag_list.add(tag) school.save! end # Delete the applicant @applicant.destroy! student end end private def create_new_student(tag) # Create a user and generate a login token. user = school.users.with_email(@applicant.email).first_or_create!(email: @applicant.email, title: 'Student') user.regenerate_login_token if user.login_token.blank? user.update!(name: @applicant.name) # Create the team and tag it. team = Startup.create!(name: @applicant.name, level: first_level) team.tag_list.add(tag) team.save! # Finally, create a student profile for the user. Founder.create!(user: user, startup: team) end def school @school ||= @course.school end def first_level @first_level ||= @course.levels.find_by(number: 1) end end end
25.730769
114
0.647235
4a4bc55c3d4da7f59f941e1cbd50e61e8797f982
2,583
require 'active_record' ActiveRecord::Migration.verbose = false ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => ':memory:') class CreateModelsForTest < ActiveRecord::Migration[5.2] def self.up create_table :users do |t| t.string :name t.integer :posts_count, :default => 0 t.integer :posts_ar_count, :default => 0 t.integer :followers_count, :default => 0 t.integer :users_i_follow_count, :default => 0 t.integer :bogus_followed_count, :default => 0 t.integer :reviews_sum, :default => 0 end create_table :follows do |t| t.integer :user_id t.integer :followee_id t.string :followee_type end create_table :posts do |t| t.string :body t.belongs_to :user end create_table :reviews do |t| t.integer :score t.belongs_to :user end end def self.down drop_table(:users) drop_table(:posts) drop_table(:follows) drop_table(:reviews) end end class User < ActiveRecord::Base has_many :posts has_many :reviews def calculate_posts_count posts.count end def calculate_bogus_follow_count 101 end end class Follow < ActiveRecord::Base belongs_to :user belongs_to :followee, polymorphic: true include Counter::Cache counter_cache_on column: :followers_count, relation: :followee, polymorphic: true, recalculation: false counter_cache_on column: :bogus_followed_count, relation: :followee, polymorphic: true, method: :calculate_bogus_follow_count, recalculation: true counter_cache_on column: :users_i_follow_count, relation: :user, if: ->(follow) { follow.followee_type == "User" }, recalculation: false end class Post < ActiveRecord::Base belongs_to :user include Counter::Cache counter_cache_on column: :posts_count, relation: :user, relation_class_name: "User", method: :calculate_posts_count, recalculation: false counter_cache_on column: :posts_ar_count, relation: :user, relation_class_name: "User", recalculation: false end class Review < ActiveRecord::Base belongs_to :user include Counter::Cache counter_cache_on column: :reviews_sum, relation: :user, increment_by: ->(review) { review.score }, recalculation: false end
23.916667
87
0.625629
18eb69f2e7864a7361939e8fd20f29deb9d43c36
547
module Intrigue module Ident module Check class Nagios < Intrigue::Ident::Check::Base def generate_checks(url) [ { type: "fingerprint", category: "application", tags: ["COTS","Administrative","Development"], vendor: "Nagios", product:"Nagios", description:"Nagios", version: nil, match_type: :content_headers, match_content: /nagios/i, paths: [ { path: "#{url}", follow_redirects: true } ], inference: false } ] end end end end end
19.535714
62
0.575868
33a649ebde80c8b952ad3122dafba872427e79f6
1,111
# This file keeps logic to load configurations of the entire library module Frisky @@redis = nil @@config = nil @@log = nil def config=(config) @@config = config @@redis = Redis.new(host: config['redis']) if config['redis'] # Github if config['github'] and config['github']['keys'] Frisky.config['github']['keys'].map! { |data| data.split(/:/) } def Octokit.client_id Octokit.client_id, Octokit.client_secret = Frisky.config['github']['keys'].sample super end end if defined? CONFIG_EXTENSIONS CONFIG_EXTENSIONS.each do |method| self.send(method, config) end end end def config_file(file) Frisky.config = YAML.load_file(file) end def config; @@config; end def redis; @@redis; end def log; if @@log == nil @@log = ::Logger.new(STDOUT) @@log.datetime_format = "%H:%M:%S" @@log.formatter = proc do |severity, datetime, progname, msg| "[#{severity}] #{datetime}: #{msg}\n" end end @@log end extend self end
22.22
89
0.576958
7a627b0cea56ae290299d7c7915ea84ad8eb1624
2,100
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::BatchAI::Mgmt::V2017_09_01_preview module Models # # Use this to prepare the VM. NOTE: The volumes specified in mountVolumes # are mounted first and then the setupTask is run. Therefore the setup task # can use local mountPaths in its execution. # class NodeSetup include MsRestAzure # @return [SetupTask] Specifies a setup task which can be used to # customize the compute nodes of the cluster. The NodeSetup task runs # every time a VM is rebooted. For that reason the task code needs to be # idempotent. Generally it is used to either download static data that is # required for all jobs that run on the cluster VMs or to # download/install software. attr_accessor :setup_task # @return [MountVolumes] Information on shared volumes to be used by # jobs. attr_accessor :mount_volumes # # Mapper for NodeSetup class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'NodeSetup', type: { name: 'Composite', class_name: 'NodeSetup', model_properties: { setup_task: { client_side_validation: true, required: false, serialized_name: 'setupTask', type: { name: 'Composite', class_name: 'SetupTask' } }, mount_volumes: { client_side_validation: true, required: false, serialized_name: 'mountVolumes', type: { name: 'Composite', class_name: 'MountVolumes' } } } } } end end end end
30.882353
79
0.572381
333a01a51d12f805a9691a040256b2ecb79af6a5
4,088
module FHIR module Deserializer module ConceptMap include FHIR::Formats::Utilities include FHIR::Deserializer::Utilities def parse_xml_entry_OtherConceptComponent(entry) return nil unless entry model = FHIR::ConceptMap::OtherConceptComponent.new self.parse_element_data(model, entry) set_model_data(model, 'concept', entry.at_xpath('./fhir:concept/@value').try(:value)) set_model_data(model, 'system', entry.at_xpath('./fhir:system/@value').try(:value)) set_model_data(model, 'code', entry.at_xpath('./fhir:code/@value').try(:value)) model end def parse_xml_entry_ConceptMapConceptMapComponent(entry) return nil unless entry model = FHIR::ConceptMap::ConceptMapConceptMapComponent.new self.parse_element_data(model, entry) set_model_data(model, 'system', entry.at_xpath('./fhir:system/@value').try(:value)) set_model_data(model, 'code', entry.at_xpath('./fhir:code/@value').try(:value)) set_model_data(model, 'equivalence', entry.at_xpath('./fhir:equivalence/@value').try(:value)) set_model_data(model, 'comments', entry.at_xpath('./fhir:comments/@value').try(:value)) set_model_data(model, 'product', entry.xpath('./fhir:product').map {|e| parse_xml_entry_OtherConceptComponent(e)}) model end def parse_xml_entry_ConceptMapConceptComponent(entry) return nil unless entry model = FHIR::ConceptMap::ConceptMapConceptComponent.new self.parse_element_data(model, entry) set_model_data(model, 'system', entry.at_xpath('./fhir:system/@value').try(:value)) set_model_data(model, 'code', entry.at_xpath('./fhir:code/@value').try(:value)) set_model_data(model, 'dependsOn', entry.xpath('./fhir:dependsOn').map {|e| parse_xml_entry_OtherConceptComponent(e)}) set_model_data(model, 'map', entry.xpath('./fhir:map').map {|e| parse_xml_entry_ConceptMapConceptMapComponent(e)}) model end def parse_xml_entry(entry) return nil unless entry model = self.new self.parse_element_data(model, entry) self.parse_resource_data(model, entry) set_model_data(model, 'identifier', entry.at_xpath('./fhir:identifier/@value').try(:value)) set_model_data(model, 'versionNum', entry.at_xpath('./fhir:version/@value').try(:value)) set_model_data(model, 'name', entry.at_xpath('./fhir:name/@value').try(:value)) set_model_data(model, 'publisher', entry.at_xpath('./fhir:publisher/@value').try(:value)) set_model_data(model, 'telecom', entry.xpath('./fhir:telecom').map {|e| FHIR::Contact.parse_xml_entry(e)}) set_model_data(model, 'description', entry.at_xpath('./fhir:description/@value').try(:value)) set_model_data(model, 'copyright', entry.at_xpath('./fhir:copyright/@value').try(:value)) set_model_data(model, 'status', entry.at_xpath('./fhir:status/@value').try(:value)) set_model_data(model, 'experimental', entry.at_xpath('./fhir:experimental/@value').try(:value)) set_model_data(model, 'date', entry.at_xpath('./fhir:date/@value').try(:value)) set_model_data(model, 'source', FHIR::ResourceReference.parse_xml_entry(entry.at_xpath('./fhir:source'))) set_model_data(model, 'target', FHIR::ResourceReference.parse_xml_entry(entry.at_xpath('./fhir:target'))) set_model_data(model, 'concept', entry.xpath('./fhir:concept').map {|e| parse_xml_entry_ConceptMapConceptComponent(e)}) model end end end end
65.935484
136
0.60225
26ed5d5fc0f3f1f6b5e1e33087a14f0cd1a680c3
1,682
class Testkube < Formula desc "Kubernetes-native framework for test definition and execution" homepage "https://testkube.io" url "https://github.com/kubeshop/testkube/archive/refs/tags/v1.1.0.tar.gz" sha256 "dd0f2e27f836f2baab8ee0ddaa107d411eb6a9b3dfeeb8182934dc4cd99493dc" license "MIT" bottle do sha256 cellar: :any_skip_relocation, arm64_monterey: "5472c21536cc96b8c604d8206ce2cf6fd8ab4d9a7a4c89b06188edad2ccee81e" sha256 cellar: :any_skip_relocation, arm64_big_sur: "5472c21536cc96b8c604d8206ce2cf6fd8ab4d9a7a4c89b06188edad2ccee81e" sha256 cellar: :any_skip_relocation, monterey: "7aab954a2f73385966b0c785c28b3d82044b66ec02e7e51f1ad0da99568f0e9f" sha256 cellar: :any_skip_relocation, big_sur: "7aab954a2f73385966b0c785c28b3d82044b66ec02e7e51f1ad0da99568f0e9f" sha256 cellar: :any_skip_relocation, catalina: "7aab954a2f73385966b0c785c28b3d82044b66ec02e7e51f1ad0da99568f0e9f" sha256 cellar: :any_skip_relocation, x86_64_linux: "850787cc6f8108252c515e535473bee53fc90eb12f6649f2aa8d3e3fd5f40714" end depends_on "go" => :build def install ENV["CGO_ENABLED"] = "0" ldflags = %W[ -s -w -X main.version=#{version} -X main.builtBy=#{tap.user} ] system "go", "build", *std_go_args(output: bin/"kubectl-testkube", ldflags: ldflags), "cmd/kubectl-testkube/main.go" end test do output = shell_output("#{bin}/kubectl-testkube get tests 2>&1", 1) assert_match("error: invalid configuration: no configuration has been provided", output) output = shell_output("#{bin}/kubectl-testkube help") assert_match("Testkube entrypoint for kubectl plugin", output) end end
43.128205
123
0.763377
7abf0d8f719adffb193d9e4a25b5a17159b65d8c
5,872
module Refile module Attachment # Macro which generates accessors for the given column which make it # possible to upload and retrieve previously uploaded files through the # generated accessors. # # The `raise_errors` option controls whether assigning an invalid file # should immediately raise an error, or save the error and defer handling # it until later. # # Given a record with an attachment named `image`, the following methods # will be added: # # - `image` # - `image=` # - `remove_image` # - `remove_image=` # - `remote_image_url` # - `remote_image_url=` # - `image_url` # - `image_presigned_url` # # @example # class User # extend Refile::Attachment # # attachment :image # attr_accessor :image_id # end # # @param [String] name Name of the column which accessor are generated for # @param [#to_s] cache Name of a backend in {Refile.backends} to use as transient cache # @param [#to_s] store Name of a backend in {Refile.backends} to use as permanent store # @param [true, false] raise_errors Whether to raise errors in case an invalid file is assigned # @param [Symbol, nil] type The type of file that can be uploaded, see {Refile.types} # @param [String, Array<String>, nil] extension Limit the uploaded file to the given extension or list of extensions # @param [String, Array<String>, nil] content_type Limit the uploaded file to the given content type or list of content types # @return [void] def attachment(name, cache: :cache, store: :store, raise_errors: true, type: nil, extension: nil, content_type: nil) definition = AttachmentDefinition.new(name, cache: cache, store: store, raise_errors: raise_errors, type: type, extension: extension, content_type: content_type ) define_singleton_method :"#{name}_attachment_definition" do definition end mod = Module.new do attacher = :"#{name}_attacher" define_method :"#{name}_attachment_definition" do definition end define_method attacher do ivar = :"@#{attacher}" instance_variable_get(ivar) or instance_variable_set(ivar, Attacher.new(definition, self)) end define_method "#{name}=" do |value| send(attacher).set(value) end define_method name do send(attacher).get end define_method "remove_#{name}=" do |remove| send(attacher).remove = remove end define_method "remove_#{name}" do send(attacher).remove end define_method "remote_#{name}_url=" do |url| send(attacher).download(url) end define_method "remote_#{name}_url" do end define_method "#{name}_url" do |*args| Refile.attachment_url(self, name, *args) end define_method "presigned_#{name}_url" do |expires_in = 900| attachment = send(attacher) attachment.store.object(attachment.id).presigned_url(:get, expires_in: expires_in) unless attachment.id.nil? end define_method "#{name}_data" do send(attacher).data end define_singleton_method("to_s") { "Refile::Attachment(#{name})" } define_singleton_method("inspect") { "Refile::Attachment(#{name})" } end include mod end # Macro which generates accessors in pure Ruby classes for assigning # multiple attachments at once. This is primarily useful together with # multiple file uploads. There is also an Active Record version of # this macro. # # The name of the generated accessors will be the name of the association # (represented by an attribute accessor) and the name of the attachment in # the associated class. So if a `Post` accepts attachments for `images`, and # the attachment in the `Image` class is named `file`, then the accessors will # be named `images_files`. # # @example in associated class # class Document # extend Refile::Attachment # attr_accessor :file_id # # attachment :file # # def initialize(attributes = {}) # self.file = attributes[:file] # end # end # # @example in class # class Post # extend Refile::Attachment # include ActiveModel::Model # # attr_accessor :documents # # accepts_attachments_for :documents, accessor_prefix: 'documents_files', collection_class: Document # # def initialize(attributes = {}) # @documents = attributes[:documents] || [] # end # end # # @example in form # <%= form_for @post do |form| %> # <%= form.attachment_field :documents_files, multiple: true %> # <% end %> # # @param [Symbol] collection_name Name of the association # @param [Class] collection_class Associated class # @param [String] accessor_prefix Name of the generated accessors # @param [Symbol] attachment Name of the attachment in the associated class # @param [Boolean] append If true, new files are appended instead of replacing the entire list of associated classes. # @return [void] def accepts_attachments_for(collection_name, collection_class:, accessor_prefix:, attachment: :file, append: false) include MultipleAttachments.new( collection_name, collection_class: collection_class, name: accessor_prefix, attachment: attachment, append: append ) end end end
35.161677
135
0.617337
ffcb05f254ec32ee219a5f080b603e385e9fb2c9
748
Pod::Spec.new do |s| s.name = 'BPForms' s.version = '1.0.1' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'Dynamic forms for iPhone/iPad - iOS 6, 7 and later.' s.homepage = 'https://github.com/bpoplauschi/BPForms' s.author = { 'Bogdan Poplauschi' => '[email protected]' } s.source = { :git => 'https://github.com/bpoplauschi/BPForms.git', :tag => "#{s.version}" } s.description = 'Inspired from BZGFormViewController, BPForms allows easily creating beautiful dynamic forms.' s.requires_arc = true s.platform = :ios, "6.0" s.preserve_paths = 'README*' s.public_header_files = 'BPForms/**/*.h' s.source_files = 'BPForms/**/*.{h,m}' s.dependency 'Masonry' end
31.166667
112
0.621658
f7323e6b02a7e04885053c221b5e2c28c0d8fc3b
3,593
# frozen_string_literal: true # encoding: utf-8 # Copyright (C) 2017-2020 MongoDB 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. module Mongo class Session # An object representing the server-side session. # # @api private # # @since 2.5.0 class ServerSession # Regex for removing dashes from the UUID string. # # @since 2.5.0 DASH_REGEX = /\-/.freeze # Pack directive for the UUID. # # @since 2.5.0 UUID_PACK = 'H*'.freeze # The last time the server session was used. # # @since 2.5.0 attr_reader :last_use # The current transaction number. # # When a transaction is active, all operations in that transaction # use the same transaction number. If the entire transaction is restarted # (for example, by Session#with_transaction, in which case it would # also invoke the block provided to it again), each transaction attempt # has its own transaction number. # # Transaction number is also used outside of transactions for # retryable writes. In this case, each write operation has its own # transaction number, but retries of a write operation use the same # transaction number as the first write (which is how the server # knows that subsequent writes are retries and should be ignored if # the first write succeeded on the server but was not read by the # client, for example). # # @since 2.5.0 attr_reader :txn_num # Initialize a ServerSession. # # @example # ServerSession.new # # @since 2.5.0 def initialize set_last_use! session_id @txn_num = 0 end # Update the last_use attribute of the server session to now. # # @example Set the last use field to now. # server_session.set_last_use! # # @return [ Time ] The last time the session was used. # # @since 2.5.0 def set_last_use! @last_use = Time.now end # The session id of this server session. # # @example Get the session id. # server_session.session_id # # @return [ BSON::Document ] The session id. # # @since 2.5.0 def session_id @session_id ||= (bytes = [SecureRandom.uuid.gsub(DASH_REGEX, '')].pack(UUID_PACK) BSON::Document.new(id: BSON::Binary.new(bytes, :uuid))) end # Increment the current transaction number and return the new value. # # @return [ Integer ] The updated transaction number. # # @since 2.5.0 def next_txn_num @txn_num += 1 end # Get a formatted string for use in inspection. # # @example Inspect the session object. # session.inspect # # @return [ String ] The session inspection. # # @since 2.5.0 def inspect "#<Mongo::Session::ServerSession:0x#{object_id} session_id=#{session_id} last_use=#{@last_use}>" end end end end
29.211382
104
0.623991
1abe923ea92e2532736b8f566458a0550f00693a
6,278
class Weboob < Formula include Language::Python::Virtualenv desc "Web Outside of Browsers" homepage "https://weboob.org/" url "https://git.weboob.org/weboob/weboob/uploads/7b91875f693b60e93c5976daa051034b/weboob-2.0.tar.gz" mirror "https://files.pythonhosted.org/packages/88/c1/b3423348d8e2a557c7e0d53b5977cf1a382703c7b4d1397876836184b493/weboob-2.0.tar.gz" sha256 "fc8be1f77ad3a53285cef8b20a8b747960c163fad729c56838043d8ddcdfc9b0" revision 2 livecheck do url "https://git.weboob.org/weboob/weboob.git" regex(/^v?(\d+(?:\.(?:\d+|[a-z])+))$/i) end bottle do cellar :any sha256 "c99649e0f0e732c428990bef00a8bf6c9f174d98bab9f16298b2f5d210496275" => :big_sur sha256 "d1a6600484c0292ac57ae427cb1be121848184acecb246639c3a65f2ba5282c4" => :arm64_big_sur sha256 "a4347ac13e479dc024e4fdb27f7403a8b4651aca064401b808d03caa3c76bbe1" => :catalina sha256 "01d9798fee2890b412c663d5a75564299ff1c96b0d62afdd588dc5998c52f418" => :mojave sha256 "2069c0ae93e3e2d8a3b06980640b27fb5169f6e19380ac2c1cbe96bc54d95549" => :high_sierra end depends_on "freetype" depends_on "gnupg" depends_on "jpeg" depends_on "libyaml" depends_on "[email protected]" resource "Babel" do url "https://files.pythonhosted.org/packages/34/18/8706cfa5b2c73f5a549fdc0ef2e24db71812a2685959cff31cbdfc010136/Babel-2.8.0.tar.gz" sha256 "1aac2ae2d0d8ea368fa90906567f5c08463d98ade155c0c4bfedd6a0f7160e38" end resource "certifi" do url "https://files.pythonhosted.org/packages/b8/e2/a3a86a67c3fc8249ed305fc7b7d290ebe5e4d46ad45573884761ef4dea7b/certifi-2020.4.5.1.tar.gz" sha256 "51fcb31174be6e6664c5f69e3e1691a2d72a1a12e90f872cbdb1567eb47b6519" end resource "chardet" do url "https://files.pythonhosted.org/packages/fc/bb/a5768c230f9ddb03acc9ef3f0d4a3cf93462473795d18e9535498c8f929d/chardet-3.0.4.tar.gz" sha256 "84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae" end resource "cssselect" do url "https://files.pythonhosted.org/packages/70/54/37630f6eb2c214cdee2ae56b7287394c8aa2f3bafb8b4eb8c3791aae7a14/cssselect-1.1.0.tar.gz" sha256 "f95f8dedd925fd8f54edb3d2dfb44c190d9d18512377d3c1e2388d16126879bc" end resource "html2text" do url "https://files.pythonhosted.org/packages/6c/f9/033a17d8ea8181aee41f20c74c3b20f1ccbefbbc3f7cd24e3692de99fb25/html2text-2020.1.16.tar.gz" sha256 "e296318e16b059ddb97f7a8a1d6a5c1d7af4544049a01e261731d2d5cc277bbb" end resource "idna" do url "https://files.pythonhosted.org/packages/cb/19/57503b5de719ee45e83472f339f617b0c01ad75cba44aba1e4c97c2b0abd/idna-2.9.tar.gz" sha256 "7588d1c14ae4c77d74036e8c22ff447b26d0fde8f007354fd48a7814db15b7cb" end resource "lxml" do url "https://files.pythonhosted.org/packages/39/2b/0a66d5436f237aff76b91e68b4d8c041d145ad0a2cdeefe2c42f76ba2857/lxml-4.5.0.tar.gz" sha256 "8620ce80f50d023d414183bf90cc2576c2837b88e00bea3f33ad2630133bbb60" end resource "Pillow" do url "https://files.pythonhosted.org/packages/ce/ef/e793f6ffe245c960c42492d0bb50f8d14e2ba223f1922a5c3c81569cec44/Pillow-7.1.2.tar.gz" sha256 "a0b49960110bc6ff5fead46013bcb8825d101026d466f3a4de3476defe0fb0dd" end resource "python-dateutil" do url "https://files.pythonhosted.org/packages/be/ed/5bbc91f03fa4c839c4c7360375da77f9659af5f7086b7a7bdda65771c8e0/python-dateutil-2.8.1.tar.gz" sha256 "73ebfe9dbf22e832286dafa60473e4cd239f8592f699aa5adaf10050e6e1823c" end resource "pytz" do url "https://files.pythonhosted.org/packages/f4/f6/94fee50f4d54f58637d4b9987a1b862aeb6cd969e73623e02c5c00755577/pytz-2020.1.tar.gz" sha256 "c35965d010ce31b23eeb663ed3cc8c906275d6be1a34393a1d73a41febf4a048" end resource "PyYAML" do url "https://files.pythonhosted.org/packages/64/c2/b80047c7ac2478f9501676c988a5411ed5572f35d1beff9cae07d321512c/PyYAML-5.3.1.tar.gz" sha256 "b8eac752c5e14d3eca0e6dd9199cd627518cb5ec06add0de9d32baeee6fe645d" end resource "requests" do url "https://files.pythonhosted.org/packages/f5/4f/280162d4bd4d8aad241a21aecff7a6e46891b905a4341e7ab549ebaf7915/requests-2.23.0.tar.gz" sha256 "b3f43d496c6daba4493e7c431722aeb7dbc6288f52a6e04e7b6023b0247817e6" end resource "six" do url "https://files.pythonhosted.org/packages/21/9f/b251f7f8a76dec1d6651be194dfba8fb8d7781d10ab3987190de8391d08e/six-1.14.0.tar.gz" sha256 "236bdbdce46e6e6a3d61a337c0f8b763ca1e8717c03b369e87a7ec7ce1319c0a" end resource "Unidecode" do url "https://files.pythonhosted.org/packages/b1/d6/7e2a98e98c43cf11406de6097e2656d31559f788e9210326ce6544bd7d40/Unidecode-1.1.1.tar.gz" sha256 "2b6aab710c2a1647e928e36d69c21e76b453cd455f4e2621000e54b2a9b8cce8" end resource "urllib3" do url "https://files.pythonhosted.org/packages/05/8c/40cd6949373e23081b3ea20d5594ae523e681b6f472e600fbc95ed046a36/urllib3-1.25.9.tar.gz" sha256 "3018294ebefce6572a474f0604c2021e33b3fd8006ecd11d62107a5d2a963527" end def install venv = virtualenv_create(libexec, "python3") resource("Pillow").stage do inreplace "setup.py" do |s| sdkprefix = MacOS.sdk_path_if_needed ? MacOS.sdk_path : "" s.gsub! "openjpeg.h", "probably_not_a_header_called_this_eh.h" s.gsub! "xcb.h", "probably_not_a_header_called_this_eh.h" s.gsub! "ZLIB_ROOT = None", "ZLIB_ROOT = ('#{sdkprefix}/usr/lib', '#{sdkprefix}/usr/include')" s.gsub! "JPEG_ROOT = None", "JPEG_ROOT = ('#{Formula["jpeg"].opt_prefix}/lib', '#{Formula["jpeg"].opt_prefix}/include')" s.gsub! "FREETYPE_ROOT = None", "FREETYPE_ROOT = ('#{Formula["freetype"].opt_prefix}/lib', " \ "'#{Formula["freetype"].opt_prefix}/include')" end unless MacOS::CLT.installed? ENV.append "CFLAGS", "-I#{MacOS.sdk_path}/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers" end venv.pip_install Pathname.pwd end # Fix "ld: file not found: /usr/lib/system/libsystem_darwin.dylib" for lxml ENV["SDKROOT"] = MacOS.sdk_path if MacOS.version == :sierra res = resources.map(&:name).to_set - ["Pillow"] res.each do |r| venv.pip_install resource(r) end venv.pip_install_and_link buildpath end test do system bin/"weboob-config", "modules" end end
43.296552
145
0.773495
38c7913f5040b8dbc27efb44952954bed7abeb77
1,587
require 'bosh/director/api/controllers/base_controller' module Bosh::Director module Api::Controllers class LinkAddressController < BaseController register DeploymentsSecurity def initialize(config) super(config) @deployment_manager = Api::DeploymentManager.new @link_manager = Api::LinkManager.new end get '/', authorization: :read do validate_query_params(params) query_options = { azs: params['azs'], status: params['status'] } result = { address: @link_manager.link_address(params['link_id'], query_options) } body(json_encode(result)) end private def validate_query_params(params) raise(LinkIdRequiredError, 'Link id is required') unless params.has_key?('link_id') validate_azs(params[:azs]) validate_status(params[:status]) end def validate_azs(azs) return if azs.nil? raise LinkInvalidAzsError, '`azs` param must be array type: `azs[]=`' unless azs.is_a?(Array) az_manager = Api::AvailabilityZoneManager.new azs.each do |az_name| raise(LinkInvalidAzsError, "az #{az_name} is not valid") unless az_manager.is_az_valid?(az_name) end end def validate_status(status) return if status.nil? valid_status = %w(healthy unhealthy all default) raise(LinkInvalidStatusError, "status must be a one of: #{valid_status}") unless status.is_a?(String) && valid_status.include?(status) end end end end
28.854545
142
0.644612
e2a2f8274a84ce07c7a480a8475210198ddfb847
175
#!/usr/bin/env ruby -w require "ripper" require "pp" ARGV.each do |p| f = File.read p puts pp Ripper.lex f puts pp Ripper.sexp_raw f puts pp Ripper.sexp f end
11.666667
22
0.651429
bb6de7189b41bfef646e44b8696879352984ac3e
2,996
# -*- encoding: utf-8 -*- # stub: rails 4.2.2 ruby lib Gem::Specification.new do |s| s.name = "rails".freeze s.version = "4.2.2" s.required_rubygems_version = Gem::Requirement.new(">= 1.8.11".freeze) if s.respond_to? :required_rubygems_version= s.require_paths = ["lib".freeze] s.authors = ["David Heinemeier Hansson".freeze] s.date = "2015-06-16" s.description = "Ruby on Rails is a full-stack web framework optimized for programmer happiness and sustainable productivity. It encourages beautiful code by favoring convention over configuration.".freeze s.email = "[email protected]".freeze s.homepage = "http://www.rubyonrails.org".freeze s.licenses = ["MIT".freeze] s.required_ruby_version = Gem::Requirement.new(">= 1.9.3".freeze) s.rubygems_version = "2.6.1".freeze s.summary = "Full-stack web application framework.".freeze s.installed_by_version = "2.6.1" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<activesupport>.freeze, ["= 4.2.2"]) s.add_runtime_dependency(%q<actionpack>.freeze, ["= 4.2.2"]) s.add_runtime_dependency(%q<actionview>.freeze, ["= 4.2.2"]) s.add_runtime_dependency(%q<activemodel>.freeze, ["= 4.2.2"]) s.add_runtime_dependency(%q<activerecord>.freeze, ["= 4.2.2"]) s.add_runtime_dependency(%q<actionmailer>.freeze, ["= 4.2.2"]) s.add_runtime_dependency(%q<activejob>.freeze, ["= 4.2.2"]) s.add_runtime_dependency(%q<railties>.freeze, ["= 4.2.2"]) s.add_runtime_dependency(%q<bundler>.freeze, ["< 2.0", ">= 1.3.0"]) s.add_runtime_dependency(%q<sprockets-rails>.freeze, [">= 0"]) else s.add_dependency(%q<activesupport>.freeze, ["= 4.2.2"]) s.add_dependency(%q<actionpack>.freeze, ["= 4.2.2"]) s.add_dependency(%q<actionview>.freeze, ["= 4.2.2"]) s.add_dependency(%q<activemodel>.freeze, ["= 4.2.2"]) s.add_dependency(%q<activerecord>.freeze, ["= 4.2.2"]) s.add_dependency(%q<actionmailer>.freeze, ["= 4.2.2"]) s.add_dependency(%q<activejob>.freeze, ["= 4.2.2"]) s.add_dependency(%q<railties>.freeze, ["= 4.2.2"]) s.add_dependency(%q<bundler>.freeze, ["< 2.0", ">= 1.3.0"]) s.add_dependency(%q<sprockets-rails>.freeze, [">= 0"]) end else s.add_dependency(%q<activesupport>.freeze, ["= 4.2.2"]) s.add_dependency(%q<actionpack>.freeze, ["= 4.2.2"]) s.add_dependency(%q<actionview>.freeze, ["= 4.2.2"]) s.add_dependency(%q<activemodel>.freeze, ["= 4.2.2"]) s.add_dependency(%q<activerecord>.freeze, ["= 4.2.2"]) s.add_dependency(%q<actionmailer>.freeze, ["= 4.2.2"]) s.add_dependency(%q<activejob>.freeze, ["= 4.2.2"]) s.add_dependency(%q<railties>.freeze, ["= 4.2.2"]) s.add_dependency(%q<bundler>.freeze, ["< 2.0", ">= 1.3.0"]) s.add_dependency(%q<sprockets-rails>.freeze, [">= 0"]) end end
49.114754
207
0.650534
1c93f541655067e46cc9aed689dd03641319d527
678
cask 'keepassxc' do version '2.2.2' sha256 'e9f80042d0aa1d19e5f20f492224895138cd752cd0a963c4dad1e42e1544a4dd' # github.com/keepassxreboot/keepassxc was verified as official when first introduced to the cask url "https://github.com/keepassxreboot/keepassxc/releases/download/#{version}/KeePassXC-#{version}.dmg" appcast 'https://github.com/keepassxreboot/keepassxc/releases.atom', checkpoint: '6776dc2b09e6dfb93a04ff19f0b538f8e7c112125ee13494fd2ece9772a7c5e7' name 'KeePassXC' homepage 'https://keepassxc.org/' gpg "#{url}.sig", key_url: 'https://keepassxc.org/keepassxc_master_signing_key.asc' app 'KeePassXC.app' zap delete: '~/.keepassxc' end
39.882353
105
0.775811
79364f1d0a6f4cbf037e6373300558b969c928a7
1,744
require "spec_helper" describe VideoBlur::Screen do describe "ratio" do let(:video) { VideoBlur::Video.new(input: "spec/resources/sample.mp4", output: nil) } context "video is the same size as the screen" do before(:each) do allow(video).to receive(:size).and_return("1440x815") end it "returns 1.0" do expect(VideoBlur::Screen.new(width: 1440, height: 815).ratio(video: video)).to eq(1.0) end end context "video is wider than the screen" do before(:each) do allow(video).to receive(:size).and_return("2880x815") end it "returns 2.0" do expect(VideoBlur::Screen.new(width: 1440, height: 815).ratio(video: video)).to eq(2.0) end end context "video is taller than the screen" do before(:each) do allow(video).to receive(:size).and_return("1440x1630") end it "returns 2.0" do expect(VideoBlur::Screen.new(width: 1440, height: 815).ratio(video: video)).to eq(2.0) end end context "video is smaller than the screen" do before(:each) do allow(video).to receive(:size).and_return("720x407") end it "returns 1.0" do expect(VideoBlur::Screen.new(width: 1440, height: 815).ratio(video: video)).to eq(1.0) end end context "nil values" do it "sets default values" do screen = VideoBlur::Screen.new(width: nil, height: nil) expect(screen.ratio(video: video)).to eq(1.0) end end context "missing values" do it "sets default values" do screen = VideoBlur::Screen.new expect(screen.ratio(video: video)).to eq(1.0) end end end end
28.590164
94
0.599197
1cf4692c605ae4f950e416c8eca9987db2658fb4
624
require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') require File.expand_path(File.dirname(__FILE__) + '/../../../../lib/sniffles/sniffers/cms/xcart') describe Sniffles::Sniffers::Xcart do describe "#output" do context "xcart", :vcr => { :cassette_name => 'exprodirect_com' } do let(:xcart) { described_class.new(page_body("http://www.exprodirect.com/")) } it { xcart.output[:found].should eq true } end context "not xcart" do let(:blank) { described_class.new(empty_html_doc) } it { blank.output[:found].should eq false } end end end
34.666667
97
0.637821
ff3807763062e1f9018dcfbbdf144c6c52745b46
855
# # Be sure to run `pod lib lint UYEditor.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 = "UYEditor" s.version = "0.3.7" s.summary = "UYEditor" s.description = <<-DESC #UYEditor DESC s.homepage = "https://github.com/youyuedu/UYEditor" s.license = 'MIT' s.author = { "winddpan" => "[email protected]" } s.source = { :git => "https://github.com/youyuedu/UYEditor.git", :tag => s.version.to_s } s.platform = :ios, '7.0' s.requires_arc = true s.resources = 'iOS/HTML/*', 'iOS/UYEditor.xcassets' s.source_files = 'iOS/Source/**/*.{h,m}' s.frameworks = 'UIKit', 'Foundation' end
29.482759
99
0.625731
39bca7c464bbf020d38ed6aa31d822287e1979f6
1,658
require 'test_helper' class OrderTest < ActiveSupport::TestCase test '::order(column.asc)' do assert_sql(<<~SQL, Property.order(Property.arel_table[:id].asc)) SELECT "properties".* FROM "properties" ORDER BY "properties"."id" ASC SQL end test '::order(column1.asc, column2.asc)' do assert_sql(<<~SQL, Property.order(Property.arel_table[:id].asc, Property.arel_table[:name].asc)) SELECT "properties".* FROM "properties" ORDER BY "properties"."id" ASC, "properties"."name" ASC SQL end test '::order(column.desc)' do assert_sql(<<~SQL, Property.order(Property.arel_table[:id].desc)) SELECT "properties".* FROM "properties" ORDER BY "properties"."id" DESC SQL end test '::order(column.asc(:nulls_first))' do assert_sql(<<~SQL, Property.order(Property.arel_table[:id].asc(:nulls_first))) SELECT "properties".* FROM "properties" ORDER BY "properties"."id" ASC NULLS FIRST SQL end test '::order(column.asc(:nulls_last))' do assert_sql(<<~SQL, Property.order(Property.arel_table[:id].asc(:nulls_last))) SELECT "properties".* FROM "properties" ORDER BY "properties"."id" ASC NULLS LAST SQL end test '::order(column.desc(:nulls_first))' do assert_sql(<<~SQL, Property.order(Property.arel_table[:id].desc(:nulls_first))) SELECT "properties".* FROM "properties" ORDER BY "properties"."id" DESC NULLS FIRST SQL end test '::order(column.desc(:nulls_last))' do assert_sql(<<~SQL, Property.order(Property.arel_table[:id].desc(:nulls_last))) SELECT "properties".* FROM "properties" ORDER BY "properties"."id" DESC NULLS LAST SQL end end
35.276596
101
0.680941
26db5db83fe2a8e8362b12e0fe00359d3eea79db
354
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::EventHub::Mgmt::V2017_04_01 module Models # # Defines values for SkuName # module SkuName Basic = "Basic" Standard = "Standard" end end end
20.823529
70
0.683616
26630ad55db72ccdcb210770206579c755f67c55
2,557
module SymmetricEncryption module Generator # Common internal method for generating accessors for decrypted accessors # Primarily used by extensions def self.generate_decrypted_accessors(model, decrypted_name, encrypted_name, options) options = options.dup random_iv = options.delete(:random_iv) || false compress = options.delete(:compress) || false type = options.delete(:type) || :string raise(ArgumentError, "SymmetricEncryption Invalid options #{options.inspect} when encrypting '#{decrypted_name}'") unless options.empty? raise(ArgumentError, "Invalid type: #{type.inspect}. Valid types: #{SymmetricEncryption::COERCION_TYPES.inspect}") unless SymmetricEncryption::COERCION_TYPES.include?(type) if model.const_defined?(:EncryptedAttributes, _search_ancestors = false) mod = model.const_get(:EncryptedAttributes) else mod = model.const_set(:EncryptedAttributes, Module.new) model.send(:include, mod) end # Generate getter and setter methods mod.module_eval(<<~ACCESSORS, __FILE__, __LINE__ + 1) # Set the un-encrypted field # Also updates the encrypted field with the encrypted value # Freeze the decrypted field value so that it is not modified directly def #{decrypted_name}=(value) v = SymmetricEncryption::Coerce.coerce(value, :#{type}).freeze return if (@#{decrypted_name} == v) && !v.nil? && !(v == '') self.#{encrypted_name} = @stored_#{encrypted_name} = ::SymmetricEncryption.encrypt(v, random_iv: #{random_iv}, compress: #{compress}, type: :#{type}).freeze @#{decrypted_name} = v end # Returns the decrypted value for the encrypted field # The decrypted value is cached and is only decrypted if the encrypted value has changed # If this method is not called, then the encrypted value is never decrypted def #{decrypted_name} if !defined?(@stored_#{encrypted_name}) || (@stored_#{encrypted_name} != self.#{encrypted_name}) @#{decrypted_name} = ::SymmetricEncryption.decrypt(self.#{encrypted_name}.freeze, type: :#{type}).freeze @stored_#{encrypted_name} = self.#{encrypted_name} end @#{decrypted_name} end # Map changes to encrypted value to unencrypted equivalent def #{decrypted_name}_changed? #{encrypted_name}_changed? end ACCESSORS end end end
49.173077
178
0.656629
5db3f7b676feab6afebc2b68d9e5187b5215ed60
187
class AddGbifToNames < ActiveRecord::Migration[6.1] def change add_column :names, :gbif_json, :text, default: nil add_column :names, :gbif_at, :datetime, default: nil end end
26.714286
56
0.721925
6a15ac7a8c096a48d24c4b681f63de13d7f6d605
2,461
# coding: utf-8 Pod::Spec.new do |s| # MARK: - Description s.name = 'SwiftCommons' s.summary = 'A collection of useful utility classes common to different iOS projects.' s.version = '1.3.0' s.platform = :ios s.ios.deployment_target = '9.0' s.swift_version = '4.2' s.cocoapods_version = '>= 1.4.0' s.static_framework = true s.homepage = 'https://github.com/roxiemobile/swift-commons.ios' s.authors = { 'Roxie Mobile Ltd.' => '[email protected]', 'Alexander Bragin' => '[email protected]' } s.license = 'BSD-4-Clause' # MARK: - Configuration s.source = { git: 'https://github.com/roxiemobile/swift-commons.ios.git', tag: s.version.to_s } # MARK: - Modules # The core abstractions and public protocols used for iOS application development. s.subspec 'Abstractions' do |sp| sp.dependency 'SwiftCommonsAbstractions', s.version.to_s end # A collection of reusable components used to simplify the work of writing concurrent and asynchronous code. s.subspec 'Concurrent' do |sp| sp.dependency 'SwiftCommonsConcurrent', s.version.to_s end # A collection of reusable components used to simplify serialization, deserialization and validation operations on data objects. s.subspec 'Data' do |sp| sp.dependency 'SwiftCommonsData', s.version.to_s end # A collection of static classes for debugging and diagnostics of program contracts such as preconditions, postconditions, and invariants. s.subspec 'Diagnostics' do |sp| sp.dependency 'SwiftCommonsDiagnostics', s.version.to_s end # A collection of useful type extensions used for iOS application development. s.subspec 'Extensions' do |sp| sp.dependency 'SwiftCommonsExtensions', s.version.to_s end # A collection of useful classes and Swift language extensions. s.subspec 'Lang' do |sp| sp.dependency 'SwiftCommonsLang', s.version.to_s end # Provides simple abstraction layer over an existing logging frameworks. s.subspec 'Logging' do |sp| sp.dependency 'SwiftCommonsLogging', s.version.to_s end # A collection of Objective-C frameworks, utility classes and 3rd party libraries used by other modules of this library. s.subspec 'ObjC' do |sp| sp.dependency 'SwiftCommonsObjC', s.version.to_s end # NOTE: Protection s.dependency '//+WrongSourceRepository' end
33.712329
140
0.694839
bf1ddebc5937b6c76802cbb0294380807a38c983
5,813
require 'json' require 'fileutils' require_relative 'asset_information' require_relative '../../service/transactor' require_relative '../../defaults' module Emojidex module Data # local caching functionality for collections module CollectionCache include Emojidex::Data::CollectionAssetInformation attr_reader :cache_path, :download_queue attr_accessor :download_threads, :formats, :sizes def setup_cache(path = nil) @formats = Emojidex::Defaults.selected_formats unless @formats @sizes = Emojidex::Defaults.selected_sizes unless @sizes @download_queue = [] @download_threads = 4 # check if cache dir is already set return @cache_path if @cache_path && path.nil? # setup cache @cache_path = File.expand_path((path || Emojidex::Defaults.system_cache_path) + '/emoji') # ENV['EMOJI_CACHE'] = @cache_path FileUtils.mkdir_p(@cache_path) Emojidex::Defaults.sizes.keys.each do |size| FileUtils.mkdir_p(@cache_path + "/#{size}") end # load will expect emoji.json even if it contains no emoji unless File.exist? "#{cache_path}/emoji.json" File.open("#{@cache_path}/emoji.json", 'w') { |f| f.write '[]' } end @cache_path end def load_cache(path = nil) setup_cache(path) load_local_collection(@cache_path) end # Caches emoji to local emoji storage cache # Options: # cache_path: manually specify cache location # formats: formats to cache (default is SVG only) # sizes: sizes to cache (default is px32, but this is irrelivant for SVG) def cache(options = {}) _cache(options) cache_index end # Caches emoji to local emoji storage cache # +regenerates checksums and paths # Options: # cache_path: manually specify cache location # formats: formats to cache (default is SVG only) # sizes: sizes to cache (default is px32, but this is irrelivant for SVG) def cache!(options = {}) _cache(options) generate_paths generate_checksums cache_index end # Updates an index in the specified destination (or the cache path if not specified). # This method reads the existing index, combines the contents with this collection, and # writes the results. def cache_index(destination = nil) destination ||= @cache_path idx = Emojidex::Data::Collection.new idx.r18 = @r18 idx.load_local_collection(destination) if FileTest.exist? "#{destination}/emoji.json" idx.add_emoji @emoji.values idx.write_index(destination) end # [over]writes a sanitized index to the specified destination. # WARNING: This method destroys any index files in the destination. def write_index(destination) idx = @emoji.values.to_json idx = JSON.parse idx idx.each do |moji| moji['paths'] = nil moji['remote_checksums'] = nil moji.delete_if { |_k, v| v.nil? } end File.open("#{destination}/emoji.json", 'w') { |f| f.write idx.to_json } end private def _svg_check_copy(moji) if @vector_source_path != nil src_d = "#{@vector_source_path}/#{moji.code}" src = "#{src_d}.svg" FileUtils.cp(src, @cache_path) if File.exist?(src) && @vector_source_path != @cache_path FileUtils.cp_r(src_d, @cache_path) if File.directory?(src_d) && @vector_source_path != @cache_path # Copies source frames and data files if unpacked @download_queue << { moji: moji, formats: :svg, sizes: [] } unless File.exist?("#{@cache_path}/#{moji.code}.svg") # nothing was copied, get from net return end @download_queue << { moji: moji, formats: :svg, sizes: [] } end def _raster_check_copy(moji, format, sizes) sizes.each do |size| if @raster_source_path != nil src_d = "#{@raster_source_path}/#{size}/#{moji.code}" src = "#{src_d}.#{format}" FileUtils.cp("#{src}", ("#{@cache_path}/#{size}")) if File.exist?(src) && @raster_source_path != @cache_path FileUtils.cp_r(src, @cache_path) if File.directory?(src_d) && @raster_source_path != @cache_path # Copies source frames and data files if unpacked @download_queue << { moji: moji, formats: [format], sizes: [size] } unless File.exist?("#{@cache_path}/#{size}/#{moji.code}.#{format}") # nothing was copied, get from net end end end def _process_download_queue thr = [] @download_queue.each do |dl| thr << Thread.new { _cache_from_net(dl[:moji], dl[:formats], dl[:sizes]) } thr.each(&:join) if thr.length >= (@download_threads - 1) end thr.each(&:join) # grab end of queue end def _cache_from_net(moji, formats, sizes) formats = *formats unless formats.class == Array dls = [] dls << Thread.new { moji.cache(:svg) } if formats.include? :svg dls << Thread.new { moji.cache(:png, sizes) } if formats.include? :png dls.each(&:join) end def _cache(options) setup_cache options[:cache_path] formats = options[:formats] || @formats sizes = options[:sizes] || @sizes @emoji.values.each do |moji| _svg_check_copy(moji) if formats.include? :svg _raster_check_copy(moji, :png, sizes) if formats.include? :png end _process_download_queue @vector_source_path = @cache_path if formats.include? :svg @raster_source_path = @cache_path if formats.include? :png end end end end
37.993464
182
0.61913
623ba3f89b507657ba70f5ddfa96087478fb14eb
636
require_relative '../jdbc_spec_helper' describe 'logstash-output-jdbc: mysql', if: ENV['JDBC_MYSQL_JAR'] do include_context 'rspec setup' include_context 'when initializing' include_context 'when outputting messages' let(:jdbc_jar_env) do 'JDBC_MYSQL_JAR' end let(:systemd_database_service) do 'mysql' end let(:jdbc_settings) do { 'driver_class' => 'com.mysql.jdbc.Driver', 'connection_string' => 'jdbc:mysql://localhost/logstash_output_jdbc_test?user=root', 'driver_jar_path' => ENV[jdbc_jar_env], 'statement' => jdbc_statement, 'max_flush_exceptions' => 1 } end end
24.461538
90
0.698113
1da2496ce62736a72d4b1335c324899bb8ff618a
815
module ScormEngine module Models class DispatchZip < Base # @attr # The external identification of the dispatch. # @return [String] attr_accessor :dispatch_id # @attr # The type of ZIP package to generate. # @return [String] (SCORM12, SCORM2004-3RD, AICC) attr_accessor :type # @attr # # @return [String] attr_accessor :filename # @attr # # @return [String] attr_accessor :body # rubocop:disable Lint/MissingSuper def initialize(options = {}) @options = options.dup @dispatch_id = options[:dispatch_id] @type = options[:type]&.upcase @filename = options[:filename] @body = options[:body] end # rubocop:enable Lint/MissingSuper end end end
22.638889
55
0.586503
7ac6d930ea325646d3f711d80ef68bcddcd83042
7,940
namespace :perf do task :rails_load do ENV["RAILS_ENV"] ||= "production" ENV['RACK_ENV'] = ENV["RAILS_ENV"] ENV["DISABLE_SPRING"] = "true" ENV["SECRET_KEY_BASE"] ||= "foofoofoo" ENV['LOG_LEVEL'] = "FATAL" require 'rails' puts "Booting: #{Rails.env}" %W{ . lib test config }.each do |file| $LOAD_PATH << file end require 'application' Rails.env = ENV["RAILS_ENV"] DERAILED_APP = Rails.application if DERAILED_APP.respond_to?(:initialized?) DERAILED_APP.initialize! unless DERAILED_APP.initialized? else DERAILED_APP.initialize! unless DERAILED_APP.instance_variable_get(:@initialized) end if ENV["DERAILED_SKIP_ACTIVE_RECORD"] && defined? ActiveRecord if defined? ActiveRecord::Tasks::DatabaseTasks ActiveRecord::Tasks::DatabaseTasks.create_current else # Rails 3.2 raise "No valid database for #{ENV['RAILS_ENV']}, please create one" unless ActiveRecord::Base.connection.active?.inspect end ActiveRecord::Migrator.migrations_paths = DERAILED_APP.paths['db/migrate'].to_a ActiveRecord::Migration.verbose = true ActiveRecord::Migrator.migrate(ActiveRecord::Migrator.migrations_paths, nil) end DERAILED_APP.config.consider_all_requests_local = true end task :rack_load do puts "You're not using Rails" puts "You need to tell derailed how to boot your app" puts "In your perf.rake add:" puts puts "namespace :perf do" puts " task :rack_load do" puts " # DERAILED_APP = your code here" puts " end" puts "end" end task :setup do if DerailedBenchmarks.gem_is_bundled?("railties") Rake::Task["perf:rails_load"].invoke else Rake::Task["perf:rack_load"].invoke end TEST_COUNT = (ENV['TEST_COUNT'] || ENV['CNT'] || 1_000).to_i PATH_TO_HIT = ENV["PATH_TO_HIT"] || ENV['ENDPOINT'] || "/" puts "Endpoint: #{ PATH_TO_HIT.inspect }" require 'rack/test' require 'rack/file' DERAILED_APP = DerailedBenchmarks.add_auth(DERAILED_APP) if server = ENV["USE_SERVER"] @port = (3000..3900).to_a.sample puts "Port: #{ @port.inspect }" puts "Server: #{ server.inspect }" thread = Thread.new do Rack::Server.start(app: DERAILED_APP, :Port => @port, environment: "none", server: server) end sleep 1 def call_app(path = File.join("/", PATH_TO_HIT)) cmd = "curl 'http://localhost:#{@port}#{path}' -s --fail 2>&1" response = `#{cmd}` raise "Bad request to #{cmd.inspect} Response:\n#{ response.inspect }" unless $?.success? end else @app = Rack::MockRequest.new(DERAILED_APP) def call_app response = @app.get(PATH_TO_HIT) raise "Bad request: #{ response.body }" unless response.status == 200 response end end end desc "hits the url TEST_COUNT times" task :test => [:setup] do require 'benchmark' Benchmark.bm { |x| x.report("#{TEST_COUNT} requests") { TEST_COUNT.times { call_app } } } end desc "stackprof" task :stackprof => [:setup] do # [:wall, :cpu, :object] begin require 'stackprof' rescue LoadError raise "Add stackprof to your gemfile to continue `gem 'stackprof', group: :development`" end TEST_COUNT = (ENV["TEST_COUNT"] ||= "100").to_i file = "tmp/#{Time.now.iso8601}-stackprof-cpu-myapp.dump" StackProf.run(mode: :cpu, out: file) do Rake::Task["perf:test"].invoke end cmd = "stackprof #{file}" puts "Running `#{cmd}`. Execute `stackprof --help` for more info" puts `#{cmd}` end task :kernel_require_patch do require 'derailed_benchmarks/core_ext/kernel_require.rb' end desc "show memory usage caused by invoking require per gem" task :mem => [:kernel_require_patch, :setup] do puts "## Impact of `require <file>` on RAM" puts puts "Showing all `require <file>` calls that consume #{ENV['CUT_OFF']} MiB or more of RSS" puts "Configure with `CUT_OFF=0` for all entries or `CUT_OFF=5` for few entries" puts "Note: Files only count against RAM on their first load." puts " If multiple libraries require the same file, then" puts " the 'cost' only shows up under the first library" puts call_app TOP_REQUIRE.print_sorted_children end desc "outputs memory usage over time" task :mem_over_time => [:setup] do require 'get_process_mem' puts "PID: #{Process.pid}" ram = GetProcessMem.new @keep_going = true begin unless ENV["SKIP_FILE_WRITE"] ruby = `ruby -v`.chomp FileUtils.mkdir_p("tmp") file = File.open("tmp/#{Time.now.iso8601}-#{ruby}-memory-#{TEST_COUNT}-times.txt", 'w') file.sync = true end ram_thread = Thread.new do while @keep_going mb = ram.mb STDOUT.puts mb file.puts mb unless ENV["SKIP_FILE_WRITE"] sleep 5 end end TEST_COUNT.times { call_app } ensure @keep_going = false ram_thread.join file.close unless ENV["SKIP_FILE_WRITE"] end end task :ram_over_time do Kernel.warn("The ram_over_time task is deprecated. Use mem_over_time") Rake::Task["perf:ram_over_time"].invoke end desc "iterations per second" task :ips => [:setup] do require 'benchmark/ips' Benchmark.ips do |x| x.report("ips") { call_app } end end desc "outputs GC::Profiler.report data while app is called TEST_COUNT times" task :gc => [:setup] do GC::Profiler.enable TEST_COUNT.times { call_app } GC::Profiler.report GC::Profiler.disable end task :foo => [:setup] do require 'objspace' call_app before = Hash.new { 0 } after = Hash.new { 0 } after_size = Hash.new { 0 } GC.start GC.disable TEST_COUNT.times { call_app } rvalue_size = GC::INTERNAL_CONSTANTS[:RVALUE_SIZE] ObjectSpace.each_object do |obj| after[obj.class] += 1 memsize = ObjectSpace.memsize_of(obj) + rvalue_size # compensate for API bug memsize = rvalue_size if memsize > 100_000_000_000 after_size[obj.class] += memsize end require 'pp' pp after.sort {|(k,v), (k2, v2)| v2 <=> v } puts "=========" puts puts pp after_size.sort {|(k,v), (k2, v2)| v2 <=> v } end desc "outputs allocated object diff after app is called TEST_COUNT times" task :allocated_objects => [:setup] do call_app GC.start GC.disable start = ObjectSpace.count_objects TEST_COUNT.times { call_app } finish = ObjectSpace.count_objects GC.enable finish.each do |k,v| puts k => (v - start[k]) / TEST_COUNT.to_f end end desc "profiles ruby allocation" task :objects => [:setup] do require 'memory_profiler' call_app GC.start num = Integer(ENV["TEST_COUNT"] || 1) opts = {} opts[:ignore_files] = /#{ENV['IGNORE_FILES_REGEXP']}/ if ENV['IGNORE_FILES_REGEXP'] opts[:allow_files] = "#{ENV['ALLOW_FILES']}" if ENV['ALLOW_FILES'] puts "Running #{num} times" report = MemoryProfiler.report(opts) do num.times { call_app } end report.pretty_print end desc "heap analyzer" task :heap => [:setup] do require 'objspace' file_name = "tmp/#{Time.now.iso8601}-heap.dump" ObjectSpace.trace_object_allocations_start puts "Running #{ TEST_COUNT } times" TEST_COUNT.times { call_app } GC.start puts "Heap file generated: #{ file_name.inspect }" ObjectSpace.dump_all(output: File.open(file_name, 'w')) require 'heapy' Heapy::Analyzer.new(file_name).analyze puts "" puts "Run `$ heapy --help` for more options" puts "" puts "Also try uploading #{file_name.inspect} to http://tenderlove.github.io/heap-analyzer/" end end
27.191781
129
0.63199
794a0eb4398c352092c8ff4f3125b703f0c66fb1
1,583
module LinkingPaths module Acts #:nodoc: module Scribe #:nodoc: def self.included(base) # :nodoc: base.extend ClassMethods end module ClassMethods activity_options ||= {} def record_activity_of(actor, options = {}) include_scribe_instance_methods { has_many :activities, :as => :item, :dependent => :destroy actions = options[:actions] || [:create, :destroy] actions.each do |action| send "after_#{action}" do |record| unless options[:if].kind_of?(Proc) and not options[:if].call(record) user = record.send(activity_options[:actor]) Activity.report(user, action, record) end end end } self.activity_options.merge! :actor => actor end def record_activities(actions = []) raise "record_activities(#{actions.join ','}) has been deprecated. Use Activity.report(user, #{actions.first}), etc. instead." end def include_scribe_instance_methods(&block) unless included_modules.include? InstanceMethods yield if block_given? class_inheritable_accessor :activity_options self.activity_options ||= {} include InstanceMethods end end end module InstanceMethods def record_activity(action) raise "record_activity has been deprecated. Use Activity.report(actor, action, item)." end end end end end
31.039216
136
0.58307
08d56e0fe4785842dde166d48d391c4844ce2cde
3,866
###################################################################### # Copyright (c) 2008-2016, Alliance for Sustainable Energy. # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ###################################################################### module UI # This patch allows all file separators to be accepted and prints an error message if path does not exist. # Decided that the normal behavior of UI.openpanel should not be changed (even for the better). # New alternative method is: UI.open_panel def UI.open_panel(*args) if (args[1]) dir = args[1] if (not dir.empty?) if (RUBY_PLATFORM =~ /mswin/ or RUBY_PLATFORM =~ /mingw/) # Windows # Replace / with \\ for the file separator dir = dir.split("/").join("\\") # Check for and append required final \\ if (dir[dir.length - 1].chr != "\\") dir += "\\" end else # Mac # Check for and append required final / if (dir[dir.length - 1].chr != "/") dir += "/" end end if (not File.directory?(dir)) puts "UI.open_panel received bad directory: " + dir args[1] = "" else args[1] = dir end end end # Allow empty file name to be passed in as a valid argument if (args[2]) if (args[2].strip.empty?) args[2] = "*.*" end else args[2] = "*.*" end #if (path = _openpanel(*args)) if (path = UI.openpanel(*args)) # call the original method # Replace \\ with / for the file separator (works better for saving the path in a registry default) path = path.split("\\").join("/") end return(path) end # Decided that the normal behavior of UI.savepanel should not be changed (even for the better). # New alternative method is: UI.save_panel def UI.save_panel(*args) if (args[1]) dir = args[1] if (not dir.empty?) if (RUBY_PLATFORM =~ /mswin/ or RUBY_PLATFORM =~ /mingw/) # Windows # Replace / with \\ for the file separator dir = dir.split("/").join("\\") # Check for and append required final \\ if (dir[dir.length - 1].chr != "\\") dir += "\\" end else # Mac # Check for and append required final / if (dir[dir.length - 1].chr != "/") dir += "/" end end if (not File.directory?(dir)) puts "UI.save_panel received bad directory: " + dir args[1] = "" else args[1] = dir end end end # Allow empty file name to be passed in as a valid argument if (args[2]) if (args[2].strip.empty?) args[2] = "*.*" end else args[2] = "*.*" end #if (path = _savepanel(*args)) if (path = UI.savepanel(*args)) # call the original method # Replace \\ with / for the file separator (works better for saving the path in a registry default) path = path.split("\\").join("/") end return(path) end end
29.968992
108
0.554837
e9b5f3f962f7703c02a2e7a7311ce95dec970a4b
2,161
# frozen_string_literal: true # The MIT License (MIT) # # Copyright (c) 2015 GitLab B.V. # # 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. module Heya class License module Boundary BOUNDARY_START = /(\A|\r?\n)-*BEGIN .+? LICENSE-*\r?\n/.freeze BOUNDARY_END = /\r?\n-*END .+? LICENSE-*(\r?\n|\z)/.freeze class << self def add_boundary(data, product_name) data = remove_boundary(data) product_name.upcase! pad = lambda do |message, width| total_padding = [width - message.length, 0].max padding = total_padding / 2.0 [ "-" * padding.ceil, message, "-" * padding.floor ].join end [ pad.call("BEGIN #{product_name} LICENSE", 60), data.strip, pad.call("END #{product_name} LICENSE", 60) ].join("\n") end def remove_boundary(data) after_boundary = data.split(BOUNDARY_START).last in_boundary = after_boundary.split(BOUNDARY_END).first in_boundary end end end end end
33.246154
79
0.652476
91ccffb5bff5b0b3ab5f002d67df6fb344a42e09
6,169
module MyersDiff class WordDiff BOUNDARIES_REGEX = /(\s+|[()\[\]{}'"]|\b)/.freeze EXTENDED_WORD_CHARS_REGEX = /^[a-zA-Z\u{C0}-\u{FF}\u{D8}-\u{F6}\u{F8}-\u{2C6}\u{2C8}-\u{2D7}\u{2DE}-\u{2FF}\u{1E00}-\u{1EFF}]+$/u.freeze def diff(s1, s2, **options) old_string = cast_input(s1) new_string = cast_input(s2) old_string = remove_empty(tokenize(old_string)) new_string = remove_empty(tokenize(new_string)) new_len = new_string.size old_len = old_string.size edit_length = 1 max_edit_length = new_len + old_len best_path = { } best_path[0] = { new_pos: -1, components: [] } old_pos = extract_common(best_path[0], new_string, old_string, 0) if best_path[0][:new_pos] + 1 >= new_len && old_pos + 1 >= old_len return [ { value: join(new_string), count: new_string.size } ] end exec_edit_length = lambda do diagonal_path = -1 * edit_length while diagonal_path <= edit_length add_path = best_path[diagonal_path - 1] remove_path = best_path[diagonal_path + 1] old_pos = (remove_path ? remove_path[:new_pos] : 0) - diagonal_path best_path[diagonal_path - 1] = nil if add_path can_add = add_path && add_path[:new_pos] + 1 < new_len can_remove = remove_path && 0 <= old_pos && old_pos < old_len if !can_add && !can_remove best_path[diagonal_path] = nil diagonal_path += 2 next end base_path = if !can_add || (can_remove && add_path[:new_pos] < remove_path[:new_pos]) p = clone_path(remove_path) push_component(p[:components], nil, true) p else p = add_path p[:new_pos] += 1 push_component(p[:components], true, nil) p end old_pos = extract_common(base_path, new_string, old_string, diagonal_path) if base_path[:new_pos] + 1 >= new_len && old_pos + 1 >= old_len return build_values(base_path[:components], new_string, old_string) else best_path[diagonal_path] = base_path end diagonal_path += 2 end edit_length += 1 nil end while edit_length <= max_edit_length if res = exec_edit_length.call return res end end 'death' end def push_component(components, added, removed) last = components.last if last && last[:added] == added && last[:removed] == removed components[-1] = { added: last[:added], removed: last[:removed], count: last[:count] + 1 } else components.push(count: 1, added: added, removed: removed) end end # base_path : { new_pos: int, components: [] } # diagonal_path : int def extract_common(base_path, new_string, old_string, diagonal_path) new_len = new_string.size old_len = old_string.size new_pos = base_path[:new_pos] old_pos = new_pos - diagonal_path common_count = 0 while new_pos + 1 < new_len && old_pos + 1 < old_len && equals(new_string[new_pos + 1], old_string[old_pos + 1]) new_pos += 1 old_pos += 1 common_count += 1 end if common_count > 0 base_path[:components].push(count: common_count) end base_path[:new_pos] = new_pos old_pos end def equals(l, r) l == r # TODO: support custom comparator # TODO: support case-insensitive end def remove_empty(array) array.compact end def cast_input(str) str end def tokenize(str) tokens = str.split(BOUNDARIES_REGEX) i = 0 while i < tokens.size - 1 if tokens[i + 1].empty? && !tokens[i + 2].empty? && EXTENDED_WORD_CHARS_REGEX.match?(tokens[i]) && EXTENDED_WORD_CHARS_REGEX.match?(tokens[i + 2]) tokens[i] += tokens[i + 2] tokens.delete_at(i + 1) tokens.delete_at(i + 1) i -= 1 end i += 1 end tokens end def join(chars) chars.join('') end # new_string - tokenized string i.e. array of strings def build_values(components, new_string, old_string, use_longest_token = true) component_pos = 0 component_len = components.size new_pos = 0 old_pos = 0 while component_pos < component_len component = components[component_pos] if !component[:removed] if !component[:added] && use_longest_token value = new_string[new_pos, component[:count]] value = value.map.with_index do |val, i| old_val = old_string[old_pos + i] old_val.size > val.size ? old_val : val end component[:value] = join(value) else component[:value] = join(new_string[new_pos, component[:count]]) end new_pos += component[:count] old_pos += component[:count] unless component[:added] else component[:value] = join(old_string[old_pos, component[:count]]) old_pos += component[:count] if component_pos && 0 <= component_pos - 1 && components[component_pos - 1][:added] tmp = components[component_pos - 1] components[component_pos - 1] = components[component_pos] components[component_pos] = tmp end end component_pos += 1 end last_component = components[component_len - 1] if component_len > 1 && last_component[:value].is_a?(String) && (last_component[:added] || last_component[:removed]) && equals('', last_component[:value]) components[component_len - 2][:value] += last_component[:value] components.pop end recount(components) components end def clone_path(path_hash) { new_pos: path_hash[:new_pos], components: path_hash[:components].dup } end def recount(components) components.each { |component| component[:count] = component[:value].size } end end end
29.946602
140
0.583563
79019f37acf3d31f9c42b94da992c06525823c0c
78
require "backports/version" require "backports/2.1" require "backports/rails"
19.5
27
0.794872
08a895270dca609fe18ae8f875bea40d93980bec
1,291
# frozen_string_literal: true # WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/version-3/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE Gem::Specification.new do |spec| spec.name = 'aws-sdk-codestarnotifications' spec.version = File.read(File.expand_path('../VERSION', __FILE__)).strip spec.summary = 'AWS SDK for Ruby - AWS CodeStar Notifications' spec.description = 'Official AWS Ruby gem for AWS CodeStar Notifications. This gem is part of the AWS SDK for Ruby.' spec.author = 'Amazon Web Services' spec.homepage = 'https://github.com/aws/aws-sdk-ruby' spec.license = 'Apache-2.0' spec.email = ['[email protected]'] spec.require_paths = ['lib'] spec.files = Dir['LICENSE.txt', 'CHANGELOG.md', 'VERSION', 'lib/**/*.rb'] spec.metadata = { 'source_code_uri' => 'https://github.com/aws/aws-sdk-ruby/tree/version-3/gems/aws-sdk-codestarnotifications', 'changelog_uri' => 'https://github.com/aws/aws-sdk-ruby/tree/version-3/gems/aws-sdk-codestarnotifications/CHANGELOG.md' } spec.add_dependency('aws-sdk-core', '~> 3', '>= 3.112.0') spec.add_dependency('aws-sigv4', '~> 1.1') end
40.34375
125
0.680093
eda1c62eb3e6e9e32bdef5c9827cf248085138f3
1,316
lib = File.expand_path("lib", __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "tagabaybay/version" Gem::Specification.new do |spec| spec.name = "tagabaybay" spec.version = Tagabaybay::VERSION spec.authors = ["Norly Canarias"] spec.email = ["[email protected]"] spec.summary = %q{This is a gem that allows you to transliterate from tagalog to baybayin} spec.homepage = "https://github.com/lyc4n/tagabaybay" spec.license = "MIT" spec.metadata["homepage_uri"] = spec.homepage spec.metadata["source_code_uri"] = "https://github.com/lyc4n/tagabaybay" # 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.files = Dir.chdir(File.expand_path('..', __FILE__)) do `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } end spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 2.0" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "minitest", "~> 5.0" spec.add_development_dependency "gem-release" end
41.125
98
0.674012
381ed4b31495bfcd4ad777e215b2c188e879dcc1
969
class Slowhttptest < Formula desc "Simulates application layer denial of service attacks" homepage "https://github.com/shekyan/slowhttptest" url "https://github.com/shekyan/slowhttptest/archive/v1.8.tar.gz" sha256 "31f7f1779c3d8e6f095ab19559ea515b5397b5c021573ade9cdba2ee31aaef11" head "https://github.com/shekyan/slowhttptest.git" bottle do cellar :any sha256 "ae6bf1d79b73492cf552f1c070f66c8589596ca68cb1dfd0fbacb1aec703d77a" => :catalina sha256 "f9911a5ba4c428db816eed4e97a15f5163fecbb018e66fa6c95f45a0f61e8db2" => :mojave sha256 "9df930c2bcfc3b447cfde2b4f106e6ecb2adb7ddc33c73b484f997395bdb45f0" => :high_sierra end depends_on "[email protected]" def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" end test do system "#{bin}/slowhttptest", "-u", "https://google.com", "-p", "1", "-r", "1", "-l", "1", "-i", "1" end end
35.888889
93
0.711042
7a812ebe910ce5fe63bf5e413542217c783607bd
824
# frozen_string_literal: true RSpec.describe Bootpay::Api do it "verification" do puts "verification" receipt_id = '612df0250d681b001de61de6' api = Bootpay::Api.new( application_id: '5b8f6a4d396fa665fdc2b5ea', private_key: 'rm6EYECr6aroQVG2ntW0A6LpWnkTgP4uQ3H18sDDUYw=', ) if api.request_access_token.success? response = api.verify(receipt_id) puts response.data.to_json end end it 'certificate' do puts "certificate" receipt_id = '612df0250d681b001de61de6' api = Bootpay::Api.new( application_id: '5b8f6a4d396fa665fdc2b5ea', private_key: 'rm6EYECr6aroQVG2ntW0A6LpWnkTgP4uQ3H18sDDUYw=', ) if api.request_access_token.success? response = api.certificate(receipt_id) puts response.data.to_json end end end
25.75
69
0.703883
1def78e9a214976ccd7f8ad289caecdff4399df9
478
require File.join(Rails.root, "lib/mongoid_migration_task") require 'date' class ChangePersonDob< MongoidMigrationTask def migrate person=Person.where(hbx_id:ENV['hbx_id']).first new_dob = Date.strptime(ENV['new_dob'],'%m/%d/%Y') if person.nil? puts "No person was found by the given hbx_id" unless Rails.env.test? else person.update_attributes(dob:new_dob) puts "Changed date of birth to #{new_dob}" unless Rails.env.test? end end end
31.866667
75
0.709205
1c5bd99037215b6a0126dcee7b9cf82a4df7db70
11,133
# Copyright:: Copyright 2020 Trimble Inc. # License:: The MIT License (MIT) # Drawingelement is a base class for an item in the model that can be # displayed. These items include edges, construction points, construction # lines, and images. Arc curves and arcs are not included because they are not # drawing elements by themselves, but are a composition of edges. # # @version SketchUp 6.0 class Sketchup::Drawingelement < Sketchup::Entity # Instance Methods # The {#bounds} method is used to retrieve the {Geom::BoundingBox} bounding a # {Sketchup::Drawingelement}. # # For a {Sketchup::Edge}, {Sketchup::ComponentInstance} and most other # {Sketchup::Drawingelement}s, the boundingbox follows the coordinate system # the drawing element is placed in. # For {Sketchup::ComponentDefinition}, the box bounds the contents of the # component and follows the component's own internal coordinate system. # # @example # depth = 100 # width = 100 # model = Sketchup.active_model # entities = model.active_entities # pts = [] # pts[0] = [0, 0, 0] # pts[1] = [width, 0, 0] # pts[2] = [width, depth, 0] # pts[3] = [0, depth, 0] # # Add the face to the entities in the model # face = entities.add_face pts # # Remember, anything that can be displayed, such as a face, is also # # a Drawingelement. So I can call bounds on a face because Face # # is a sub-class of Drawingelement. # boundingbox = face.bounds # # @return [Geom::BoundingBox] # # @version SketchUp 6.0 def bounds end # The casts_shadows= method is used to set the Drawingelement to cast shadows. # # @example # depth = 100 # width = 100 # model = Sketchup.active_model # entities = model.active_entities # pts = [] # pts[0] = [0, 0, 100] # pts[1] = [width, 0, 100] # pts[2] = [width, depth, 100] # pts[3] = [0, depth, 100] # # Add the face to the entities in the model. # face = entities.add_face pts # # # Make the face not cast shadows. # status = face.casts_shadows = false # UI.messagebox status.to_s # # @param [Boolean] casts # true if you want the Drawingelement object to cast # shadows, false if you do not want the Drawingelement # object to cast shadows. # # @return [Boolean] true if successful, false if unsuccessful. # # @version SketchUp 6.0 def casts_shadows=(casts) end # The casts_shadows? method is used to determine if the Drawingelement is # casting shadows. # # @example # depth = 100 # width = 100 # model = Sketchup.active_model # entities = model.active_entities # pts = [] # pts[0] = [0, 0, 0] # pts[1] = [width, 0, 0] # pts[2] = [width, depth, 0] # pts[3] = [0, depth, 0] # # Add the face to the entities in the model # face = entities.add_face pts # status = face.casts_shadows? # UI.messagebox status.to_s # # @return [Boolean] # # @version SketchUp 6.0 def casts_shadows? end # The erase! method is used to erase an element from the model. # # Erasing an Edge also erases all of the Face objects that use the Edge. # # @example # depth = 100 # width = 100 # model = Sketchup.active_model # entities = model.active_entities # pts = [] # pts[0] = [0, 0, 0] # pts[1] = [width, 0, 0] # pts[2] = [width, depth, 0] # pts[3] = [0, depth, 0] # # Add the face to the entities in the model # face = entities.add_face pts # status = face.erase! # # @return [Boolean] true if successful, false if unsuccessful # # @version SketchUp 6.0 def erase! end # The hidden= method is used to set the hidden status for an element. # # @example # depth = 100 # width = 100 # model = Sketchup.active_model # entities = model.active_entities # pts = [] # pts[0] = [0, 0, 0] # pts[1] = [width, 0, 0] # pts[2] = [width, depth, 0] # pts[3] = [0, depth, 0] # # Add the face to the entities in the model # face = entities.add_face pts # UI.messagebox "Click OK to Hide the Box" # status = face.hidden = true # # @param [Boolean] hidden # true if you want to hide the element, false if you do # not want to hide the element. # # @return [Boolean] true if the element has been hidden, false if # the element has not been hidden. # # @version SketchUp 6.0 def hidden=(hidden) end # The hidden? method is used to determine if the element is hidden. # # Hidden elements are still in the model, but they are not displayed. # # @example # depth = 100 # width = 100 # model = Sketchup.active_model # entities = model.active_entities # pts = [] # pts[0] = [0, 0, 0] # pts[1] = [width, 0, 0] # pts[2] = [width, depth, 0] # pts[3] = [0, depth, 0] # # Add the face to the entities in the model # face = entities.add_face pts # status = face.hidden? # UI.messagebox "hidden? " + status.to_s # # @return [Boolean] # # @version SketchUp 6.0 def hidden? end # The layer method is used to retrieve the Layer object of the drawing # element. # # @example # depth = 100 # width = 100 # model = Sketchup.active_model # entities = model.active_entities # pts = [] # pts[0] = [0, 0, 0] # pts[1] = [width, 0, 0] # pts[2] = [width, depth, 0] # pts[3] = [0, depth, 0] # # Add the face to the entities in the model # face = entities.add_face pts # layer = face.layer # # @return [Sketchup::Layer] a layer object if successful # # @version SketchUp 6.0 def layer end # The layer= method is used to set the layer for the drawing element. # # An exception is raised if you give a string that doesn't match any layer # name. # # @example # depth = 100 # width = 100 # model = Sketchup.active_model # entities = model.active_entities # pts = [] # pts[0] = [0, 0, 0] # pts[1] = [width, 0, 0] # pts[2] = [width, depth, 0] # pts[3] = [0, depth, 0] # # Add the face to the entities in the model # face = entities.add_face pts # # Add a layer # layer = Sketchup.active_model.layers.add "joe" # # Put the face on the joe layer (instead of layer 0) # newlayer = face.layer = layer # # @param [Sketchup::Layer, String] layer # A layer or layer name. # # @return [Sketchup::Layer, String] the new Layer object if successful # # @version SketchUp 6.0 def layer=(layer) end # The material method is used to retrieve the material for the drawing # element. # # @example # depth = 100 # width = 100 # model = Sketchup.active_model # entities = model.active_entities # pts = [] # pts[0] = [0, 0, 0] # pts[1] = [width, 0, 0] # pts[2] = [width, depth, 0] # pts[3] = [0, depth, 0] # # Add the face to the entities in the model # face = entities.add_face pts # material = face.material # # @return [Sketchup::Material] the Material object if successful # # @version SketchUp 6.0 def material end # The material= method is used to set the material for the drawing # element. # # @example # depth = 100 # width = 100 # model = Sketchup.active_model # entities = model.active_entities # pts = [] # pts[0] = [0, 0, 0] # pts[1] = [width, 0, 0] # pts[2] = [width, depth, 0] # pts[3] = [0, depth, 0] # # Add the face to the entities in the model # face = entities.add_face pts # m = model.materials.add "Joe" # begin # # Returns nil if not successful, path if successful. # # Should return a texture object. # m.texture = "c:\\My Textures\\Carpet.jpg" # rescue # UI.messagebox $!.message # end # # You will see the material applied when you reverse the box's faces # material = face.material = m # # @param [Sketchup::Material, String, Sketchup::Color] material # A Material, name of a material, Color, or name of a # color. # # @return [Sketchup::Material, String, Sketchup::Color] the new Material object if successful # # @version SketchUp 6.0 def material=(material) end # The receive_shadows= method is used to set the Drawingelement to receive # shadows. # # @example # depth = 100 # width = 100 # model = Sketchup.active_model # entities = model.active_entities # pts = [] # pts[0] = [0, 0, 100] # pts[1] = [width, 0, 100] # pts[2] = [width, depth, 100] # pts[3] = [0, depth, 100] # # Add the face to the entities in the model. # face = entities.add_face pts # # # Make the face not receive shadows. # status = face.receives_shadows = false # UI.messagebox status.to_s # # @param [Boolean] receive # true if you want the Drawingelement object to # receive shadows, false if not. # # @return [Boolean] true if successful, false if unsuccessful. # # @version SketchUp 6.0 def receives_shadows=(receive) end # The receive_shadows? method is used to determine if the Drawingelement is # receiving shadows. # # @example # depth = 100 # width = 100 # model = Sketchup.active_model # entities = model.active_entities # pts = [] # pts[0] = [0, 0, 0] # pts[1] = [width, 0, 0] # pts[2] = [width, depth, 0] # pts[3] = [0, depth, 0] # # Add the face to the entities in the model # face = entities.add_face pts # status = face.receives_shadows? # UI.messagebox status.to_s # # @return [Boolean] # # @version SketchUp 6.0 def receives_shadows? end # The visible= method is used to set the visible status for an element. This # method performs an opposite function to the hidden= method. # # @example # depth = 100 # width = 100 # model = Sketchup.active_model # entities = model.active_entities # pts = [] # pts[0] = [0, 0, 0] # pts[1] = [width, 0, 0] # pts[2] = [width, depth, 0] # pts[3] = [0, depth, 0] # # Add the face to the entities in the model # face = entities.add_face pts # UI.messagebox "Click OK to Hide the Box" # status = face.visible = false # # @param [Boolean] visibility # true if you want to hide the element, false if not # # @return [Boolean] true if the element has been hidden, false if # the element has not been hidden. # # @version SketchUp 6.0 def visible=(visibility) end # The visible? method is used to get the visible status for an element. # # @example # depth = 100 # width = 100 # model = Sketchup.active_model # entities = model.active_entities # pts = [] # pts[0] = [0, 0, 0] # pts[1] = [width, 0, 0] # pts[2] = [width, depth, 0] # pts[3] = [0, depth, 0] # # Add the face to the entities in the model # face = entities.add_face pts # UI.messagebox "Click OK to Hide the Box" # face.visible = false # UI.messagebox "Is the face visible? " + face.visible?.to_s # # @return [Boolean] # # @version SketchUp 6.0 def visible? end end
28.042821
95
0.610707
4a5a888354639b2e194583c322721d09fb99590e
722
Pod::Spec.new do |s| s.name = "FontAwesome.swift" s.version = "1.4.3" s.summary = "Use Font Awesome in your Swift projects" s.homepage = "https://github.com/thii/FontAwesome.swift" s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { "Thi Doan" => "[email protected]" } s.source = { :git => "https://github.com/thii/FontAwesome.swift.git", :tag => s.version.to_s } s.ios.deployment_target = '8.0' s.tvos.deployment_target = '9.0' s.requires_arc = true s.source_files = 'FontAwesome/*.{swift}' s.resource_bundle = { 'FontAwesome.swift' => 'FontAwesome/*.otf' } s.frameworks = 'UIKit', 'CoreText' s.swift_version = "4.0" end
38
106
0.580332
39a0becc62a25f05635f26d155474676d3db00ae
4,440
require 'rspec' require 'tempfile' require 'rspec/core/rake_task' require 'bosh/dev/bat_helper' require 'bosh/dev/sandbox/nginx' require 'bosh/dev/sandbox/workspace' require 'common/thread_pool' require 'parallel_tests/tasks' namespace :spec do namespace :integration do desc 'Run BOSH integration tests against a local sandbox' task :agent => :install_dependencies do sh('go/src/github.com/cloudfoundry/bosh-agent/bin/build') run_integration_specs end desc 'Install BOSH integration test dependencies (currently Nginx)' task :install_dependencies do nginx = Bosh::Dev::Sandbox::Nginx.new nginx.install end def run_integration_specs Bosh::Dev::Sandbox::Workspace.clean num_processes = ENV['NUM_GROUPS'] num_processes ||= ENV['TRAVIS'] ? 4 : nil options = {} options[:count] = num_processes if num_processes options[:group] = ENV['GROUP'] if ENV['GROUP'] run_in_parallel('spec/integration', options) end def run_in_parallel(test_path, options={}) count = " -n #{options[:count]}" unless options[:count].to_s.empty? group = " --only-group #{options[:group]}" unless options[:group].to_s.empty? command = "https_proxy= http_proxy= bundle exec parallel_test '#{test_path}'#{count}#{group} --group-by filesize --type rspec" puts command abort unless system(command) end end task :integration => %w(spec:integration:agent) namespace :unit do desc 'Run unit tests for each BOSH component gem in parallel' task ruby_gems: %w(rubocop) do trap('INT') { exit } builds = Dir['*'].select { |f| File.directory?(f) && File.exists?("#{f}/spec") } builds -= %w(bat) cpi_builds = builds.select { |f| File.directory?(f) && f.end_with?("_cpi") } spec_logs = Dir.mktmpdir puts "Logging spec results in #{spec_logs}" max_threads = ENV.fetch('BOSH_MAX_THREADS', 10).to_i null_logger = Logging::Logger.new('Ignored') Bosh::ThreadPool.new(max_threads: max_threads, logger: null_logger).wrap do |pool| builds.each do |build| pool.process do log_file = "#{spec_logs}/#{build}.log" rspec_files = cpi_builds.include?(build) ? "spec/unit/" : "spec/" rspec_cmd = "rspec --tty --backtrace -c -f p #{rspec_files}" # inject command name so coverage results for each component don't clobber others if system({'BOSH_BUILD_NAME' => build}, "cd #{build} && #{rspec_cmd} > #{log_file} 2>&1") puts "----- BEGIN #{build}" puts " #{rspec_cmd}" print File.read(log_file) puts "----- END #{build}\n\n" else raise("#{build} failed to build unit tests: #{File.read(log_file)}") end end end pool.wait end end task(:agent) do # Do not use exec because this task is part of other tasks sh('go/src/github.com/cloudfoundry/bosh-agent/bin/test-unit') end end task :unit => %w(spec:unit:ruby_gems spec:unit:agent) namespace :external do desc 'AWS bootstrap CLI can provision and destroy resources' RSpec::Core::RakeTask.new(:aws_bootstrap) do |t| t.pattern = 'spec/external/aws_bootstrap_spec.rb' t.rspec_opts = %w(--format documentation --color) end end namespace :system do desc 'Run system (BATs) tests (deploys microbosh)' task :micro, [:infrastructure_name, :hypervisor_name, :operating_system_name, :operating_system_version, :net_type, :agent_name, :light, :disk_format] do |_, args| Bosh::Dev::BatHelper.for_rake_args(args).deploy_microbosh_and_run_bats end desc 'Run system (BATs) tests (uses existing microbosh)' task :existing_micro, [:infrastructure_name, :hypervisor_name, :operating_system_name, :operating_system_version, :net_type, :agent_name, :light, :disk_format] do |_, args| Bosh::Dev::BatHelper.for_rake_args(args).run_bats end desc 'Deploy microbosh for system (BATs) tests' task :deploy_micro, [:infrastructure_name, :hypervisor_name, :operating_system_name, :operating_system_version, :net_type, :agent_name, :light, :disk_format] do |_, args| Bosh::Dev::BatHelper.for_rake_args(args).deploy_bats_microbosh end end end desc 'Run unit and integration specs' task :spec => %w(spec:unit spec:integration)
36.097561
176
0.656982
f7be2242cb284c9631fda6f78273dfc69cc6065b
209
formats = { am_pm: "%I:%M %p", am_pm_long: "%b %e %Y, %l:%M %p", am_pm_long_tz: "%b %e %Y, %l:%M %p %Z", day_long: "%A, %B %d, %Y" } Time::DATE_FORMATS.merge! formats Date::DATE_FORMATS.merge! formats
23.222222
41
0.569378
d5a79ccb81f7b9c02bfb849b83c2909563321c42
824
require "rails_helper" RSpec.describe SchedulesController, type: :routing do describe "routing" do it "routes to #index" do expect(:get => "/schedules").to route_to("schedules#index") end it "routes to #show" do expect(:get => "/schedules/1").to route_to("schedules#show", :id => "1") end it "routes to #create" do expect(:post => "/schedules").to route_to("schedules#create") end it "routes to #update via PUT" do expect(:put => "/schedules/1").to route_to("schedules#update", :id => "1") end it "routes to #update via PATCH" do expect(:patch => "/schedules/1").to route_to("schedules#update", :id => "1") end it "routes to #destroy" do expect(:delete => "/schedules/1").to route_to("schedules#destroy", :id => "1") end end end
26.580645
84
0.610437
ab93f8a3ac7fc0c31d10cefc2628d15432d55d65
1,236
# frozen_string_literal: true # we have to require StubPlayer first because ruby's module resolution is bad require_relative "player/stub_player" Dir.glob(File.join(__dir__, "player/*")) { |file| require_relative file } module Muzak # The namespace for muzak players. module Player extend Utils # All classes (player implementations) under the {Player} namespace. # @api private PLAYER_CLASSES = constants.map(&Player.method(:const_get)).grep(Class).freeze # All human-friendly player names. # @see Player::StubPlayer.player_name # @api private PLAYER_NAMES = PLAYER_CLASSES.map(&:player_name).freeze # An association of human-friendly player names to implementation classes. # @api private PLAYER_MAP = PLAYER_NAMES.zip(PLAYER_CLASSES).to_h.freeze # Returns an instantiated player as specified in `Config.player`. # @return [StubPlayer] the player instance def self.load_player!(instance) klass = PLAYER_MAP[Config.player] error! "#{Config.player} isn't a known player" unless klass if klass.available? klass.new(instance) else error! "#{Config.player} isn't available, do you need to install it?" end end end end
30.146341
81
0.70712
4a01fb48bd2e2fceabcdb89699576ae1e9c0663a
7,709
require 'spec_helper' describe Rack::PassbookRack do let(:register_delete_path) {'/v1/devices/fe772e610be3efafb65ed77772ca311a/registrations/pass.com.polyglotprogramminginc.testpass/27-1'} let(:register_delete_params) {{'deviceLibraryIdentifier' => 'fe772e610be3efafb65ed77772ca311a', 'passTypeIdentifier' => 'pass.com.polyglotprogramminginc.testpass', 'serialNumber' => '27-1'}} let(:passes_for_device_path) {'/v1/devices/fe772e610be3efafb65ed77772ca311a/registrations/pass.com.polyglotprogramminginc.testpass'} let(:passes_for_device_params) {{'deviceLibraryIdentifier' => 'fe772e610be3efafb65ed77772ca311a', 'passTypeIdentifier' => 'pass.com.polyglotprogramminginc.testpass'}} let(:latest_pass_path) {'/v1/passes/pass.com.polyglotprogramminginc.testpass/27-1'} let(:latest_pass_params) {{'passTypeIdentifier' => 'pass.com.polyglotprogramminginc.testpass', 'serialNumber' => '27-1'}} let(:log_path) {'/v1/log'} let(:push_token) {"8c56f2e787d9c089963960ace834bc2875e3f0cf7745da5b98d58bc6be05b4dc"} let(:auth_token) {"3c0adc9ccbcf3e733edeb897043a4835"} context 'find method' do let(:passbook_rack) {Rack::PassbookRack.new nil} shared_examples_for 'a method that can handle non passbook urls' do context 'incomplete passbook api path' do subject {passbook_rack.find_method('/v1/devices/fe772e610be3efafb65ed77772ca311a/registrations')} it {should eq nil} end context 'no version api path' do subject {passbook_rack.find_method('/devices/fe772e610be3efafb65ed77772ca311a/registrations')} it {should eq nil} end context 'no devices api path' do subject {passbook_rack.find_method('/v1/fe772e610be3efafb65ed77772ca311a/registrations')} it {should eq nil} end context 'no registrations api path' do subject {passbook_rack.find_method('/v1/devices/fe772e610be3efafb65ed77772ca311a')} it {should eq nil} end end context 'device register delete' do context 'a valid path' do subject {passbook_rack.find_method(register_delete_path)} its([:method]) {should eq 'device_register_delete'} its([:params]) {should eq(register_delete_params) } end it_behaves_like 'a method that can handle non passbook urls' end context 'passes for device' do subject {passbook_rack.find_method(passes_for_device_path)} its([:method]) {should eq 'passes_for_device'} its([:params]) {should eq passes_for_device_params } end context 'latest pass' do subject {passbook_rack.find_method(latest_pass_path)} its([:method]) {should eq 'latest_pass'} its([:params]) {should eq(latest_pass_params) } end context 'latest pass' do subject {passbook_rack.find_method(log_path)} its([:method]) {should eq 'log'} end end context 'rack middleware' do context 'register pass without authToken' do before do Passbook::PassbookNotification.should_receive(:register_pass). with(register_delete_params.merge!('pushToken' => push_token)).and_return({:status => 201}) post register_delete_path, {"pushToken" => push_token}.to_json end subject {last_response} its(:status) {should eq 201} end context 'register pass with authToken' do before do Passbook::PassbookNotification.should_receive(:register_pass). with(register_delete_params.merge!('pushToken' => push_token,'authToken' => auth_token)).and_return({:status => 201}) post register_delete_path, {"pushToken" => push_token}.to_json, rack_env = {'HTTP_AUTHORIZATION' => auth_token} end subject {last_response} its(:status) {should eq 201} end context 'passes for device' do context 'with passes' do let(:passes_for_device_response) {{'last_updated' => 1, 'serial_numbers' => [343, 234]}} before do Passbook::PassbookNotification.should_receive(:passes_for_device). with(passes_for_device_params).and_return(passes_for_device_response) get passes_for_device_path end context 'status' do subject {last_response.status} it {should eq 200} end context 'body' do subject{JSON.parse(last_response.body)} it {should eq passes_for_device_response} end end context 'with passes modified since' do before do Passbook::PassbookNotification.should_receive(:passes_for_device). with(passes_for_device_params.merge!('passesUpdatedSince' => '1371189712')).and_return(nil) path_with_update_since = passes_for_device_path + "?passesUpdatedSince=1371189712" get path_with_update_since end context 'status' do subject {last_response.status} it {should eq 204} end end context 'without passes' do before do Passbook::PassbookNotification.should_receive(:passes_for_device). with(passes_for_device_params).and_return(nil) get passes_for_device_path end context 'status' do subject {last_response.status} it {should eq 204} end end end context 'get latest pass' do context 'valid pass' do let(:raw_pass) {'some url encoded text'} before do Passbook::PassbookNotification.should_receive(:latest_pass).with(latest_pass_params). and_return(raw_pass) get latest_pass_path end subject {last_response} its(:status) {should eq 200} its(:header) {should eq({'Content-Type' => 'application/vnd.apple.pkpass', 'Content-Disposition' => 'attachment', 'filename' => '27-1.pkpass', 'Content-Length' => '21'})} its(:body) {should eq raw_pass} end context 'no pass' do before do Passbook::PassbookNotification.should_receive(:latest_pass).with(latest_pass_params). and_return(nil) get latest_pass_path end subject {last_response} its(:status) {should eq 204} end end context 'unregister pass without authToken' do before do Passbook::PassbookNotification.should_receive(:unregister_pass). with(register_delete_params).and_return({:status => 200}) delete register_delete_path end subject {last_response} its(:status) {should eq 200} end context 'unregister pass with authToken' do before do Passbook::PassbookNotification.should_receive(:unregister_pass). with(register_delete_params.merge!('authToken' => auth_token)).and_return({:status => 200}) delete register_delete_path, {}, rack_env = {'HTTP_AUTHORIZATION' => auth_token} end subject {last_response} its(:status) {should eq 200} end context 'log' do let(:log_params) {{'logs' => ['some error']}} before do Passbook::PassbookNotification.should_receive(:passbook_log). with(log_params) post log_path, log_params.to_json end subject {last_response} its(:status) {should eq 200} end context 'non passbook requests' do before do get '/foo' end subject {last_response} its(:status) {should eq 200} its(:body) {should eq 'test app'} end end end require 'rack/test' include Rack::Test::Methods def app test_app = lambda do |env| [200, {}, 'test app'] end Rack::PassbookRack.new test_app end class Passbook::PassbookNotification end
32.944444
137
0.666753
26a9e66aed5910f920e30b184ca7f0cb04e0d190
329
# # Cookbook Name:: build # Recipe:: smoke_tier_ec_upgrade_aws # # Copyright (c) 2015 The Authors, All Rights Reserved. node.override['chef-server-acceptance']['identifier'] = 'tier-ec-upgrade' include_recipe 'build::smoke_general_prep' include_recipe 'build::tier_prepare_machine_configs' include_recipe 'build::smoke_tier'
23.5
73
0.781155
0886befe0443b6353b7d621e43464f862144a156
827
# frozen_string_literal: true require "minitest" module Break class TestingFrontend class << self def build(&block) Class.new(self, &block) end def stack @stack ||= [] end def [](index) stack[index] end def last stack.last end def clear stack.clear end end attr_reader :session def initialize self.class.stack << self end def attach(session) @session = session end def detach; end def where; end def notify(_message); end end class Test < Minitest::Test def self.test(name, &block) define_method("test_#{name}", &block) end def pass Kernel.binding.tap do |binding| yield binding if block_given? end end end end
14.258621
43
0.561064
e9ad8f65f3ba66aca244e424d88459145d262c70
181
class CreateCompanyCategories < ActiveRecord::Migration[6.0] def change create_table :company_categories do |t| t.string :category t.timestamps end end end
18.1
60
0.707182
21169d231165382e342154725e76ea5c46e9c5cf
375
# Copyright (c) 2013 Universidade Federal Fluminense (UFF). # This file is part of SAPOS. Please, consult the license terms in the LICENSE file. # Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :allocation do day { I18n.translate("date.day_names").first } course_class start_time 10 end_time 12 end end
26.785714
84
0.744
3978b9081d2f886d8db718dce5df17a33cdafab1
100
require './app' require 'sidekiq/web' run Rack::URLMap.new('/' => App, '/sidekiq' => Sidekiq::Web)
20
60
0.63
ed4e1bfdd5c3e40c71e94b9ef9c4503128450192
114
require "test_helper" class FingerTest < ActiveSupport::TestCase test "the truth" do refute true end end
14.25
42
0.736842
01e5ae37460321a77b1c68e246bb8e28ef4e4367
1,420
# frozen_string_literal: true require 'helper' class TestAvatar < Test::Unit::TestCase include DeterministicHelper ROBOHASH = 'https://robohash.org' assert_methods_are_deterministic(FFaker::Avatar, :image) def setup @tester = FFaker::Avatar end def test_avatar assert_match(%r{\Ahttps://robohash\.org/.+\.png\?size=300x300\z}, @tester.image) end def test_avatar_with_param assert_equal("#{ROBOHASH}/faker.png?size=300x300", @tester.image('faker')) end def test_avatar_with_correct_size assert_equal("#{ROBOHASH}/faker.png?size=150x320", @tester.image('faker', '150x320')) end def test_avatar_with_incorrect_size assert_raise ArgumentError do @tester.image(nil, '150x320z') end end def test_avatar_with_supported_format assert_equal("#{ROBOHASH}/faker.jpg?size=300x300", @tester.image('faker', '300x300', 'jpg')) end def test_avatar_with_incorrect_format assert_raise ArgumentError do @tester.image(nil, '300x300', 'wrong_format') end end def test_avatar_with_correct_background assert_equal("#{ROBOHASH}/faker.png?size=300x300&bgset=bg1", @tester.image('faker', '300x300', 'png', '1')) end def test_avatar_with_incorrect_background assert_raise ArgumentError do @tester.image('faker', '300x300', 'png', 'not_a_number') end end end
24.482759
78
0.685915
01705cdf1cce1d24b74de8367b1e9b042a8e2a9e
128
require 'test_helper' class RobotConditionTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
16
50
0.71875
e941581e2f382ea2ac6a45ae3e600424f74f182f
517
module QuickenParser class Transactions include Enumerable attr_accessor :timespan def initialize(args={}) @txns = Array.new args.each_pair do |key, value| send("#{key}=", value) end end def first @txns.first end def last @txns.last end def length @txns.length end alias_method :size, :length def <<(txn) @txns << txn end def each @txns.each do |txn| yield txn end end end end
13.972973
36
0.545455
798db0aae335749c7d9cf34283b8a30852c7c98b
1,623
# encoding: utf-8 # # Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you 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_relative '../spec_helper' module Selenium module WebDriver compliant_on driver: :remote do describe Element do before do driver.file_detector = ->(_str) { __FILE__ } end after do driver.file_detector = nil end compliant_on browser: [:chrome, :ff_legacy] do it 'uses the file detector' do driver.navigate.to url_for('upload.html') driver.find_element(id: 'upload').send_keys('random string') driver.find_element(id: 'go').submit driver.switch_to.frame('upload_target') body = driver.find_element(xpath: '//body') expect(body.text).to include('uses the set file detector') end end end end end # WebDriver end # Selenium
32.46
72
0.680838
ffe8a287b41d83850cd4ac8d2e8dccf2e739ad25
10,480
# # Author:: Seth Chisamore <[email protected]> # Cookbook:: php # Resource:: pear # # Copyright:: 2011-2021, Chef Software, Inc <[email protected]> # # 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. # unified_mode true property :package_name, String, name_property: true property :version, [String, nil] property :channel, String property :options, String property :directives, Hash, default: {} property :zend_extensions, Array, default: [] property :preferred_state, String, default: 'stable' property :binary, String, default: 'pear' property :priority, [String, nil] def current_installed_version(new_resource) version_check_cmd = "#{new_resource.binary} -d" version_check_cmd << " preferred_state=#{new_resource.preferred_state}" version_check_cmd << " list#{expand_channel(new_resource.channel)}" p = shell_out(version_check_cmd) response = nil response = grep_for_version(p.stdout, new_resource.package_name) if p.stdout =~ /\.?Installed packages/i response end def expand_channel(channel) channel ? " -c #{channel}" : '' end def grep_for_version(stdout, package) version = nil stdout.split(/\n/).grep(/^#{package}\s/i).each do |m| # XML_RPC 1.5.4 stable # mongo 1.1.4/(1.1.4 stable) 1.1.4 MongoDB database driver # Horde_Url -n/a-/(1.0.0beta1 beta) Horde Url class # Horde_Url 1.0.0beta1 (beta) 1.0.0beta1 Horde Url class version = m.split(/\s+/)[1].strip version = if version.split(%r{/\//})[0] =~ /.\./ # 1.1.4/(1.1.4 stable) version.split(%r{/\//})[0] else # -n/a-/(1.0.0beta1 beta) version.split(%r{/(.*)\/\((.*)/}).last.split(/\s/)[0] end end version end load_current_value do |new_resource| unless current_installed_version(new_resource).nil? version(current_installed_version(new_resource)) Chef::Log.debug("Current version is #{version}") if version end end action :install do build_essential # If we specified a version, and it's not the current version, move to the specified version install_version = new_resource.version unless new_resource.version.nil? || new_resource.version == current_resource.version # Check if the version we want is already installed versions_match = candidate_version == current_installed_version(new_resource) # If it's not installed at all or an upgrade, install it if install_version || new_resource.version.nil? && !versions_match converge_by("install package #{new_resource.package_name} #{install_version}") do info_output = "Installing #{new_resource.package_name}" info_output << " version #{install_version}" if install_version && !install_version.empty? Chef::Log.info(info_output) install_package(new_resource.package_name, install_version) end end end # reinstall is just an install that always fires action :reinstall do build_essential install_version = new_resource.version unless new_resource.version.nil? converge_by("reinstall package #{new_resource.package_name} #{install_version}") do info_output = "Installing #{new_resource.package_name}" info_output << " version #{install_version}" if install_version && !install_version.empty? Chef::Log.info(info_output) install_package(new_resource.package_name, install_version, force: true) end end action :upgrade do if current_resource.version != candidate_version orig_version = @current_resource.version || 'uninstalled' description = "upgrade package #{new_resource.package_name} version from #{orig_version} to #{candidate_version}" converge_by(description) do upgrade_package(new_resource.package_name, candidate_version) end end end action :remove do if removing_package? converge_by("remove package #{new_resource.package_name}") do remove_package(@current_resource.package_name, new_resource.version) end end end action :purge do if removing_package? converge_by("purge package #{new_resource.package_name}") do remove_package(@current_resource.package_name, new_resource.version) end end end action_class do def expand_options(options) options ? " #{options}" : '' end def candidate_version candidate_version_cmd = "#{new_resource.binary} -d " candidate_version_cmd << "preferred_state=#{new_resource.preferred_state}" candidate_version_cmd << " search#{expand_channel(new_resource.channel)}" candidate_version_cmd << " #{new_resource.package_name}" p = shell_out(candidate_version_cmd) response = nil response = grep_for_version(p.stdout, new_resource.package_name) if p.stdout =~ /\.?Matched packages/i response end def install_package(name, version, **opts) command = "printf \"\r\" | #{new_resource.binary} -d" command << " preferred_state=#{new_resource.preferred_state}" command << " install -a#{expand_options(new_resource.options)}" command << ' -f' if opts[:force] # allows us to force a reinstall command << " #{prefix_channel(new_resource.channel)}#{name}" command << "-#{version}" if version && !version.empty? pear_shell_out(command) manage_pecl_ini(name, :create, new_resource.directives, new_resource.zend_extensions, new_resource.priority) if pecl? enable_package(name) end def upgrade_package(name, version) command = "printf \"\r\" | #{new_resource.binary} -d" command << " preferred_state=#{new_resource.preferred_state}" command << " upgrade -a#{expand_options(new_resource.options)}" command << " #{prefix_channel(new_resource.channel)}#{name}" command << "-#{version}" if version && !version.empty? pear_shell_out(command) manage_pecl_ini(name, :create, new_resource.directives, new_resource.zend_extensions, new_resource.priority) if pecl? enable_package(name) end def remove_package(name, version) command = "#{new_resource.binary} uninstall" command << " #{expand_options(new_resource.options)}" command << " #{prefix_channel(new_resource.channel)}#{name}" command << "-#{version}" if version && !version.empty? pear_shell_out(command) disable_package(name) manage_pecl_ini(name, :delete, nil, nil, nil) if pecl? end def enable_package(name) execute "#{node['php']['enable_mod']} #{name}" do only_if { platform?('ubuntu') && ::File.exist?(node['php']['enable_mod']) } end end def disable_package(name) execute "#{node['php']['disable_mod']} #{name}" do only_if { platform?('ubuntu') && ::File.exist?(node['php']['disable_mod']) } end end def pear_shell_out(command) p = shell_out!(command) # pear/pecl commands return a 0 on failures...we'll grep for it p.invalid! if p.stdout.split('\n').last =~ /^ERROR:.+/i p end def prefix_channel(channel) channel ? "#{channel}/" : '' end def removing_package? if new_resource.version.nil? true # remove any version of a package else new_resource.version == @current_resource.version # we don't have the version we want to remove end end def extension_dir @extension_dir ||= begin # Consider using "pecl config-get ext_dir". It is more cross-platform. # p = shell_out("php-config --extension-dir") p = shell_out("#{node['php']['pecl']} config-get ext_dir") p.stdout.strip end end def get_extension_files(name) files = [] # use appropriate binary when listing pecl packages list_binary = if new_resource.channel == 'pecl.php.net' node['php']['pecl'] else new_resource.binary end p = shell_out("#{list_binary} list-files #{name}") p.stdout.each_line.grep(/^src\s+.*\.so$/i).each do |line| files << line.split[1] end files end def pecl? @pecl ||= begin # search as a pear first since most 3rd party channels will report pears as pecls! search_args = '' search_args << " -d preferred_state=#{new_resource.preferred_state}" search_args << " search#{expand_channel(new_resource.channel)} #{new_resource.package_name}" if grep_for_version(shell_out(new_resource.binary + search_args).stdout, new_resource.package_name) if (new_resource.binary.include? 'pecl') || (new_resource.channel == 'pecl.php.net') true else false end elsif grep_for_version(shell_out(node['php']['pecl'] + search_args).stdout, new_resource.package_name) true else raise "Package #{new_resource.package_name} not found in either PEAR or PECL." end end end def manage_pecl_ini(name, action, directives, zend_extensions, priority) ext_prefix = extension_dir ext_prefix << ::File::SEPARATOR if ext_prefix[-1].chr != ::File::SEPARATOR files = get_extension_files(name) extensions = Hash[ files.map do |filepath| rel_file = filepath.clone rel_file.slice! ext_prefix if rel_file.start_with? ext_prefix zend = zend_extensions.include?(rel_file) [(zend ? filepath : rel_file), zend] end ] directory node['php']['ext_conf_dir'] do owner 'root' group 'root' mode '0755' recursive true end template "#{node['php']['ext_conf_dir']}/#{name}.ini" do source 'extension.ini.erb' cookbook 'php' owner 'root' group 'root' mode '0644' variables( name: name, extensions: extensions, directives: directives, priority: priority ) action action end execute "#{node['php']['enable_mod']} #{name}" do creates "#{node['php']['conf_dir']}/conf.d/#{name}" only_if { platform_family? 'debian' } end end end
34.587459
125
0.669179
9116a234da7b0995c42cf87f9748c9c96e3aba0a
134
class AddAuthorIdToPosts < ActiveRecord::Migration[5.1] def change add_column :exposition_posts, :author_id, :integer end end
22.333333
55
0.768657
d526a9f8b9f5196445d199e8eaced5a63b53525e
322
module Stall module Shippable extend ActiveSupport::Concern included do has_one :shipment, dependent: :destroy, inverse_of: :cart accepts_nested_attributes_for :shipment end private def items super.tap do |items| items << shipment if shipment end end end end
16.947368
63
0.658385
e223c5a635808befc82247304338c86697a3a1f3
280
require 'ostruct' module Rmega def self.default_options { upload_timeout: 120, api_request_timeout: 20, api_url: 'https://eu.api.mega.co.nz/cs' } end def self.options @options ||= OpenStruct.new(default_options) end end
17.5
58
0.607143
1db3cc05ca36d34f99b15e8b0ce307756e572946
417
# This file is generated by rake. Do not edit. module Fcntl FD_CLOEXEC = 1 F_DUPFD = 0 F_GETFD = 1 F_GETFL = 3 F_GETLK = 7 F_RDLCK = 1 F_SETFD = 2 F_SETFL = 4 F_SETLK = 8 F_SETLKW = 9 F_UNLCK = 2 F_WRLCK = 3 O_ACCMODE = 3 O_APPEND = 8 O_CREAT = 512 O_EXCL = 2048 O_NDELAY = 4 O_NOCTTY = 32768 O_NONBLOCK = 4 O_RDONLY = 0 O_RDWR = 2 O_TRUNC = 1024 O_WRONLY = 1 end
12.264706
46
0.613909
082b17f572d57d405f89150e998d0cd684ab3fb2
194
class AddSubdomainToChannels < ActiveRecord::Migration def change add_column :channels, :subdomain, :string, allow_nil: false add_index :channels, :subdomain, {unique: true} end end
27.714286
63
0.752577
62bd12a25faea18c9ae6de4e3efb6afaa2025cdc
59
# frozen_string_literal: true json.extract! @handle, :url
14.75
29
0.762712
ff2b55f5cbe3cdf04fec261567eeae79cf3c0a3f
1,581
require "rails_helper" RSpec.describe PdfConcatenator do include PdfHelper describe "#run" do it "fills PDFs and concatenates the resulting files" do form_one = double("form one", fill?: true, source_pdf_path: "spec/fixtures/test_fillable_pdf.pdf", output_file: Tempfile.new, attributes: { anyone_buys_food_separately_names: "Luigi Tester" }) form_two = double("form two", fill?: true, source_pdf_path: "spec/fixtures/test_fillable_pdf_2.pdf", output_file: Tempfile.new, attributes: { anyone_caretaker_names: "Christa Tester" }) verification_doc_one = double("verification doc 1", fill?: false, output_file: open("spec/fixtures/test_remote_pdf.pdf")) verification_doc_two = double("verification doc 1", fill?: false, output_file: open("spec/fixtures/test_remote_pdf.pdf")) output_file = PdfConcatenator.new([form_one, form_two, verification_doc_one, verification_doc_two]).run expect(output_file).to be_a(Tempfile) expect(PDF::Reader.new(output_file).page_count).to eq 4 result = filled_in_values(output_file.path) expect(result["anyone_buys_food_separately_names"]).to eq "Luigi Tester" expect(result["anyone_caretaker_names"]).to eq "Christa Tester" end end end
41.605263
109
0.5895
11635f5754145bf506a01cdf14642bb8e831325c
7,699
=begin #NSX-T Manager API #VMware NSX-T Manager REST API OpenAPI spec version: 2.5.1.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.4.19 =end require 'date' module NSXT # List of directory domain LDAP servers class DirectoryLdapServerListResults # Link to this resource attr_accessor :_self # The server will populate this field when returing the resource. Ignored on PUT and POST. attr_accessor :_links # Schema for this resource attr_accessor :_schema # Opaque cursor to be used for getting next page of records (supplied by current result page) attr_accessor :cursor # If true, results are sorted in ascending order attr_accessor :sort_ascending # Field by which records are sorted attr_accessor :sort_by # Count of results found (across all pages), set only on first page attr_accessor :result_count # List of directory domain LDAP servers attr_accessor :results # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'_self' => :'_self', :'_links' => :'_links', :'_schema' => :'_schema', :'cursor' => :'cursor', :'sort_ascending' => :'sort_ascending', :'sort_by' => :'sort_by', :'result_count' => :'result_count', :'results' => :'results' } end # Attribute type mapping. def self.swagger_types { :'_self' => :'SelfResourceLink', :'_links' => :'Array<ResourceLink>', :'_schema' => :'String', :'cursor' => :'String', :'sort_ascending' => :'BOOLEAN', :'sort_by' => :'String', :'result_count' => :'Integer', :'results' => :'Array<DirectoryLdapServer>' } 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?(:'_self') self._self = attributes[:'_self'] end if attributes.has_key?(:'_links') if (value = attributes[:'_links']).is_a?(Array) self._links = value end end if attributes.has_key?(:'_schema') self._schema = attributes[:'_schema'] end if attributes.has_key?(:'cursor') self.cursor = attributes[:'cursor'] end if attributes.has_key?(:'sort_ascending') self.sort_ascending = attributes[:'sort_ascending'] end if attributes.has_key?(:'sort_by') self.sort_by = attributes[:'sort_by'] end if attributes.has_key?(:'result_count') self.result_count = attributes[:'result_count'] end if attributes.has_key?(:'results') if (value = attributes[:'results']).is_a?(Array) self.results = value end 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 if @results.nil? invalid_properties.push('invalid value for "results", results cannot be nil.') end 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? return false if @results.nil? 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 && _self == o._self && _links == o._links && _schema == o._schema && cursor == o.cursor && sort_ascending == o.sort_ascending && sort_by == o.sort_by && result_count == o.result_count && results == o.results 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 [_self, _links, _schema, cursor, sort_ascending, sort_by, result_count, results].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the 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 = NSXT.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
28.943609
107
0.60878
1c8dfa4cfb81e2b57f9c44d1524a3d3def67da54
6,586
require 'zlib' class TDLibTLTypeInfo TLClass = Struct.new(:name, :comment) do def to_s name.to_s end def converter "typeof(TLObjectConverter)" end end Type = Struct.new(:name, :realname, :props, :type, :tl_class, :source, :comment) do def to_s name.to_s end def converter "typeof(TLObjectConverter)" end def type_id val = Zlib.crc32(source.scan(/[#\?\[\]=]|[A-Za-z0-9:_]+/).join(' ')) val -= 0x100000000 if val >= 0x80000000 val end end Property = Struct.new(:name, :capname, :type, :comment) do def to_s name.to_s end end class Int64 def self.to_s "long" end def self.converter "typeof(Int64Converter)" end end class Vector class << self attr_accessor :subtype, :item_converter @@subtypes = {} def to_s st, dim = nestinfo "#{st}#{"[]"*dim}" end def nestinfo dim = 1 st = subtype while st.is_a?(Class) && st <= Vector dim += 1 st = st.subtype end [st, dim] end def [](subtype) return @@subtypes[subtype] if @@subtypes[subtype] st = Class.new(Vector) st.subtype = subtype if subtype.is_a?(Class) && subtype <= Vector st.item_converter = subtype.item_converter else st.item_converter = subtype.converter if subtype.respond_to?(:converter) && subtype.converter end @@subtypes[subtype] = st st end def json_prop if item_converter return ["ItemConverterType = #{item_converter}"] end [] end # def respond_to_missing?(name, inc) # subtype.respond_to?(name, inc) # end # def method_missing(*args) # subtype.__send__(*args) # end end end BuiltinTypes = { double: "double", string: "string", int32: "int", int53: "long", int64: Int64, bytes: "Memory<byte>", vector: Vector, boolFalse: FalseClass, boolTrue: TrueClass, Bool: "bool" }.freeze Types = {} Functions = {} Classes = {} class LazyResolver def initialize(name) @name = name end def resolve AllDefinitions[@name] || Classes[@name] || @name end def to_s @name.to_s end def self.resolve(name) if name.is_a? LazyResolver return name.resolve elsif name.is_a? Symbol return AllDefinitions[name] || Classes[name] || name end return name end end class << self def load(tlfile=nil) tlfile = File.join(File.realpath(File.dirname(__FILE__)), 'td_api.tl') unless tlfile comments = [] File.open(tlfile, 'r') do |f| current = :type f.each_line do |line| line.strip! if line.start_with?('//') comments << line next end next if line.empty? if line == '---functions---' current = :function next end if line == '---types---' current = :type next end parse_line(line, current, comments) comments.clear end end Types.freeze Functions.freeze const_set(:AllDefinitions, Types.merge(Functions).freeze) AllDefinitions.each_value do |type| props = type.props props.each do |prop| ptype = prop.type if ptype.is_a? Symbol rbtype = AllDefinitions[ptype] || Classes[ptype] unless rbtype raise TypeError, "unknown TL type reference #{ptype} on #{type.inspect}" end prop.type = rbtype end prop.freeze end end end private def parse_typename(name) type, subtype = name.split("<", 2) type = type.intern rbtype = BuiltinTypes[type] || Types[type] || Classes[type] || LazyResolver.new(type) if subtype subtype.chop! if subtype[-1] == ">" subtype = parse_typename(subtype) else subtype = subtype.intern if subtype == :PageBlock nil end subtype = BuiltinTypes[subtype] || Types[subtype] || Classes[subtype] || LazyResolver.new(subtype) end rbtype = rbtype[subtype] end rbtype end TL_RE = /^((?:`[+-]`)|[a-zA-Z][a-zA-Z0-9]*)\s+(.*)\s*=\s*(\S(?:.*\S)?)\s*;$/ def parse_line(line, current, comments) md = TL_RE.match(line) return unless md typename = md[1].intern return BuiltinTypes[typename] if BuiltinTypes.key?(typename) info = Type.new info.name = typename.to_s.sub(/\A[a-z]/, &:upcase) info.realname = typename info.type = current info.source = line info.tl_class = md[3].intern stripped_comment = comments.map {|s| s.sub(%r(\A//), '').strip }.join(' ') comment_components = stripped_comment.scan(/@[^@]+/).each(&:strip!).map do |x| result = x.split(' ',2) result[0] = result[0][1..-1].intern result end if info.name != info.tl_class.to_s && info.type != :function unless Classes[info.tl_class] # STDERR.puts("Creating TL class #{info.tl_class}") tlc = TLClass.new tlc.name = info.tl_class Classes[info.tl_class] = tlc end else info.tl_class = "TLObject" if info.type != :function end if (index = comment_components.index{|x| x[0] == :class}) comment_components.delete_at(index) class_desc = comment_components[index] if class_desc if class_desc[0] == :description comment_components.delete_at(index) Classes[info.tl_class].comment = class_desc[1] end end end info.comment = comment_components.find{|x|x[0] == :description}&.fetch(1) props = md[2].split(' ') props.map! do |x| result = x.split(':') propname = result[0].intern capname = result[0].split('_').each(&:capitalize!).join proptype = parse_typename(result[1]) comment = comment_components.find{|x|x[0] == propname}&.fetch(1) Property.new(propname, capname, proptype, comment) end info.props = props.freeze (current == :function ? Functions : Types)[typename] = info info # rescue # raise TypeError, "error parsing TL: #{line.inspect}" end end end
23.862319
108
0.548588
3916008982df66ccc1fa2b57ce9a17d8e013543e
505
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::ApiManagement::Mgmt::V2018_06_01_preview module Models # # Defines values for SubscriptionState # module SubscriptionState Suspended = "suspended" Active = "active" Expired = "expired" Submitted = "submitted" Rejected = "rejected" Cancelled = "cancelled" end end end
24.047619
70
0.683168
abfe123626d0130531a95ad0cfbbadcb6e73a75c
1,422
class Manage::LibraryDocumentsController < Manage::ManagementController load_and_authorize_resource before_action :get_posts, only: [:new, :edit] before_action :get_library_section, only: [:new] def show end def new @library_document = @library_section.library_documents.build end def edit end def create if @library_document.save flash[:notice] = 'New library document created' else flash[:error] = 'Library document could not be created' end respond_with @library_document, location: manage_path end def update @library_document.update_attributes(library_document_params) respond_with @library_document, location: manage_library_document_path(@library_document) end def destroy @library_document.destroy respond_with @library_document, location: manage_path end def remove_attachment @library_document.update(attachment: nil) respond_with @library_document, location: edit_manage_library_document_path(@library_document) end protected def library_document_params params.require(:library_document).permit(:title, :order, :library_section_id, :post_id, :attachment) end def get_posts types = PostType.where(name: ['Resource Links', 'Handbooks']) @posts = Post.where(post_type: types) end def get_library_section @library_section = LibrarySection.find(params[:library_section_id]) end end
25.392857
104
0.755274
f82dff950316770726c8d655ba1a20d28b98a977
15,714
#-- 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. #++ require 'spec_helper' describe User, 'allowed_to?' do let(:user) { FactoryGirl.build(:user) } let(:anonymous) { FactoryGirl.build(:anonymous) } let(:project) { FactoryGirl.build(:project, is_public: false) } let(:project2) { FactoryGirl.build(:project, is_public: false) } let(:role) { FactoryGirl.build(:role) } let(:role2) { FactoryGirl.build(:role) } let(:anonymous_role) { FactoryGirl.build(:anonymous_role) } let(:member) { FactoryGirl.build(:member, project: project, roles: [role], principal: user) } let(:member2) { FactoryGirl.build(:member, project: project2, roles: [role2], principal: user) } before do anonymous_role.save! Role.non_member user.save! end shared_examples_for 'w/ inquiring for project' do let(:permission) { :add_work_packages } let(:final_setup_step) {} context 'w/ the user being admin' do before do user.update_attribute(:admin, true) project.save final_setup_step end it 'should be true' do expect(user.allowed_to?(permission, project)).to be_truthy end end context 'w/ the user being admin w/ the project being archived' do before do user.update_attribute(:admin, true) project.update_attribute(:status, Project::STATUS_ARCHIVED) final_setup_step end it 'should be false' do expect(user.allowed_to?(permission, project)).to be_falsey end end context 'w/ the user being admin w/ the project module the permission belongs to being inactive' do before do user.update_attribute(:admin, true) project.enabled_module_names = [] final_setup_step end it 'should be false' do expect(user.allowed_to?(permission, project)).to be_falsey end end context 'w/ the user being a member in the project w/o the role having the necessary permission' do before do member.save! final_setup_step end it 'should be false' do expect(user.allowed_to?(permission, project)).to be_falsey end end context 'w/ the user being a member in the project w/ the role having the necessary permission' do before do role.add_permission! permission member.save! final_setup_step end it 'should be true' do expect(user.allowed_to?(permission, project)).to be_truthy end end context 'w/ the user being a member in the project w/ the role having the necessary permission w/o the module being active' do let(:permission) { :view_news } before do role.add_permission! permission project.enabled_module_names = [] member.save! final_setup_step end it 'should be false' do expect(user.allowed_to?(permission, project)).to be_falsey end end context 'w/ the user being a member in the project w/ the role having the necessary permission w/ asking for a controller/action hash w/o the module being active' do let(:permission) { { controller: 'news', action: 'show' } } before do role.add_permission! permission project.enabled_module_names = [] member.save! final_setup_step end it 'should be false' do expect(user.allowed_to?(permission, project)).to be_falsey end end context 'w/ the user being a member in the project w/o the role having the necessary permission w/ non members having the necessary permission' do before do project.is_public = false non_member = Role.non_member non_member.add_permission! permission member.save! final_setup_step end it 'should be false' do expect(user.allowed_to?(permission, project)).to be_falsey end end context 'w/ the user being a member in the project w/o the role having the necessary permission w/ inquiring for a permission that is public' do let(:permission) { :view_project } before do project.is_public = false member.save! final_setup_step end it 'should be true' do expect(user.allowed_to?(permission, project)).to be_truthy end end context 'w/o the user being member in the project w/ non member being allowed the action w/ the project being private' do before do project.is_public = false project.save! non_member = Role.non_member non_member.add_permission! permission final_setup_step end it 'should be false' do expect(user.allowed_to?(permission, project)).to be_falsey end end context 'w/o the user being member in the project w/ the project being public w/ non members being allowed the action' do before do project.is_public = true project.save! non_member = Role.non_member non_member.add_permission! permission final_setup_step end it 'should be true' do expect(user.allowed_to?(permission, project)).to be_truthy end end context 'w/ the user being member in the project w/ the project being public w/ non members being allowed the action w/o the role being allowed the action' do before do project.is_public = true project.save! non_member = Role.non_member non_member.add_permission! permission member.save! final_setup_step end it 'should be false' do expect(user.allowed_to?(permission, project)).to be_falsey end end context 'w/ the user being anonymous w/ the project being public w/ anonymous being allowed the action' do before do project.is_public = true project.save! anonymous_role.add_permission! permission final_setup_step end it 'should be true' do expect(anonymous.allowed_to?(permission, project)).to be_truthy end end context 'w/ the user being anonymous w/ the project being public w/ querying for a public permission' do let(:permission) { :view_project } before do project.is_public = true project.save! anonymous_role.save! final_setup_step end it 'should be true' do expect(anonymous.allowed_to?(permission, project)).to be_truthy end end context 'w/ the user being anonymous w/ requesting a controller and action allowed by multiple permissions w/ the project being public w/ anonymous being allowed the action' do let(:permission) { { controller: 'projects', action: 'settings' } } before do project.is_public = true project.save! anonymous_role.add_permission! :manage_categories final_setup_step end it 'should be true' do expect(anonymous.allowed_to?(permission, project)) .to be_truthy end end context 'w/ the user being anonymous w/ the project being public w/ anonymous being not allowed the action' do before do project.is_public = true project.save! final_setup_step end it 'should be false' do expect(anonymous.allowed_to?(permission, project)).to be_falsey end end context 'w/ the user being a member in two projects w/ the user being allowed the action in both projects' do before do role.add_permission! permission role2.add_permission! permission member.save! member2.save! final_setup_step end it 'should be true' do expect(user.allowed_to?(permission, [project, project2])).to be_truthy end end context 'w/ the user being a member in two projects w/ the user being allowed in only one project' do before do role.add_permission! permission member.save! member2.save! final_setup_step end it 'should be false' do expect(user.allowed_to?(permission, [project, project2])).to be_falsey end end context 'w/o the user being a member in the two projects w/ both projects being public w/ non member being allowed the action' do before do non_member = Role.non_member non_member.add_permission! permission project.update_attribute(:is_public, true) project2.update_attribute(:is_public, true) final_setup_step end it 'should be true' do expect(user.allowed_to?(permission, [project, project2])).to be_truthy end end context 'w/o the user being a member in the two projects w/ only one project being public w/ non member being allowed the action' do before do non_member = Role.non_member non_member.add_permission! permission project.update_attribute(:is_public, true) project2.update_attribute(:is_public, false) final_setup_step end it 'should be false' do expect(user.allowed_to?(permission, [project, project2])).to be_falsey end end context 'w/ requesting a controller and action w/ the user being allowed the action' do before do role.add_permission! permission member.save! final_setup_step end it 'should be true' do expect(user.allowed_to?({ controller: 'work_packages', action: 'new' }, project)) .to be_truthy end end context 'w/ requesting a controller and action allowed by multiple permissions w/ the user being allowed the action' do let(:permission) { :manage_categories } before do role.add_permission! permission member.save! final_setup_step end it 'should be true' do expect(user.allowed_to?({ controller: 'projects', action: 'settings' }, project)) .to be_truthy end end end shared_examples_for 'w/ inquiring globally' do let(:permission) { :add_work_packages } let(:final_setup_step) {} context 'w/ the user being admin' do before do user.admin = true user.save! final_setup_step end it 'should be true' do expect(user.allowed_to?(permission, nil, global: true)).to be_truthy end end context 'w/ the user being a member in a project w/o the role having the necessary permission' do before do member.save! final_setup_step end it 'should be false' do expect(user.allowed_to?(permission, nil, global: true)).to be_falsey end end context 'w/ the user being a member in the project w/ the role having the necessary permission' do before do role.add_permission! permission member.save! final_setup_step end it 'should be true' do expect(user.allowed_to?(permission, nil, global: true)).to be_truthy end end context 'w/ the user being a member in the project w/ inquiring for controller and action w/ the role having the necessary permission' do before do role.add_permission! permission member.save! final_setup_step end it 'should be true' do expect(user.allowed_to?({ controller: 'work_packages', action: 'new' }, nil, global: true)) .to be_truthy end end context 'w/ the user being a member in the project w/o the role having the necessary permission w/ non members having the necessary permission' do before do non_member = Role.non_member non_member.add_permission! permission member.save! final_setup_step end it 'should be true' do expect(user.allowed_to?(permission, nil, global: true)).to be_truthy end end context 'w/o the user being a member in the project w/ non members being allowed the action' do before do non_member = Role.non_member non_member.add_permission! permission final_setup_step end it 'should be true' do expect(user.allowed_to?(permission, nil, global: true)).to be_truthy end end context 'w/ the user being anonymous w/ anonymous being allowed the action' do before do anonymous_role.add_permission! permission final_setup_step end it 'should be true' do expect(anonymous.allowed_to?(permission, nil, global: true)).to be_truthy end end context 'w/ requesting a controller and action allowed by multiple permissions w/ the user being a member in the project w/o the role having the necessary permission w/ non members having the necessary permission' do let(:permission) { :manage_categories } before do non_member = Role.non_member non_member.add_permission! permission member.save! final_setup_step end it 'should be true' do expect(user.allowed_to?({ controller: 'projects', action: 'settings' }, nil, global: true)) .to be_truthy end end context 'w/ the user being anonymous w/ anonymous being not allowed the action' do before do final_setup_step end it 'should be false' do expect(anonymous.allowed_to?(permission, nil, global: true)).to be_falsey end end end context 'w/o preloaded permissions' do it_behaves_like 'w/ inquiring for project' it_behaves_like 'w/ inquiring globally' end context 'w/ preloaded permissions' do it_behaves_like 'w/ inquiring for project' do let(:final_setup_step) { user.preload_projects_allowed_to(permission) } end end end
26.499157
99
0.626702
183528e9861ea754d7e86f49fd61d3e13ad2f571
6,346
#! /usr/bin/env ruby require 'spec_helper' provider_class = Puppet::Type.type(:package).provider(:yum) describe provider_class do include PuppetSpec::Fixtures it_behaves_like 'RHEL package provider', provider_class, 'yum' describe "when supplied the source param" do let(:name) { 'baz' } let(:resource) do Puppet::Type.type(:package).new( :name => name, :provider => 'yum', ) end let(:provider) do provider = provider_class.new provider.resource = resource provider end before { provider_class.stubs(:command).with(:cmd).returns("/usr/bin/yum") } context "when installing" do it "should use the supplied source as the explicit path to a package to install" do resource[:ensure] = :present resource[:source] = "/foo/bar/baz-1.1.0.rpm" provider.expects(:execute).with(["/usr/bin/yum", "-d", "0", "-e", "0", "-y", :install, "/foo/bar/baz-1.1.0.rpm"]) provider.install end end context "when ensuring a specific version" do it "should use the suppplied source as the explicit path to the package to update" do # The first query response informs yum provider that package 1.1.0 is # already installed, and the second that it's been upgraded provider.expects(:query).twice.returns({:ensure => "1.1.0"}, {:ensure => "1.2.0"}) resource[:ensure] = "1.2.0" resource[:source] = "http://foo.repo.com/baz-1.2.0.rpm" provider.expects(:execute).with(["/usr/bin/yum", "-d", "0", "-e", "0", "-y", 'update', "http://foo.repo.com/baz-1.2.0.rpm"]) provider.install end end end describe "parsing the output of check-update" do describe "with no multiline entries" do let(:check_update) { File.read(my_fixture("yum-check-update-simple.txt")) } let(:output) { described_class.parse_updates(check_update) } it 'creates an entry for each package keyed on the package name' do expect(output['curl']).to eq([{:name => 'curl', :epoch => '0', :version => '7.32.0', :release => '10.fc20', :arch => 'i686'}, {:name => 'curl', :epoch => '0', :version => '7.32.0', :release => '10.fc20', :arch => 'x86_64'}]) expect(output['gawk']).to eq([{:name => 'gawk', :epoch => '0', :version => '4.1.0', :release => '3.fc20', :arch => 'i686'}]) expect(output['dhclient']).to eq([{:name => 'dhclient', :epoch => '12', :version => '4.1.1', :release => '38.P1.fc20', :arch => 'i686'}]) expect(output['selinux-policy']).to eq([{:name => 'selinux-policy', :epoch => '0', :version => '3.12.1', :release => '163.fc20', :arch => 'noarch'}]) end it 'creates an entry for each package keyed on the package name and package architecture' do expect(output['curl.i686']).to eq([{:name => 'curl', :epoch => '0', :version => '7.32.0', :release => '10.fc20', :arch => 'i686'}]) expect(output['curl.x86_64']).to eq([{:name => 'curl', :epoch => '0', :version => '7.32.0', :release => '10.fc20', :arch => 'x86_64'}]) expect(output['gawk.i686']).to eq([{:name => 'gawk', :epoch => '0', :version => '4.1.0', :release => '3.fc20', :arch => 'i686'}]) expect(output['dhclient.i686']).to eq([{:name => 'dhclient', :epoch => '12', :version => '4.1.1', :release => '38.P1.fc20', :arch => 'i686'}]) expect(output['selinux-policy.noarch']).to eq([{:name => 'selinux-policy', :epoch => '0', :version => '3.12.1', :release => '163.fc20', :arch => 'noarch'}]) expect(output['java-1.8.0-openjdk.x86_64']).to eq([{:name => 'java-1.8.0-openjdk', :epoch => '1', :version => '1.8.0.131', :release => '2.b11.el7_3', :arch => 'x86_64'}]) end end describe "with multiline entries" do let(:check_update) { File.read(my_fixture("yum-check-update-multiline.txt")) } let(:output) { described_class.parse_updates(check_update) } it "parses multi-line values as a single package tuple" do expect(output['libpcap']).to eq([{:name => 'libpcap', :epoch => '14', :version => '1.4.0', :release => '1.20130826git2dbcaa1.el6', :arch => 'x86_64'}]) end end describe "with obsoleted packages" do let(:check_update) { File.read(my_fixture("yum-check-update-obsoletes.txt")) } let(:output) { described_class.parse_updates(check_update) } it "ignores all entries including and after 'Obsoleting Packages'" do expect(output).not_to include("Obsoleting") expect(output).not_to include("NetworkManager-bluetooth.x86_64") expect(output).not_to include("1:1.0.0-14.git20150121.b4ea599c.el7") end end describe "with security notifications" do let(:check_update) { File.read(my_fixture("yum-check-update-security.txt")) } let(:output) { described_class.parse_updates(check_update) } it "ignores all entries including and after 'Security'" do expect(output).not_to include("Security") end it "includes updates before 'Security'" do expect(output).to include("yum-plugin-fastestmirror.noarch") end end describe "with broken update notices" do let(:check_update) { File.read(my_fixture("yum-check-update-broken-notices.txt")) } let(:output) { described_class.parse_updates(check_update) } it "ignores all entries including and after 'Update'" do expect(output).not_to include("Update") end it "includes updates before 'Update'" do expect(output).to include("yum-plugin-fastestmirror.noarch") end end describe "with improper package names in output" do it "raises an exception parsing package name" do expect { described_class.update_to_hash('badpackagename', '1') }.to raise_exception(Exception, /Failed to parse/) end end describe "with trailing plugin output" do let(:check_update) { File.read(my_fixture("yum-check-update-plugin-output.txt")) } let(:output) { described_class.parse_updates(check_update) } it "parses correctly formatted entries" do expect(output['bash']).to eq([{:name => 'bash', :epoch => '0', :version => '4.2.46', :release => '12.el7', :arch => 'x86_64'}]) end it "ignores all mentions of plugin output" do expect(output).not_to include("Random plugin") end end end end
51.177419
232
0.61913
6a007ba625a5ed63655d3e011b560aaf241b3226
4,271
# Sample schema: # create_table "users", :force => true do |t| # t.column "login", :string, :limit => 40 # t.column "email", :string, :limit => 100 # t.column "crypted_password", :string, :limit => 40 # t.column "salt", :string, :limit => 40 # t.column "activation_code", :string, :limit => 40 # only if you want # t.column "activated_at", :datetime # user activation # t.column "created_at", :datetime # t.column "updated_at", :datetime # end # # If you wish to have a mailer, run: # # ./script/generate authenticated_mailer user # # Be sure to add the observer to the form login controller: # # class AccountController < ActionController::Base # observer :user_observer # end # # For extra credit: keep these two requires for 2-way reversible encryption # require 'openssl' # require 'base64' # require 'digest/sha1' class User < ActiveRecord::Base has_many :photos has_many :albums # Virtual attribute for the unencrypted password attr_accessor :password validates_uniqueness_of :login, :email, :salt validates_length_of :login, :within => 3..40 validates_length_of :email, :within => 3..100 validates_length_of :password, :within => 4..40, :if => :password_required? validates_presence_of :login, :email, :first, :last validates_presence_of :password, :password_confirmation, :if => :password_required? validates_confirmation_of :password, :if => :password_required? before_save :encrypt_password # Uncomment this to use activation # before_create :make_activation_code # Authenticates a user by their login name and unencrypted password. Returns the user or nil. def self.authenticate(login, password) # use this instead if you want user activation # u = find :first, :select => 'id, salt', :conditions => ['login = ? and activated_at IS NOT NULL', login] u = find_by_login(login) # need to get the salt return nil unless u find :first, :conditions => ["id = ? AND crypted_password = ?", u.id, u.encrypt(password)] end # Encrypts some data with the salt. def self.encrypt(password, salt) Digest::SHA1.hexdigest("--#{salt}--#{password}--") end # Encrypts the password with the user salt def encrypt(password) self.class.encrypt(password, salt) end def full_name self.first + " " + self.last end def is_admin? false end # More extra credit for adding 2-way encryption. Feel free to remove self.encrypt above if you use this # # # Encrypts some data with the salt. # def self.encrypt(password, salt) # enc = OpenSSL::Cipher::Cipher.new('DES-EDE3-CBC') # enc.encrypt(salt) # data = enc.update(password) # Base64.encode64(data << enc.final) # end # # # getter method to decrypt password # def password # unless @password # enc = OpenSSL::Cipher::Cipher.new('DES-EDE3-CBC') # enc.decrypt(salt) # text = enc.update(Base64.decode64(crypted_password)) # @password = (text << enc.final) # end # @password # rescue # nil # end # Uncomment these methods for user activation These also help let the mailer know precisely when the user is activated. # There's also a commented-out before hook above and a protected method below. # # The controller has a commented-out 'activate' action too. # # # Activates the user in the database. # def activate # @activated = true # update_attributes(:activated_at => Time.now.utc, :activation_code => nil) # end # # # Returns true if the user has just been activated. # def recently_activated? # @activated # end protected # before filter def encrypt_password return unless password self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record? self.crypted_password = encrypt(password) end def password_required? crypted_password.nil? or not password.blank? end # If you're going to use activation, uncomment this too #def make_activation_code # self.activation_code = Digest::SHA1.hexdigest( Time.now.to_s.split('//').sort_by {rand}.join ) #end end
32.356061
122
0.657926
217ec6efc1c1433515b5d03a8d85eb1f88f370f9
796
require 'rails_helper' describe 'ルーティング' do example '職員トップページ' do expect(get: 'http://baukis.example.com').to route_to( host: 'baukis.example.com', controller: 'staff/top', action: 'index' ) end example '管理者ログインフォーム' do expect(get: 'http://baukis.example.com/admin/login').to route_to( host: 'baukis.example.com', controller: 'admin/sessions', action: 'new' ) end example 'ホスト名が対象外ならerrors/not_foundへ' do expect(get: 'http://foo.example.jp').to route_to( controller: 'errors', action: 'routing_error' ) end example '存在しないパスからerrors/not_foundへ' do expect(get: 'http://baukis.example.com/xyz').to route_to( controller: 'errors', action: 'routing_error', anything: 'xyz' ) end end
22.742857
69
0.63191
330202bb624e5c1d05466867165210511b1f9e0c
686
class ProfileJSON < RSpec::Core::Formatters::JsonFormatter RSpec::Core::Formatters.register self def initialize(*args) RSpec.configure{|c| c.add_formatter(:progress)} super(*args) end def close(_notification) collected_output = [] @output_hash[:examples].map do |ex| collected_output << { :description => ex[:full_description], :staus => ex[:status], :run_time => ex[:run_time], :exception => ex[:exception] } end require 'json' output.puts("== BEGIN_JSON_PROFILE ==") output.puts JSON.pretty_generate(collected_output.sort_by{|x| x[:run_time]}) output.puts("== END_JSON_PROFILE ==") end end
25.407407
80
0.641399
aca1d47fb6ae942fce7f2174684162fdc2ef46e1
3,784
module Gameball class Transaction # include Gameball::Utils def self.get_player_balance(playerId) hashedBody = Gameball::Utils::hashBody(playerUniqueId: playerId) body = { playerUniqueId: playerId, hash: hashedBody } res = Gameball::Utils::request("post", "/integrations/transaction/balance", body) unless res.kind_of? Net::HTTPSuccess raise Gameball::GameballError.new(res.body) else return res end end def self.hold_points(body) # puts body # check if attributes are available Gameball::Utils.validate(body, ["playerUniqueId", "amount"], ["otp"]) body[:transactionTime] = Time.now.utc body = Gameball::Utils::extractAttributesToHash(body) res = Gameball::Utils::request("post", "/integrations/transaction/hold", body) unless res.kind_of? Net::HTTPSuccess if res.kind_of? Net::HTTPInternalServerError raise Gameball::GameballError.new("An Internal Server Error has occurred") else raise Gameball::GameballError.new(res.body) end else return res end end def self.redeem_points(body) # check if attributes are available Gameball::Utils.validate(body, ["holdReference", "playerUniqueId", "transactionId"], []) body[:transactionTime] = Time.now.utc body = Gameball::Utils::extractAttributesToHash(body) res = Gameball::Utils::request("post", "/integrations/transaction/redeem", body) unless res.kind_of? Net::HTTPSuccess if res.kind_of? Net::HTTPInternalServerError raise Gameball::GameballError.new("An Internal Server Error has occurred") else raise Gameball::GameballError.new(res.body) end else return res end end def self.reverse_transaction(body) Gameball::Utils.validate(body, ["reversedTransactionId", "playerUniqueId", "transactionId"], []) body[:transactionTime] = Time.now.utc body = Gameball::Utils::extractAttributesToHash(body) res = Gameball::Utils::request("post", "/integrations/transaction/cancel", body) unless res.kind_of? Net::HTTPSuccess if res.kind_of? Net::HTTPInternalServerError raise Gameball::GameballError.new("An Internal Server Error has occurred") else raise Gameball::GameballError.new(res.body) end else return res end end def self.reward_points(body) Gameball::Utils.validate(body, ["playerUniqueId", "amount", "transactionId"], ["playerAttributes"]) body[:transactionTime] = Time.now.utc body = Gameball::Utils::extractAttributesToHash(body) res = Gameball::Utils::request("post", "/integrations/transaction/reward", body) unless res.kind_of? Net::HTTPSuccess if res.kind_of? Net::HTTPInternalServerError raise Gameball::GameballError.new("An Internal Server Error has occurred") else raise Gameball::GameballError.new(res.body) end else return true end end def self.reverse_hold(body) # check if holdReference is in body else throw error Gameball::Utils.validate(body, ["holdReference", "playerUniqueId"], []) body[:transactionTime] = Time.now.utc body = Gameball::Utils::extractAttributesToHash(body) res = Gameball::Utils::request("post", "/integrations/transaction/hold", body) unless res.kind_of? Net::HTTPSuccess if res.kind_of? Net::HTTPInternalServerError raise Gameball::GameballError.new("An Internal Server Error has occurred") else raise Gameball::GameballError.new(res.body) end else return res end end end end
37.84
105
0.657505
ffa89e855d8fbdbd8d776551f8fcc0aff151b8f0
18,964
# encoding: utf-8 require 'spec_helper' describe Grape::Validations::CoerceValidator do subject do Class.new(Grape::API) end def app subject end describe 'coerce' do module CoerceValidatorSpec class User include Virtus.model attribute :id, Integer attribute :name, String end end context 'i18n' do after :each do I18n.locale = :en end it 'i18n error on malformed input' do I18n.load_path << File.expand_path('../zh-CN.yml', __FILE__) I18n.reload! I18n.locale = 'zh-CN'.to_sym subject.params do requires :age, type: Integer end subject.get '/single' do 'int works' end get '/single', age: '43a' expect(last_response.status).to eq(400) expect(last_response.body).to eq('年龄格式不正确') end it 'gives an english fallback error when default locale message is blank' do I18n.locale = 'pt-BR'.to_sym subject.params do requires :age, type: Integer end subject.get '/single' do 'int works' end get '/single', age: '43a' expect(last_response.status).to eq(400) expect(last_response.body).to eq('age is invalid') end end it 'error on malformed input' do subject.params do requires :int, type: Integer end subject.get '/single' do 'int works' end get '/single', int: '43a' expect(last_response.status).to eq(400) expect(last_response.body).to eq('int is invalid') get '/single', int: '43' expect(last_response.status).to eq(200) expect(last_response.body).to eq('int works') end it 'error on malformed input (Array)' do subject.params do requires :ids, type: Array[Integer] end subject.get '/array' do 'array int works' end get 'array', ids: %w(1 2 az) expect(last_response.status).to eq(400) expect(last_response.body).to eq('ids is invalid') get 'array', ids: %w(1 2 890) expect(last_response.status).to eq(200) expect(last_response.body).to eq('array int works') end context 'complex objects' do it 'error on malformed input for complex objects' do subject.params do requires :user, type: CoerceValidatorSpec::User end subject.get '/user' do 'complex works' end get '/user', user: '32' expect(last_response.status).to eq(400) expect(last_response.body).to eq('user is invalid') get '/user', user: { id: 32, name: 'Bob' } expect(last_response.status).to eq(200) expect(last_response.body).to eq('complex works') end end context 'coerces' do it 'Integer' do subject.params do requires :int, coerce: Integer end subject.get '/int' do params[:int].class end get '/int', int: '45' expect(last_response.status).to eq(200) expect(last_response.body).to eq('Fixnum') end context 'Array' do it 'Array of Integers' do subject.params do requires :arry, coerce: Array[Integer] end subject.get '/array' do params[:arry][0].class end get '/array', arry: %w(1 2 3) expect(last_response.status).to eq(200) expect(last_response.body).to eq('Fixnum') end it 'Array of Bools' do subject.params do requires :arry, coerce: Array[Virtus::Attribute::Boolean] end subject.get '/array' do params[:arry][0].class end get 'array', arry: [1, 0] expect(last_response.status).to eq(200) expect(last_response.body).to eq('TrueClass') end it 'Array of Complex' do subject.params do requires :arry, coerce: Array[CoerceValidatorSpec::User] end subject.get '/array' do params[:arry].size end get 'array', arry: [31] expect(last_response.status).to eq(400) expect(last_response.body).to eq('arry is invalid') get 'array', arry: { id: 31, name: 'Alice' } expect(last_response.status).to eq(400) expect(last_response.body).to eq('arry is invalid') get 'array', arry: [{ id: 31, name: 'Alice' }] expect(last_response.status).to eq(200) expect(last_response.body).to eq('1') end end context 'Set' do it 'Set of Integers' do subject.params do requires :set, coerce: Set[Integer] end subject.get '/set' do params[:set].first.class end get '/set', set: Set.new([1, 2, 3, 4]).to_a expect(last_response.status).to eq(200) expect(last_response.body).to eq('Fixnum') end it 'Set of Bools' do subject.params do requires :set, coerce: Set[Virtus::Attribute::Boolean] end subject.get '/set' do params[:set].first.class end get '/set', set: Set.new([1, 0]).to_a expect(last_response.status).to eq(200) expect(last_response.body).to eq('TrueClass') end end it 'Bool' do subject.params do requires :bool, coerce: Virtus::Attribute::Boolean end subject.get '/bool' do params[:bool].class end get '/bool', bool: 1 expect(last_response.status).to eq(200) expect(last_response.body).to eq('TrueClass') get '/bool', bool: 0 expect(last_response.status).to eq(200) expect(last_response.body).to eq('FalseClass') get '/bool', bool: 'false' expect(last_response.status).to eq(200) expect(last_response.body).to eq('FalseClass') get '/bool', bool: 'true' expect(last_response.status).to eq(200) expect(last_response.body).to eq('TrueClass') end it 'Rack::Multipart::UploadedFile' do subject.params do requires :file, type: Rack::Multipart::UploadedFile end subject.post '/upload' do params[:file].filename end post '/upload', file: Rack::Test::UploadedFile.new(__FILE__) expect(last_response.status).to eq(201) expect(last_response.body).to eq(File.basename(__FILE__).to_s) post '/upload', file: 'not a file' expect(last_response.status).to eq(400) expect(last_response.body).to eq('file is invalid') end it 'File' do subject.params do requires :file, coerce: File end subject.post '/upload' do params[:file].filename end post '/upload', file: Rack::Test::UploadedFile.new(__FILE__) expect(last_response.status).to eq(201) expect(last_response.body).to eq(File.basename(__FILE__).to_s) post '/upload', file: 'not a file' expect(last_response.status).to eq(400) expect(last_response.body).to eq('file is invalid') end it 'Nests integers' do subject.params do requires :integers, type: Hash do requires :int, coerce: Integer end end subject.get '/int' do params[:integers][:int].class end get '/int', integers: { int: '45' } expect(last_response.status).to eq(200) expect(last_response.body).to eq('Fixnum') end end context 'using coerce_with' do it 'uses parse where available' do subject.params do requires :ints, type: Array, coerce_with: JSON do requires :i, type: Integer requires :j end end subject.get '/ints' do ints = params[:ints].first 'coercion works' if ints[:i] == 1 && ints[:j] == '2' end get '/ints', ints: [{ i: 1, j: '2' }] expect(last_response.status).to eq(400) expect(last_response.body).to eq('ints is invalid') get '/ints', ints: '{"i":1,"j":"2"}' expect(last_response.status).to eq(400) expect(last_response.body).to eq('ints[0][i] is missing, ints[0][i] is invalid, ints[0][j] is missing') get '/ints', ints: '[{"i":"1","j":"2"}]' expect(last_response.status).to eq(200) expect(last_response.body).to eq('coercion works') end it 'accepts any callable' do subject.params do requires :ints, type: Hash, coerce_with: JSON.method(:parse) do requires :int, type: Integer, coerce_with: ->(val) { val == 'three' ? 3 : val } end end subject.get '/ints' do params[:ints][:int] end get '/ints', ints: '{"int":"3"}' expect(last_response.status).to eq(400) expect(last_response.body).to eq('ints[int] is invalid') get '/ints', ints: '{"int":"three"}' expect(last_response.status).to eq(200) expect(last_response.body).to eq('3') get '/ints', ints: '{"int":3}' expect(last_response.status).to eq(200) expect(last_response.body).to eq('3') end it 'must be supplied with :type or :coerce' do expect do subject.params do requires :ints, coerce_with: JSON end end.to raise_error(ArgumentError) end end context 'first-class JSON' do it 'parses objects and arrays' do subject.params do requires :splines, type: JSON do requires :x, type: Integer, values: [1, 2, 3] optional :ints, type: Array[Integer] optional :obj, type: Hash do optional :y end end end subject.get '/' do if params[:splines].is_a? Hash params[:splines][:obj][:y] else 'arrays work' if params[:splines].any? { |s| s.key? :obj } end end get '/', splines: '{"x":1,"ints":[1,2,3],"obj":{"y":"woof"}}' expect(last_response.status).to eq(200) expect(last_response.body).to eq('woof') get '/', splines: '[{"x":2,"ints":[]},{"x":3,"ints":[4],"obj":{"y":"quack"}}]' expect(last_response.status).to eq(200) expect(last_response.body).to eq('arrays work') get '/', splines: '{"x":4,"ints":[2]}' expect(last_response.status).to eq(400) expect(last_response.body).to eq('splines[x] does not have a valid value') get '/', splines: '[{"x":1,"ints":[]},{"x":4,"ints":[]}]' expect(last_response.status).to eq(400) expect(last_response.body).to eq('splines[x] does not have a valid value') end it 'works when declared optional' do subject.params do optional :splines, type: JSON do requires :x, type: Integer, values: [1, 2, 3] optional :ints, type: Array[Integer] optional :obj, type: Hash do optional :y end end end subject.get '/' do if params[:splines].is_a? Hash params[:splines][:obj][:y] else 'arrays work' if params[:splines].any? { |s| s.key? :obj } end end get '/', splines: '{"x":1,"ints":[1,2,3],"obj":{"y":"woof"}}' expect(last_response.status).to eq(200) expect(last_response.body).to eq('woof') get '/', splines: '[{"x":2,"ints":[]},{"x":3,"ints":[4],"obj":{"y":"quack"}}]' expect(last_response.status).to eq(200) expect(last_response.body).to eq('arrays work') get '/', splines: '{"x":4,"ints":[2]}' expect(last_response.status).to eq(400) expect(last_response.body).to eq('splines[x] does not have a valid value') get '/', splines: '[{"x":1,"ints":[]},{"x":4,"ints":[]}]' expect(last_response.status).to eq(400) expect(last_response.body).to eq('splines[x] does not have a valid value') end it 'accepts Array[JSON] shorthand' do subject.params do requires :splines, type: Array[JSON] do requires :x, type: Integer, values: [1, 2, 3] requires :y end end subject.get '/' do params[:splines].first[:y].class.to_s spline = params[:splines].first "#{spline[:x].class}.#{spline[:y].class}" end get '/', splines: '{"x":"1","y":"woof"}' expect(last_response.status).to eq(200) expect(last_response.body).to eq('Fixnum.String') get '/', splines: '[{"x":1,"y":2},{"x":1,"y":"quack"}]' expect(last_response.status).to eq(200) expect(last_response.body).to eq('Fixnum.Fixnum') get '/', splines: '{"x":"4","y":"woof"}' expect(last_response.status).to eq(400) expect(last_response.body).to eq('splines[x] does not have a valid value') get '/', splines: '[{"x":"4","y":"woof"}]' expect(last_response.status).to eq(400) expect(last_response.body).to eq('splines[x] does not have a valid value') end it "doesn't make sense using coerce_with" do expect do subject.params do requires :bad, type: JSON, coerce_with: JSON do requires :x end end end.to raise_error(ArgumentError) expect do subject.params do requires :bad, type: Array[JSON], coerce_with: JSON do requires :x end end end.to raise_error(ArgumentError) end end context 'multiple types' do Boolean = Grape::API::Boolean it 'coerces to first possible type' do subject.params do requires :a, types: [Boolean, Integer, String] end subject.get '/' do params[:a].class.to_s end get '/', a: 'true' expect(last_response.status).to eq(200) expect(last_response.body).to eq('TrueClass') get '/', a: '5' expect(last_response.status).to eq(200) expect(last_response.body).to eq('Fixnum') get '/', a: 'anything else' expect(last_response.status).to eq(200) expect(last_response.body).to eq('String') end it 'fails when no coercion is possible' do subject.params do requires :a, types: [Boolean, Integer] end subject.get '/' do params[:a].class.to_s end get '/', a: true expect(last_response.status).to eq(200) expect(last_response.body).to eq('TrueClass') get '/', a: 'not good' expect(last_response.status).to eq(400) expect(last_response.body).to eq('a is invalid') end context 'for primitive collections' do before do subject.params do optional :a, types: [String, Array[String]] optional :b, types: [Array[Integer], Array[String]] optional :c, type: Array[Integer, String] optional :d, types: [Integer, String, Set[Integer, String]] end subject.get '/' do ( params[:a] || params[:b] || params[:c] || params[:d] ).inspect end end it 'allows singular form declaration' do get '/', a: 'one way' expect(last_response.status).to eq(200) expect(last_response.body).to eq('"one way"') get '/', a: %w(the other) expect(last_response.status).to eq(200) expect(last_response.body).to eq('["the", "other"]') get '/', a: { a: 1, b: 2 } expect(last_response.status).to eq(400) expect(last_response.body).to eq('a is invalid') get '/', a: [1, 2, 3] expect(last_response.status).to eq(200) expect(last_response.body).to eq('["1", "2", "3"]') end it 'allows multiple collection types' do get '/', b: [1, 2, 3] expect(last_response.status).to eq(200) expect(last_response.body).to eq('[1, 2, 3]') get '/', b: %w(1 2 3) expect(last_response.status).to eq(200) expect(last_response.body).to eq('[1, 2, 3]') get '/', b: [1, true, 'three'] expect(last_response.status).to eq(200) expect(last_response.body).to eq('["1", "true", "three"]') end it 'allows collections with multiple types' do get '/', c: [1, '2', true, 'three'] expect(last_response.status).to eq(200) expect(last_response.body).to eq('[1, 2, "true", "three"]') get '/', d: '1' expect(last_response.status).to eq(200) expect(last_response.body).to eq('1') get '/', d: 'one' expect(last_response.status).to eq(200) expect(last_response.body).to eq('"one"') get '/', d: %w(1 two) expect(last_response.status).to eq(200) expect(last_response.body).to eq('#<Set: {1, "two"}>') end end context 'custom coercion rules' do before do subject.params do requires :a, types: [Boolean, String], coerce_with: (lambda do |val| if val == 'yup' true elsif val == 'false' 0 else val end end) end subject.get '/' do params[:a].class.to_s end end it 'respects :coerce_with' do get '/', a: 'yup' expect(last_response.status).to eq(200) expect(last_response.body).to eq('TrueClass') end it 'still validates type' do get '/', a: 'false' expect(last_response.status).to eq(400) expect(last_response.body).to eq('a is invalid') end it 'performs no additional coercion' do get '/', a: 'true' expect(last_response.status).to eq(200) expect(last_response.body).to eq('String') end end it 'may not be supplied together with a single type' do expect do subject.params do requires :a, type: Integer, types: [Integer, String] end end.to raise_exception ArgumentError end end context 'converter' do it 'does not build Virtus::Attribute multiple times' do subject.params do requires :something, type: Array[String] end subject.get do end expect(Virtus::Attribute).to receive(:build).at_most(2).times.and_call_original 10.times { get '/' } end end end end
30.3424
111
0.543398
1de1f137927d0a99ddb4b86b93e7580534b2b8c7
2,082
require "active_support/notifications" require "conekta" require "conekta_event/engine" if defined?(Rails) module ConektaEvent class << self attr_accessor :adapter, :backend, :event_retriever, :namespace, :private_signature def configure(&block) raise ArgumentError, "must provide a block" unless block_given? block.arity.zero? ? instance_eval(&block) : yield(self) end alias :setup :configure def instrument(params) begin event = event_retriever.call(params) rescue Conekta::ErrorList => error_list for error_detail in error_list.details do Rails.logger.info "Conekta Webhook Error => #{error_detail.message}" end if params[:type] == "account.application.deauthorized" event = OpenStruct.new(params) else raise UnauthorizedError.new(error_list) end rescue Conekta::Error => e raise UnauthorizedError.new(e) end backend.instrument namespace.call(event.type), event if event end def subscribe(name, callable = Proc.new) backend.subscribe namespace.to_regexp(name), adapter.call(callable) end def all(callable = Proc.new) subscribe nil, callable end def listening?(name) namespaced_name = namespace.call(name) backend.notifier.listening?(namespaced_name) end end class Namespace < Struct.new(:value, :delimiter) def call(name = nil) "#{value}#{delimiter}#{name}" end def to_regexp(name = nil) %r{^#{Regexp.escape call(name)}} end end class NotificationAdapter < Struct.new(:subscriber) def self.call(callable) new(callable) end def call(*args) payload = args.last subscriber.call(payload) end end class Error < StandardError; end class UnauthorizedError < Error; end self.adapter = NotificationAdapter self.backend = ActiveSupport::Notifications self.event_retriever = lambda { |params| Conekta::Event.find(params[:id]) } self.namespace = Namespace.new("conekta_event", ".") end
27.038961
86
0.670989
612e44f753d7b2aac5d657c207cb1a1766287278
814
class Issue < ApplicationRecord include MultiPageTool belongs_to :journal default_scope { order(published_at: :desc) } def namespace 'journals' end def path "/journals/#{journal.slug}/#{issue}" end def false_for_missing_methods false end alias front_color_image_present? false_for_missing_methods alias front_black_and_white_image_present? false_for_missing_methods alias back_color_image_present? false_for_missing_methods alias back_black_and_white_image_present? false_for_missing_methods alias front_color_download_present? false_for_missing_methods alias front_black_and_white_download_present? false_for_missing_methods alias back_color_download_present? false_for_missing_methods alias back_black_and_white_download_present? false_for_missing_methods end
28.068966
73
0.837838
bb32673f35f548542a00f425229465a8894460bb
376
cask :v1 => 'omnipresence' do version '1.3' sha256 '2a58504aef5f7f24c74fb79ab1b59b667d83f3ba8b75b161a62de8617c089128' url "http://downloads.omnigroup.com/software/MacOSX/10.10/OmniPresence-#{version}.dmg" name 'OmniPresence' homepage 'http://www.omnigroup.com/omnipresence' license :commercial app 'OmniPresence.app' depends_on :macos => '>= :yosemite' end
26.857143
88
0.75266
ab765f14f476dda60fe9cdf91130716bfb3bff4c
2,299
class User < ApplicationRecord has_many :microposts, dependent: :destroy attr_accessor :remember_token, :activation_token, :reset_token before_save :downcase_email before_create :create_activation_digest validates :name, presence: true, length: { maximum: 50 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }, uniqueness: {case_sensitive: false} validates :password, presence: true, length: { minimum: 6 }, allow_nil: true has_secure_password class << self # 渡された文字列のハッシュ値を返す def digest(string) cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost BCrypt::Password.create(string, cost: cost) end # ランダムなトークンを返す def new_token SecureRandom.urlsafe_base64 end end def feed Micropost.where("user_id = ?", id) end # 永続セッションのためにユーザーをデータベースに記憶する def remember self.remember_token = User.new_token update_attribute(:remember_digest, User.digest(remember_token)) end # 渡されたトークンがダイジェストと一致したらtrueを返す def authenticated?(attribute, token) digest = send("#{attribute}_digest") return false if digest.nil? BCrypt::Password.new(digest).is_password?(token) end # ユーザーのログイン情報を破棄する def forget update_attribute(:remember_digest, nil) end # アカウントを有効にする def activate update_columns(activated: true, activated_at: Time.zone.now) end # 有効化用のメールを送信する def send_activation_email UserMailer.account_activation(self).deliver_now end def create_reset_digest self.reset_token = User.new_token update_columns(reset_digest: User.digest(reset_token), reset_sent_at: Time.zone.now) end def send_password_reset_email UserMailer.password_reset(self).deliver_now end # パスワード再設定の期限が切れている場合はtrueを返す def password_reset_expired? reset_sent_at < 2.hours.ago end private def downcase_email email.downcase! end def create_activation_digest self.activation_token = User.new_token self.activation_digest = User.digest(activation_token) end end
27.698795
88
0.685515
e2e93055b17d1593ab044bb78d8cc4a6e86bd8fc
5,518
cask 'java' do version '1.9,181' sha256 '0755e848c061419313510a88508512b8d58ae9c79bd01d460e6b436dc13dfac1' url "http://download.oracle.com/otn-pub/java/jdk/#{version.minor}+#{version.after_comma}/jdk-#{version.minor}_osx-x64_bin.dmg", cookies: { 'oraclelicense' => 'accept-securebackup-cookie', } name 'Java Standard Edition Development Kit' homepage "https://www.oracle.com/technetwork/java/javase/downloads/jdk#{version.minor}-downloads-3848520.html" pkg "JDK #{version.minor}.pkg" postflight do system_command '/usr/libexec/PlistBuddy', args: ['-c', 'Add :JavaVM:JVMCapabilities: string BundledApp', "/Library/Java/JavaVirtualMachines/jdk-#{version.minor}.jdk/Contents/Info.plist"], sudo: true system_command '/usr/libexec/PlistBuddy', args: ['-c', 'Add :JavaVM:JVMCapabilities: string JNI', "/Library/Java/JavaVirtualMachines/jdk-#{version.minor}.jdk/Contents/Info.plist"], sudo: true system_command '/usr/libexec/PlistBuddy', args: ['-c', 'Add :JavaVM:JVMCapabilities: string WebStart', "/Library/Java/JavaVirtualMachines/jdk-#{version.minor}.jdk/Contents/Info.plist"], sudo: true system_command '/usr/libexec/PlistBuddy', args: ['-c', 'Add :JavaVM:JVMCapabilities: string Applets', "/Library/Java/JavaVirtualMachines/jdk-#{version.minor}.jdk/Contents/Info.plist"], sudo: true system_command '/bin/ln', args: ['-nsf', '--', "/Library/Java/JavaVirtualMachines/jdk-#{version.minor}.jdk/Contents/Home", '/Library/Java/Home'], sudo: true system_command '/bin/mkdir', args: ['-p', '--', "/Library/Java/JavaVirtualMachines/jdk-#{version.minor}.jdk/Contents/Home/bundle/Libraries"], sudo: true system_command '/bin/ln', args: ['-nsf', '--', "/Library/Java/JavaVirtualMachines/jdk-#{version.minor}.jdk/Contents/Home/lib/server/libjvm.dylib", "/Library/Java/JavaVirtualMachines/jdk-#{version.minor}.jdk/Contents/Home/bundle/Libraries/libserver.dylib"], sudo: true if MacOS.version <= :mavericks system_command '/bin/rm', args: ['-rf', '--', '/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK'], sudo: true system_command '/bin/ln', args: ['-nsf', '--', "/Library/Java/JavaVirtualMachines/jdk-#{version.minor}.jdk/Contents", '/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK'], sudo: true end end uninstall_preflight do if File.exist?("#{HOMEBREW_PREFIX}/Caskroom/java-jdk-javadoc") system_command 'brew', args: ['cask', 'uninstall', 'java-jdk-javadoc'] end end uninstall pkgutil: [ "com.oracle.jdk-#{version.minor}", 'com.oracle.jre', ], launchctl: [ 'com.oracle.java.Helper-Tool', 'com.oracle.java.Java-Updater', ], quit: [ 'com.oracle.java.Java-Updater', 'net.java.openjdk.cmd', # Java Control Panel ], delete: [ '/Library/Internet Plug-Ins/JavaAppletPlugin.plugin', "/Library/Java/JavaVirtualMachines/jdk-#{version.minor}.jdk/Contents", '/Library/PreferencePanes/JavaControlPanel.prefPane', '/Library/Java/Home', if MacOS.version <= :mavericks [ '/usr/lib/java/libjdns_sd.jnilib', '/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK', ] end, ].keep_if { |v| !v.nil? } zap delete: [ '~/Library/Caches/com.oracle.java.Java-Updater', '~/Library/Caches/Oracle.MacJREInstaller', '~/Library/Caches/net.java.openjdk.cmd', ], trash: [ '/Library/Application Support/Oracle/Java', '/Library/Preferences/com.oracle.java.Deployment.plist', '/Library/Preferences/com.oracle.java.Helper-Tool.plist', '~/Library/Application Support/Java/', '~/Library/Application Support/Oracle/Java', '~/Library/Preferences/com.oracle.java.Java-Updater.plist', '~/Library/Preferences/com.oracle.java.JavaAppletPlugin.plist', '~/Library/Preferences/com.oracle.javadeployment.plist', ], rmdir: [ "/Library/Java/JavaVirtualMachines/jdk-#{version.minor}.jdk", '~/Library/Application Support/Oracle/', ] caveats <<-EOS.undent This Cask makes minor modifications to the JRE to prevent issues with packaged applications, as discussed here: https://bugs.eclipse.org/bugs/show_bug.cgi?id=411361 If your Java application still asks for JRE installation, you might need to reboot or logout/login. Installing this Cask means you have AGREED to the Oracle Binary Code License Agreement for Java SE at https://www.oracle.com/technetwork/java/javase/terms/license/index.html EOS end
48.831858
249
0.574484
18c21e9d32cad913466a2ec2c68aec894350a6c8
797
# frozen_string_literal: true module ES CONFIG = Rails.application.config_for(:elasticsearch).freeze def self.client Elasticsearch::Client.new(log: Rails.env.development?, hosts: CONFIG[:hosts], user: CONFIG[:user], password: CONFIG[:password], randomize_hosts: true, retry_on_failure: true, reload_connections: true) end def self.collection_repository CollectionRepository.new end end if Rails.env.development? logger = ActiveSupport::Logger.new(STDERR) logger.level = Logger::DEBUG logger.formatter = proc { |_s, _d, _p, m| "\e[2m#{m}\n\e[0m" } ES.client.transport.logger = logger end
29.518519
64
0.5734
bb9ed970609b140e4c842eb57e14a1e389b5b85a
64
class UserListMoviesController < ApplicationController end
12.8
54
0.828125
7a54381ee6da3c8a458b6725b18d56b4947a8160
301
# frozen_string_literal: true FactoryBot.define do factory :alliance do id { Faker::Number.within(range: 99_000_000..100_000_000) } esi_expires_at { 1.hour.from_now } esi_last_modified_at { Time.zone.now } name { Faker::Company.name } ticker { Faker::Finance.ticker } end end
25.083333
63
0.707641
7a0e28c5ef89ddcae606c9efcc1b857aa7de51a3
1,499
cask 'font-bungee' do version '1.1.0' sha256 'd012a9e6293201c3165feba64342d29c42bb4e67b1cc66e07509c12bab760a6f' # github.com/djrrb/bungee was verified as official when first introduced to the cask url "https://github.com/djrrb/bungee/releases/download/#{version}/Bungee-fonts.zip" appcast 'https://github.com/djrrb/bungee/releases.atom', checkpoint: '93cc2dd7788c322a7dd3b997404c0a1a2b133b84ed4d719758da148a7e55e73d' name 'Bungee' homepage 'https://djr.com/bungee/' font 'fonts/Bungee_Color_Fonts/BungeeColor-Regular_sbix_MacOS.ttf' font 'fonts/Bungee_Color_Fonts/BungeeColor-Regular_svg.ttf' font 'fonts/Bungee_Desktop/Bungee/Bungee-Hairline.otf' font 'fonts/Bungee_Desktop/Bungee/Bungee-Inline.otf' font 'fonts/Bungee_Desktop/Bungee/Bungee-Outline.otf' font 'fonts/Bungee_Desktop/Bungee/Bungee-Regular.otf' font 'fonts/Bungee_Desktop/Bungee/Bungee-Shade.otf' font 'fonts/Bungee_Desktop/BungeeLayers/BungeeLayers-Inline.otf' font 'fonts/Bungee_Desktop/BungeeLayers/BungeeLayers-Outline.otf' font 'fonts/Bungee_Desktop/BungeeLayers/BungeeLayers-Regular.otf' font 'fonts/Bungee_Desktop/BungeeLayers/BungeeLayers-Shade.otf' font 'fonts/Bungee_Desktop/BungeeLayersRotated/BungeeLayersRotated-Inline.otf' font 'fonts/Bungee_Desktop/BungeeLayersRotated/BungeeLayersRotated-Outline.otf' font 'fonts/Bungee_Desktop/BungeeLayersRotated/BungeeLayersRotated-Regular.otf' font 'fonts/Bungee_Desktop/BungeeLayersRotated/BungeeLayersRotated-Shade.otf' end
53.535714
88
0.817879
e91134239fd7d52351783212b8b02f3d960a099c
193
FactoryGirl.define do factory :category, class: 'Categoryz3::Category' do name { Faker::Name.name } trait :child do association :parent, factory: :category end end end
16.083333
53
0.668394
abb9ceb076c3878d35dc10208518df397c9774ee
931
class Gel < Formula desc "Modern gem manager" homepage "https://gel.dev" url "https://github.com/gel-rb/gel/archive/v0.2.0.tar.gz" sha256 "7d69f745986c9c33272f080496aea53719d69d4f465993c740f432ef5f0a3bd3" bottle do cellar :any_skip_relocation sha256 "ca4a4081014f2baab6285c44e1fddd6975cb33f22f76bddbc5eaa4a3a1956867" => :mojave sha256 "ca4a4081014f2baab6285c44e1fddd6975cb33f22f76bddbc5eaa4a3a1956867" => :high_sierra sha256 "628fbe3459425b7c30690ce3c4e2f5cadd39e2726833e866c54ef4fdb25f30b3" => :sierra end def install ENV["PATH"] = "bin:#{ENV["HOME"]}/.local/gel/bin:#{ENV["PATH"]}" system "gel", "install" system "rake", "man" bin.install "exe/gel" prefix.install "lib" man1.install Pathname.glob("man/man1/*.1") end test do (testpath/"Gemfile").write <<~EOS source "https://rubygems.org" gem "gel" EOS system "#{bin}/gel", "install" end end
30.032258
93
0.707841
e966199fc86e04626c62c9b7c40aebe85aeb96f5
459
java_version = input('java_version', description: 'Which version of java should be installed') control 'Java is installed & linked correctly' do impact 1.0 title 'Installed' desc 'Java is installed & linked correctly' describe command('java -version 2>&1') do its('stdout') { should match java_version.to_s } end describe command('update-alternatives --display jar') do its('stdout') { should match %r{\/usr\/lib\/jvm\/java} } end end
30.6
94
0.705882
384926aa429516ddb74eb411211fe69e6138b18c
289
class AdminEditUserPage < Page def initialize expect(page).to have_css '.edit_member_link.active' super end def admin? find('#user_admin').checked? end def set_admin check 'Admin' self end def save click_on 'Save' AdminUsersPage.new end end
13.136364
55
0.66436
1aa1e7ea45425ee30408783ad7eb7e65679860eb
1,408
# 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/admin_datatransfer_v1/service.rb' require 'google/apis/admin_datatransfer_v1/classes.rb' require 'google/apis/admin_datatransfer_v1/representations.rb' module Google module Apis # Admin Data Transfer API # # Admin Data Transfer API lets you transfer user data from one user to another. # # @see https://developers.google.com/admin-sdk/data-transfer/ module AdminDatatransferV1 VERSION = 'DatatransferV1' REVISION = '20151124' # View and manage data transfers between users in your organization AUTH_ADMIN_DATATRANSFER = 'https://www.googleapis.com/auth/admin.datatransfer' # View data transfers between users in your organization AUTH_ADMIN_DATATRANSFER_READONLY = 'https://www.googleapis.com/auth/admin.datatransfer.readonly' end end end
37.052632
102
0.752841
263eda349cb75eca0b8dab9b8050e7d81298e756
5,154
require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.service = :local # Mount Action Cable outside main process or domain. # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Include generic and useful information about system operation, but avoid logging too much # information to avoid inadvertent exposure of personally identifiable information (PII). config.log_level = :info # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment). # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "rails_vue_demo_production" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Log disallowed deprecations. config.active_support.disallowed_deprecation = :log # Tell Active Support which deprecation messages to disallow. config.active_support.disallowed_deprecation_warnings = [] # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require "syslog/logger" # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false # Inserts middleware to perform automatic connection switching. # The `database_selector` hash is used to pass options to the DatabaseSelector # middleware. The `delay` is used to determine how long to wait after a write # to send a subsequent read to the primary. # # The `database_resolver` class is used by the middleware to determine which # database is appropriate to use based on the time delay. # # The `database_resolver_context` class is used by the middleware to set # timestamps for the last write to the primary. The resolver uses the context # class timestamps to determine how long to wait before reading from the # replica. # # By default Rails will store a last write timestamp in the session. The # DatabaseSelector middleware is designed as such you can define your own # strategy for connection switching and pass that into the middleware through # these configuration options. # config.active_record.database_selector = { delay: 2.seconds } # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session end
44.817391
114
0.766395
bf3ec39e71557dc3665e2cb606a4d5949c4a0658
124
class AddTitleToSubscriptions < ActiveRecord::Migration def change add_column :subscriptions, :title, :text end end
20.666667
55
0.774194
e2a4d780e5fdf9d53009068785b9f83472baa321
893
# frozen_string_literal: true require 'spec_helper' describe Zoom::Actions::Roles do let(:zc) { zoom_client } let(:args) { { role_id: 2 } } describe '#roles_members action' do before :each do stub_request( :get, zoom_url('/roles/2/members') ).to_return(body: json_response('roles', 'members'), headers: { 'Content-Type' => 'application/json' }) end it 'requires role_id param' do expect { zc.roles_members(filter_key(args, :role_id)) }.to raise_error(Zoom::ParameterMissing, [:role_id].to_s) end it 'returns a hash' do expect(zc.roles_members(args)).to be_kind_of(Hash) end it "returns 'total_records'" do expect(zc.roles_members(args)['total_records']).to eq(1) end it "returns 'roles' Array" do expect(zc.roles_members(args)['members']).to be_kind_of(Array) end end end
24.805556
109
0.641657