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
91469b05ae6f66ef4723c544a9936c5910df1996
148
require "securerandom" require "proxy_chain_rb/version" require "proxy_chain_rb/server" module ProxyChainRb class Error < StandardError; end end
18.5
34
0.817568
1dcfc3d6a316c7a1c5fec3503594bb4f90763cd9
213
require Rails.root.join('spec/shared/controllers/shared_examples_for_cloud_network_controller') describe CloudNetworkController do include_examples :shared_examples_for_cloud_network_controller, %w(amazon) end
35.5
95
0.877934
ff9a5de2079c46d88be2d86df15d76df21ee46ec
1,270
# # Be sure to run `pod spec lint QRPayFramework.podspec' to ensure this is a # valid spec and to remove all comments including this before submitting the spec. # # To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html # To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/ # Pod::Spec.new do |s| s.name = "QRPayFramework" s.version = "0.1.29" s.summary = "QRPayFramework." s.description = "QRPayFramework. Using for scan and pay from QRPay company" s.homepage = "http://wooppay.com" s.license = "Wooppay" s.license = { :type => "MIT", :file => "LICENSE" } s.author = { "Wooppay LTD" => "[email protected]" } s.ios.deployment_target = '8.0' #s.ios.vendored_frameworks = 'QRPayFramework.framework' s.source = { :git => 'https://gitlab.com/qrpayframework/QRFramework.git', :tag => "#{s.version}" } s.source_files = "QRPayFramework", "QRPayFramework/**/*.{h,m,swift}" s.resource_bundles = { 'QRPayResources' => ['QRPayFramework/Resources/*.{xib,png,jpg}'] } s.resources = 'QRPayFramework/Resources/*.{xib,png,jpg}' s.exclude_files = "QRPayFramework/Exclude" s.pod_target_xcconfig = { 'SWIFT_VERSION' => '4.0' } end
32.564103
106
0.668504
03a226d43ece88c64b371cc05df9a241436e8052
356
$LOAD_PATH.unshift File.expand_path(File.dirname(__FILE__) + '/../..') $LOAD_PATH.unshift File.expand_path(File.dirname(__FILE__) + '/../../lib') require 'yajl' unless file = ARGV[0] puts "\nUsage: ruby examples/from_file.rb benchmark/subjects/item.json\n\n" exit(0) end json = File.new(file, 'r') hash = Yajl::Parser.parse(json) puts hash.inspect
23.733333
77
0.705056
e84218fa3c2a347e2d2792b4518b818be772a59a
8,645
class ScrumBoard < ApplicationRecord ## Constants DEFAULT_SPRINT_DURATION = 2.weeks NUM_SPRINTS_FOR_AVG_VELOCITY = 3 ## Associations has_many :scrum_queues, -> { order(ended_on: :asc) }, dependent: :destroy, inverse_of: :scrum_board has_many :scrum_stories, -> { order(created_at: :asc) }, dependent: :destroy, inverse_of: :scrum_board has_many :trello_imports, -> { order(created_at: :desc) }, dependent: :destroy, inverse_of: :scrum_board has_many :wip_logs, -> { order(occurred_at: :desc) }, dependent: :destroy, inverse_of: :scrum_board has_many :scrum_events, -> { order(occurred_at: :desc) }, through: :trello_imports has_many :sprint_contributions, through: :scrum_queues ## Aliases alias_attribute :queues, :scrum_queues alias_attribute :stories, :scrum_stories alias_attribute :events, :scrum_events alias_attribute :imports, :trello_imports ## Validators validates :name, presence: true validate :trello_url_is_valid # # Class Methods # def self.find_or_create_by_trello_board(trello_board) # Find or create board. scrum_board = ScrumBoard.find_by(trello_board_id: trello_board.id) if scrum_board.nil? scrum_board = ScrumBoard.create!(trello_board_id: trello_board.id, trello_url: trello_board.url, name: trello_board.name) end scrum_board end def self.scrummy_trello_board?(trello_board) # A scrummy board will contain these lists: wish heap, backlog, current scrummy_list_names = ['wish heap', 'backlog', 'current'] board_list_names = trello_board.lists.map { |list| list.name.downcase.strip } scrummy_list_names.each do |required_name| return false unless board_list_names.any? { |list_name| list_name.include? required_name } end true end def self.sprinty_trello_list?(trello_list) trello_list.name.downcase.include? 'complete' end def self.wishy_trello_list?(trello_list) trello_list.name.downcase.include? 'wish' end def self.backloggy_trello_list?(trello_list) trello_list.name.downcase.include? 'backlog' end # # Associations # def wish_heap queues.find(&:wish_heap?) end def project_backlog queues.find(&:project_backlog?) end def sprint_backlog queues.find(&:sprint_backlog?) end def active_sprint queues.find(&:active_sprint?) end def completed_queues queues.select(&:completed_sprint_queue?).sort_by(&:started_on) end def queue_by_trello_id(trello_list_id) queues.find { |q| q.trello_list_id == trello_list_id } end def recent_sized_stories # On reorder: https://stackoverflow.com/a/4202448/1093087 stories.where('points > 0').reorder(created_at: :desc) end def sized_stories_before(date) sized_stories = stories.where('points > 0').select { |s| s.last_activity_at < date.end_of_day } sized_stories.sort_by(&:last_activity_at).reverse end def wip_events(options={}) limit = options.fetch(:limit, 10) events.select(&:wip?).slice(0, limit) end def trello_board return nil unless trello_board_id TrelloService.board(trello_board_id) end def import_in_progress? imports.select(&:in_progress?).present? end def contributors sprint_contributions.map(&:scrum_contributor) .uniq .sort_by { |c| c.board_points(self) } .reverse end # # Instance Methods # ## Action / Event Imports def update_from_trello(trello_import, action_limit=TrelloImport::BOARD_ACTION_IMPORT_LIMIT) trello_import.latest_board_actions(action_limit) #trello_import.update_sprints trello_import.end_now trello_import end # rubocop: disable Metrics/AbcSize def latest_trello_actions(limit=TrelloImport::BOARD_ACTION_IMPORT_LIMIT) # Board actions are ordered in DESC order: most recent are first. So to pull the latest, # need to import since last imported id going backwards. latest_actions = [] request_limit = 1000 since_id = last_imported_action_id before_id = nil more = true calls = 0 max_calls = 100 while more # Rate limits: https://developers.trello.com/docs/rate-limits raise "Too many calls: #{calls}" if calls > max_calls calls += 1 actions = trello_board.actions(limit: request_limit, since: since_id, before: before_id) actions.each { |action| latest_actions << action } ImportLogger.info format('Fetched %s (%s) Trello board actions from API.', actions.length, latest_actions.length) more = actions.length == request_limit before_id = actions.last.id if more end # Actions come in reverse chronological order per https://stackoverflow.com/a/51817635/1093087 latest_actions.reverse.slice(0, limit) end # rubocop: enable Metrics/AbcSize def last_event events.try(:first) end def last_imported_action_id # events are sorted in desc order. last_event.present? ? last_event.trello_id : nil end def created_on creation_event = events.find_by(trello_type: "createBoard") return nil unless creation_event creation_event.occurred_at.to_date end ## WIP Logs def build_wip_log_from_scratch new_logs = [] wip_logs.destroy_all events.reverse_each do |event| next unless event.wip? wip_log = WipLog.create_from_event(event) new_logs << wip_log end new_logs end def current_wip return nil if wip_logs.blank? wip_logs.first.wip['total'] end def backlog_points_on(date) logs = wip_logs.where('occurred_at <= ?', date.end_of_day).order(occurred_at: :desc).limit(1) logs.count > 0 ? logs.first.wip['project_backlog'] : nil end def wish_heap_points_on(date) logs = wip_logs.where('occurred_at <= ?', date.end_of_day).order(occurred_at: :desc).limit(1) logs.count > 0 ? logs.first.wip['wish_heap'] : nil end ## Sprint Contributions def build_sprint_contributions_from_scratch # To be considered active that sprint event without contributing story points. min_events_to_be_active = 3 saved_contributions = [] # Reload instance data. Not doing this was causing some contributions to be missed. reload # For each completed sprint... completed_queues.each do |queue| # From scratch... queue.sprint_contributions.destroy_all # Add a contribution for each contributor who performed the min events/actions. # This will capture any contributors who may have contributed 0 story points. queue.event_contributors.each do |contributor| event_count = contributor.count_events_for_queue(queue) next unless event_count >= min_events_to_be_active sprint_contrib = SprintContribution.create( scrum_contributor: contributor, scrum_queue: queue, story_points: contributor.points_for_sprint(queue), event_count: event_count ) ImportLogger.debug sprint_contrib.to_stdout saved_contributions << sprint_contrib end end saved_contributions end ## Velocity def average_velocity_on(date) # Averaged over last 3 sprints period = DEFAULT_SPRINT_DURATION * NUM_SPRINTS_FOR_AVG_VELOCITY days_in_sprint = DEFAULT_SPRINT_DURATION.to_i / 1.day.to_i end_at = date.end_of_day start_at = end_at - period daily_velocity = WipLog.daily_velocity_between(self, start_at, end_at) (daily_velocity * days_in_sprint).round(1) end def current_velocity average_velocity_on(Time.zone.today) end ## Story Size def average_story_size_on(date) sample_size = 20 sample = sized_stories_before(date).slice(0, sample_size) (sample.sum(&:points).to_d / sample.length).round(1) end def current_average_story_size average_story_size_on(Time.zone.today) end def sampled_story_size sample_size = 20 sample = recent_sized_stories.limit(sample_size) (sample.sum(&:points).to_d / sample.length).ceil end private # Custom Validators def trello_url_is_valid return if trello_url.nil? url_start = 'https://trello.com/b' error_message = 'must be valid Trello url' errors.add(:trello_url, error_message) unless trello_url.downcase.start_with?(url_start) end end
29.505119
99
0.685946
620f0b8ff5ce3997e91ebc214d67d306a37039d2
5,052
class OciCli < Formula include Language::Python::Virtualenv desc "Oracle Cloud Infrastructure CLI" homepage "https://docs.cloud.oracle.com/iaas/Content/API/Concepts/cliconcepts.htm" url "https://files.pythonhosted.org/packages/58/63/2ae0966975943638c55ecf3831a7fbdc061f84ad627f28e849223003c5d0/oci-cli-3.0.4.tar.gz" sha256 "3d27318112b0e0a7b7b7959df36ebabe7c06e3dcf02ed82a22575b356625e225" license any_of: ["UPL-1.0", "Apache-2.0"] head "https://github.com/oracle/oci-cli.git" bottle do sha256 cellar: :any, arm64_big_sur: "f1a19e3ff48f0c5fca75500a0bd682131d5f200f1e57ba186001e3d14b50995c" sha256 cellar: :any, big_sur: "66682140f4d43ee2efec9066a170ac6578d76f0f0b194ae4bb6e8d4496ae7654" sha256 cellar: :any, catalina: "286a55bde93d155db21dfd38260a6d78c14c2fee2b52951144280ba56d9a15da" sha256 cellar: :any, mojave: "ec26af7fedded95bc257610cfe66ebace1f2dc7c30d21a0d1185695509a960ef" sha256 cellar: :any_skip_relocation, x86_64_linux: "b92779e51e4067646e2ff6a9d03e29b5f59fdb07bcf442d56c81b57c696ac627" # linuxbrew-core end depends_on "rust" => :build depends_on "[email protected]" depends_on "six" resource "arrow" do url "https://files.pythonhosted.org/packages/94/39/b5bb573821d6784640c227ccbd72fa192f7542fa0f68589fd51757046030/arrow-1.1.1.tar.gz" sha256 "dee7602f6c60e3ec510095b5e301441bc56288cb8f51def14dcb3079f623823a" end resource "certifi" do url "https://files.pythonhosted.org/packages/6d/78/f8db8d57f520a54f0b8a438319c342c61c22759d8f9a1cd2e2180b5e5ea9/certifi-2021.5.30.tar.gz" sha256 "2bbf76fd432960138b3ef6dda3dde0544f27cbf8546c458e60baf371917ba9ee" end resource "cffi" do url "https://files.pythonhosted.org/packages/2e/92/87bb61538d7e60da8a7ec247dc048f7671afe17016cd0008b3b710012804/cffi-1.14.6.tar.gz" sha256 "c9a875ce9d7fe32887784274dd533c57909b7b1dcadcc128a2ac21331a9765dd" end resource "click" do url "https://files.pythonhosted.org/packages/27/6f/be940c8b1f1d69daceeb0032fee6c34d7bd70e3e649ccac0951500b4720e/click-7.1.2.tar.gz" sha256 "d2b5255c7c6349bc1bd1e59e08cd12acbbd63ce649f2588755783aa94dfb6b1a" end resource "configparser" do url "https://files.pythonhosted.org/packages/16/4f/48975536bd488d3a272549eb795ac4a13a5f7fcdc8995def77fbef3532ee/configparser-4.0.2.tar.gz" sha256 "c7d282687a5308319bf3d2e7706e575c635b0a470342641c93bea0ea3b5331df" end resource "cryptography" do url "https://files.pythonhosted.org/packages/9b/77/461087a514d2e8ece1c975d8216bc03f7048e6090c5166bc34115afdaa53/cryptography-3.4.7.tar.gz" sha256 "3d10de8116d25649631977cb37da6cbdd2d6fa0e0281d014a5b7d337255ca713" end resource "jmespath" do url "https://files.pythonhosted.org/packages/3c/56/3f325b1eef9791759784aa5046a8f6a1aff8f7c898a2e34506771d3b99d8/jmespath-0.10.0.tar.gz" sha256 "b85d0567b8666149a93172712e68920734333c0ce7e89b78b3e987f71e5ed4f9" end resource "oci" do url "https://files.pythonhosted.org/packages/33/02/23d3b65ad3d562c9eca93c527e50375763846e7bf151af01d6c93e9697c2/oci-2.45.0.tar.gz" sha256 "691a21ed76b5ce62a4c2ff12625b4ffe0f190e323d1af5d749e9fd91bb83f031" end resource "pycparser" do url "https://files.pythonhosted.org/packages/0f/86/e19659527668d70be91d0369aeaa055b4eb396b0f387a4f92293a20035bd/pycparser-2.20.tar.gz" sha256 "2d475327684562c3a96cc71adf7dc8c4f0565175cf86b6d7a404ff4c771f15f0" end resource "pyOpenSSL" do url "https://files.pythonhosted.org/packages/0d/1d/6cc4bd4e79f78be6640fab268555a11af48474fac9df187c3361a1d1d2f0/pyOpenSSL-19.1.0.tar.gz" sha256 "9a24494b2602aaf402be5c9e30a0b82d4a5c67528fe8fb475e3f3bc00dd69507" end resource "python-dateutil" do url "https://files.pythonhosted.org/packages/4c/c4/13b4776ea2d76c115c1d1b84579f3764ee6d57204f6be27119f13a61d0a9/python-dateutil-2.8.2.tar.gz" sha256 "0123cacc1627ae19ddf3c27a5de5bd67ee4586fbdd6440d9748f8abb483d3e86" end resource "pytz" do url "https://files.pythonhosted.org/packages/b0/61/eddc6eb2c682ea6fd97a7e1018a6294be80dba08fa28e7a3570148b4612d/pytz-2021.1.tar.gz" sha256 "83a4a90894bf38e243cf052c8b58f381bfe9a7a483f6a9cab140bc7f702ac4da" end resource "PyYAML" do url "https://files.pythonhosted.org/packages/a0/a4/d63f2d7597e1a4b55aa3b4d6c5b029991d3b824b5bd331af8d4ab1ed687d/PyYAML-5.4.1.tar.gz" sha256 "607774cbba28732bfa802b54baa7484215f530991055bb562efbed5b2f20a45e" end resource "terminaltables" do url "https://files.pythonhosted.org/packages/9b/c4/4a21174f32f8a7e1104798c445dacdc1d4df86f2f26722767034e4de4bff/terminaltables-3.1.0.tar.gz" sha256 "f3eb0eb92e3833972ac36796293ca0906e998dc3be91fbe1f8615b331b853b81" end def install virtualenv_install_with_resources end test do version_out = shell_output("#{bin}/oci --version") assert_match version.to_s, version_out assert_match "Usage: oci [OPTIONS] COMMAND [ARGS]", shell_output("#{bin}/oci --help") assert_match "", shell_output("#{bin}/oci session validate", 1) end end
48.114286
145
0.804434
6a55dec7d756ae11b72c3f25c4f09c0c08e44495
2,376
# frozen_string_literal: true require "cases/helper_sqlserver" require "models/book" class FetchTestSqlserver < ActiveRecord::TestCase let(:books) { @books } before { create_10_books } it "work with fully qualified table and columns in select" do books = Book.select("books.id, books.name").limit(3).offset(5) assert_equal Book.all[5, 3].map(&:id), books.map(&:id) end describe "count" do it "gauntlet" do books[0].destroy books[1].destroy books[2].destroy assert_equal 7, Book.count assert_equal 1, Book.limit(1).offset(1).count assert_equal 1, Book.limit(1).offset(5).count assert_equal 1, Book.limit(1).offset(6).count assert_equal 0, Book.limit(1).offset(7).count assert_equal 3, Book.limit(3).offset(4).count assert_equal 2, Book.limit(3).offset(5).count assert_equal 1, Book.limit(3).offset(6).count assert_equal 0, Book.limit(3).offset(7).count assert_equal 0, Book.limit(3).offset(8).count end end describe "order" do it "gauntlet" do Book.where(name: "Name-10").delete_all _(Book.order(:name).limit(1).offset(1).map(&:name)).must_equal ["Name-2"] _(Book.order(:name).limit(2).offset(2).map(&:name)).must_equal ["Name-3", "Name-4"] _(Book.order(:name).limit(2).offset(7).map(&:name)).must_equal ["Name-8", "Name-9"] _(Book.order(:name).limit(3).offset(7).map(&:name)).must_equal ["Name-8", "Name-9"] _(Book.order(:name).limit(3).offset(9).map(&:name)).must_equal [] end end protected def create_10_books Book.delete_all @books = (1..10).map { |i| Book.create! name: "Name-#{i}" } end end class DeterministicFetchWithCompositePkTestSQLServer < ActiveRecord::TestCase it "orders by the identity column if table has one" do SSCompositePkWithIdentity.delete_all SSCompositePkWithIdentity.create(pk_col_two: 2) SSCompositePkWithIdentity.create(pk_col_two: 1) _(SSCompositePkWithIdentity.take(1).map(&:pk_col_two)).must_equal [2] end it "orders by the first column if table has no identity column" do SSCompositePkWithoutIdentity.delete_all SSCompositePkWithoutIdentity.create(pk_col_one: 2, pk_col_two: 2) SSCompositePkWithoutIdentity.create(pk_col_one: 1, pk_col_two: 1) _(SSCompositePkWithoutIdentity.take(1).map(&:pk_col_two)).must_equal [1] end end
33.942857
89
0.689815
391d4b56a30008337b16e537d4073e9d6785e1c6
655
# frozen_string_literal: true # encoding: utf-8 require 'spec_helper' describe 'has_one associations' do context 'destroying parent in transaction with dependent child' do require_transaction_support let(:person) { Person.create! } let(:game) { Game.create!(person: person) } before do Person.delete_all Game.delete_all game end it 'works' do Person.count.should == 1 Game.count.should == 1 Person.with_session do |session| session.with_transaction do person.destroy end end Person.count.should == 0 Game.count.should == 0 end end end
18.714286
68
0.639695
212fab37f203d83e46f68d7182ed6fc80679eba0
815
ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' require 'minitest/reporters' Minitest::Reporters.use! class ActiveSupport::TestCase # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. fixtures :all # Add more helper methods to be used by all tests here... include ApplicationHelper def is_logged_in? !session[:user_id].nil? end def log_in_as(user) session[:user_id] = user.id end end class ActionDispatch::IntegrationTest def log_in_as(user, password: 'password', remember_me: '1') post login_path, params: { session: { email: user.email, password: password, remember_me: remember_me } } end end
27.166667
82
0.655215
7a265b0de1c2ee96a1389626d354765ba8e2d206
354
cask 'minbox' do version '2.0.12' sha256 '3c5a6bd1888453ef6de902da9bf29f873516572d4f7ff7d7d096c5425ae9dcd2' url 'https://minbox.com/download' appcast 'https://minbox.com/updates.xml', checkpoint: 'd6f20222f6fca106398c29a026237661e4805106af60d373f71f17948aa5d425' name 'Minbox' homepage 'https://minbox.com' app 'Minbox.app' end
27.230769
88
0.762712
1d1be55a1dc1a120c5fbf169866ff71d27a33821
2,684
#-- encoding: UTF-8 #-- copyright # OpenProject is an open source project management software. # Copyright (C) 2012-2020 the OpenProject GmbH # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License version 3. # # OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows: # Copyright (C) 2006-2017 Jean-Philippe Lang # Copyright (C) 2010-2013 the ChiliProject Team # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # See docs/COPYRIGHT.rdoc for more details. #++ class CustomActions::Conditions::Role < CustomActions::Conditions::Base def fulfilled_by?(work_package, user) values.empty? || (self.class.roles_in_project(work_package, user).map(&:id) & values).any? end class << self def key :role end def roles_in_project(work_packages, user) with_request_store(projects_of(work_packages)) do |projects| projects.map do |project| user.roles_for_project(project) end.flatten end end private def custom_action_scope_has_current(work_packages, user) CustomAction .includes(association_key) .where(habtm_table => { key_id => roles_in_project(work_packages, user) }) end def projects_of(work_packages) # Using this if/else instead of Array(work_packages) # to avoid "delegator does not forward private method #to_ary" warnings # for WorkPackageEagerLoadingWrapper if work_packages.respond_to?(:map) work_packages.map(&:project).uniq else [work_packages.project] end end def with_request_store(projects) RequestStore.store[:custom_actions_role] ||= Hash.new do |hash, hash_projects| hash[hash_projects] = yield hash_projects end RequestStore.store[:custom_actions_role][projects] end end private def associated ::Role .givable .select(:id, :name) .map { |u| [u.id, u.name] } end end
30.850575
91
0.708644
7ae0ed6cfe8568fcb16f6662a5a6bafdf9945e9c
400
# == Schema Information # # Table name: jedd_reposts # # id :integer not null, primary key # vspace_user_id :integer # jedd_directory_id :integer # created_at :datetime # updated_at :datetime # class Repost < ActiveRecord::Base self.table_name = 'jedd_reposts' belongs_to :vspace_user belongs_to :jedd_directory, :class_name => 'Directory' end
22.222222
60
0.6625
7942506a84707a3b54437937a3abb3d9f49b5ad2
733
# frozen_string_literal: true class ForBlockReport < BaseReport set_lang :ru set_report_name :for_block set_human_name "Индикаторы (IoC) для блокировки (последние сутки)" set_report_model 'Indicator' set_required_params [] set_formats %i[txt] def txt(blank_document) @file_name = "#{Time.now.utc} #{@human_name}.txt" r = blank_document @records.each do |record| r << "#{record}\n" end end private def get_records(options, _organization) now = Time.now Indicator.where(updated_at: ((now - 24.hours)..now)) .where(trust_level: 'high') .where(purpose: 'for_prevent') .group(:content, :content_format) .order(:content_format) .pluck(:content) end end
23.645161
68
0.675307
1885539518092b1c67777cb735930991c6b9a035
233
require 'rubygems' begin require 'bacon' rescue LoadError require 'mac_bacon' end lib_path = File.expand_path("#{File.dirname(__FILE__)}/../lib") $LOAD_PATH.unshift(lib_path) unless $LOAD_PATH.include?(lib_path) require 'facon'
21.181818
65
0.759657
4af8206eeaeec3e51683204a3ff79b97a1d7c69e
629
# # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'flutter_lyric' s.version = '0.0.1' s.summary = 'lyric_widget' s.description = <<-DESC lyric_widget DESC s.homepage = 'http://example.com' s.license = { :file => '../LICENSE' } s.author = { 'Your Company' => '[email protected]' } s.source = { :path => '.' } s.source_files = 'Classes/**/*' s.public_header_files = 'Classes/**/*.h' s.dependency 'Flutter' s.ios.deployment_target = '8.0' end
28.590909
83
0.537361
03b2a2d3f3cfa2a2d910a3e7f76f6d83e015db22
2,087
# frozen_string_literal: true require 'spec_helper' describe 'Rsyslog::Actions::Outputs::Omkafka' do let(:data) do { broker: 'foo', topic: 'default', key: 'primary', dynatopic: 'off', 'dynatopic.cachesize' => 512, 'partitions.auto' => 'off', 'partitions.number' => 10, 'partitions.usefixed' => 0, errorfile: 'error.log', confparam: %w[param1 param2], topicconfparam: %w[param1 param2], template: 't_kafka', closetimeout: 600, resubmitonfailure: 'on', keepfailedmessages: 'off', failedmsgfile: 'message' } end context 'with valid data' do context 'full data' do it { is_expected.to allow_value(data) } end context 'individual parameters' do it 'is valid' do data.each do |param, value| expected_param = { param.to_sym => value } expected_param[:topic] = 'topic' unless param.to_s == 'topic' is_expected.to allow_value(expected_param) end end end end context 'with invalid data' do context 'bad strings' do let(:bad_strings) do { broker: '', topic: 1, key: 4, dynatopic: true, 'partitions.auto' => false, errorfile: '', confparam: [0, 1], topicconfparam: [0, 1], template: '', resubmitonfailure: false, keepfailedmessages: true, failedmsgfile: '' } end it { is_expected.not_to allow_value(bad_strings) } end context 'bad integers' do let(:bad_int) do { 'dynatopic.cachesize' => '50m', 'partitions.number' => '50', 'partitions.usefixed' => '0', closetimeout: '5h' } end it { is_expected.not_to allow_value(bad_int) } end context 'bad array' do let(:bad_array) do { confparam: 'param1', topicconfparam: 'param2' } end it { is_expected.not_to allow_value(bad_array) } end end end
23.188889
71
0.547197
618130a3a13f7885b0ddde64c39066f030bd32a3
609
# # Cookbook:: national_parks_cookbook # Spec:: default # # Copyright:: 2017, The Authors, All Rights Reserved. require 'spec_helper' describe 'national_parks_cookbook::tomcat' do context 'When all attributes are default, on an unspecified platform' do let(:chef_run) do runner = ChefSpec::ServerRunner.new # (platform: 'centos', version: '7.2.1511') runner.converge(described_recipe) end it 'converges successfully' do expect(chef_run).to create_user('tomcat') expect(chef_run).to create_group('tomcat') expect { chef_run }.to_not raise_error end end end
26.478261
85
0.70936
26d8f26830179fad799cb6e71ea48983a0043463
923
require "goon_model_gen" require "goon_model_gen/source/type" module GoonModelGen module Source class Enum < Type class Element attr_reader :value, :name def initialize(value, name) @value, @name = value, name end end attr_reader :base_type, :elements # @param name [String] # @param base_type [String] # @param element_definitions [Array<Hash<Object,String>>,Hash<Object,String>] def initialize(name, base_type, element_definitions) unless element_definitions.all?{|i| i.is_a?(Hash) && (i.length == 1) } raise "Enum element definitions must be an Array of 1 element Hash but was #{element_definitions.inspect}" end super(name) @base_type = base_type @elements = element_definitions.map do |i| Element.new(i.keys.first, i.values.first) end end end end end
27.147059
116
0.632719
91784b82b0a3346334a1bc8622b22cd0b067c25d
606
require 'simplecov' module SimpleCov::Configuration def clean_filters @filters = [] end end SimpleCov.configure do clean_filters load_adapter 'test_frameworks' end ENV["COVERAGE"] && SimpleCov.start do add_filter "/.rvm/" end $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $LOAD_PATH.unshift(File.dirname(__FILE__)) require 'rspec' require 'allin-sdk-ruby' # Requires supporting files with custom matchers and macros, etc, # in ./support/ and its subdirectories. Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f} RSpec.configure do |config| end
20.2
69
0.729373
bb0752e46c50edda8d19a1319c38c3386706e281
897
require 'spec_helper' require 'presenters/v3/app_environment_variables_presenter' module VCAP::CloudController::Presenters::V3 RSpec.describe AppEnvironmentVariablesPresenter do let(:app) do VCAP::CloudController::AppModel.make( environment_variables: { 'CUSTOM_ENV_VAR' => 'hello' }, ) end subject(:presenter) { AppEnvironmentVariablesPresenter.new(app) } describe '#to_hash' do let(:result) { presenter.to_hash } it 'presents the app environment variables as json' do expect(result).to eq({ var: { CUSTOM_ENV_VAR: 'hello' }, links: { self: { href: "#{link_prefix}/v3/apps/#{app.guid}/environment_variables", }, app: { href: "#{link_prefix}/v3/apps/#{app.guid}", } } }) end end end end
25.628571
79
0.576366
79be65d1144aa74938083198fab39c6ca6e98842
405
module OpenProductAssembly class Engine < Rails::Engine engine_name 'open_product_assembly' config.autoload_paths += %W(#{config.root}/lib) def self.activate Dir.glob(File.join(File.dirname(__FILE__), "../../app/decorators/**/*.rb")) do |c| Rails.configuration.cache_classes ? require(c) : load(c) end end config.to_prepare &method(:activate).to_proc end end
27
88
0.674074
f78d38f5b05aea430aa4807dc953121b083c0f8a
597
require 'asciidoctor' require 'asciidoctor/extensions' require 'open3' include Asciidoctor def python3_preprocessor(name) klass = Class.new(Asciidoctor::Extensions::Preprocessor) do class << self attr_accessor :script end def process document, reader script = self.class.script out, err, s = Open3.capture3("python3 #{script}", :stdin_data => reader.read) if not s.success? $stderr.puts(err) exit 1 end return Reader.new out.split("\n") end end klass.script = File.join(File.dirname(__FILE__), name) return klass end
23.88
84
0.670017
edbf71aa6ab63a9227116c370acc32d904c80e2c
1,222
class Gsar < Formula desc "General Search And Replace on files" homepage "http://tjaberg.com/" url "http://tjaberg.com/gsar121.zip" version "1.21" sha256 "05fb9583c970aba4eb0ffae2763d7482b0697c65fda1632a247a0153d7db65a9" bottle do cellar :any_skip_relocation sha256 "be008a03610074b4c66f775ae1802ed214006e6ba21150da886c8f4aa97362a4" => :catalina sha256 "b357c58535d31278d9b815770aa10e9f7d496849ecf58e131a23ea2182c7cbc3" => :mojave sha256 "07872ab6e21c22fe0ff901974ff6772d934bebc6f574a8908e6e3600a0fb6fb9" => :high_sierra sha256 "762262cc0840aa074588b1fbbd534f6b865a44d344628b9dbf36b07dfdef2a9a" => :sierra sha256 "5cf3fe6d772f95378e2802a6208b8f06524a81b4d881343571dd3af201b69e98" => :el_capitan sha256 "6e138e63b868dfbd4d16109cabe60f50dc600fd65cbf14cd3926b1b8c2f3e2dc" => :yosemite sha256 "3911e63bccd5deae4101c7c38a84954ad7e205bda69b3eefcee61a4d46e1df8d" => :mavericks sha256 "3e0cdee67e5f45f98f759b505f691b9ea7b6b25dd770fa4d58cc630a54f7a5de" => :x86_64_linux end def install system "make" bin.install "gsar" end test do assert_match /1 occurrence changed/, shell_output("#{bin}/gsar -sCourier -rMonaco #{test_fixtures("test.ps")} new.ps") end end
42.137931
122
0.803601
112f963edb0ad227de3c36d975ee160c50dfce45
1,520
module PageObjectModel class ShopPageNavigation < PageObjectModel::Page trait "* id:'sliding_tabs'" element :toggle_button, "* id:'togglebutton_home'" element :featured_category, "* text:'Featured'" element :left_selection, "* id:'left_selection'" element :right_selection, "* id:'right_selection'" element :book_title_text, "* id:'title_text'" element :author_name_text, "* id:'author_name'" ###pop up element :close_button, "* id:'button_close'" element :pop_up_book_title_text, "* id:'textview_title'" element :pop_up_book_author_text, "* id:'textview_author'" element :buy_now_button, "* id:'button_buy'" element :get_free_sample_button, "* id:'button_add_sample'" element :have_a_look_inside, "* id:'textview_open_sample'" ##pop up dialog element :read_now_button, "* id:'button2' text:'Read now'" element :download_button, "* id:'button1' text:'Download'" def assert_do_you_want_to_read_popup wait_for_elements_exist( [ "* id:'parentPanel'", "* id:'textview_title' text:'Do you want to read the free sample now or download it to your device'", "* id:'textview_message' text:'(You will need to sign in or register and signin to download)'", read_now_button.selector, download_button.selector ],:timeout => 5) end end end module PageObjectModel def shop_page_navigation @_shop_page_navigation ||= page(ShopPageNavigation) end end
38.974359
115
0.676974
1a2166ad8f0abf0ac6905e9442bc19c853a0f661
673
# encoding: utf-8 module Github module Validations module Presence # Ensures that esential arguments are present before request is made # def _validate_presence_of(*params) params.each do |param| raise ArgumentError, "parameter cannot be nil" if param.nil? end end # Check if user or repository parameters are passed # def _validate_user_repo_params(user_name, repo_name) raise ArgumentError, "[user] parameter cannot be nil" if user_name.nil? raise ArgumentError, "[repo] parameter cannot be nil" if repo_name.nil? end end # Presence end # Validations end # Github
25.884615
79
0.670134
1d3af967178cd93fdbd06780cfb4096dd2a5bd59
1,060
class GetPrintImagesService def initialize() # @print_uids = Print.pluck(:eb_uid) end def call begin get_print_images return true rescue StandardError => e puts "SOMETHING BROKE" return false end end private # attr_reader :print_uids def get_print_images collection_id = 36459 Print.all.pluck(:eb_uid).each do |uid| download_image( uid ) end end def download_image print_uid print_url = "http://expressobeans.com/public/detail.php/#{print_uid}" a = Mechanize.new page = a.get(print_url) #pp page.images #pp page.images.first.attributes["src"] img_url = page.parser.xpath("//img[contains(@alt, 'Image')]")[0]['src'].sub("&t=mi", "&t=lg") image_path = "http://expressobeans.com/#{img_url}" save_path = Rails.root.join('public', 'assets', 'prints', 'images', 'temp', "#{print_uid}.jpg") # pp path puts img_url puts image_path puts save_path a.get(image_path).save( save_path ) #pp page.search("/visual/IS.php") end end
22.553191
99
0.642453
f86ac8cae37a5ba0ed922c6d48eaea869256bf57
1,478
# Installs a relatively minimalist version of the GPAC tools. The # most commonly used tool in this package is the MP4Box metadata # interleaver, which has relatively few dependencies. # # The challenge with building everything is that Gpac depends on # a much older version of FFMpeg and WxWidgets than the version # that Brew installs class Gpac < Formula desc "Multimedia framework for research and academic purposes" homepage "https://gpac.wp.mines-telecom.fr/" url "https://github.com/gpac/gpac/archive/v0.8.0.tar.gz" sha256 "f9c4bf82b0cbc9014bc217d6245118ceb1be319f877501f8b6da7a284f70ec65" head "https://github.com/gpac/gpac.git" bottle do cellar :any sha256 "f2c2011bf39b446799dc060821df0947997583f2ec4793488aa98964fe6d6cb5" => :mojave sha256 "817c6ab9614c89b887bd2887faa03e1aaa505cf25861c9ca4c53e598b56b5396" => :high_sierra sha256 "d1860839d41ed5922e40c1f2b1ff6215083cfaba19d9751db985541b2cf475b8" => :sierra end depends_on "pkg-config" => :build depends_on "openssl" conflicts_with "bento4", :because => "both install `mp42ts` binaries" def install args = %W[ --disable-wx --disable-pulseaudio --prefix=#{prefix} --mandir=#{man} --disable-x11 ] system "./configure", *args system "make" system "make", "install" end test do system "#{bin}/MP4Box", "-add", test_fixtures("test.mp3"), "#{testpath}/out.mp4" assert_predicate testpath/"out.mp4", :exist? end end
31.446809
93
0.728687
185f88538384c0b08cfebe721c78d7dd6e90fdc2
5,000
module Souls class Compute < Thor desc "setup_vpc_nat", "Set Up VPC Cloud Nat" method_option :range, default: "10.124.0.0/28", aliases: "--range", desc: "GCP VPC Network IP Range" def setup_vpc_nat puts(Paint["Initializing NAT Setup This process might take about 10 min...", :yellow]) Souls::Gcloud.new.config_set create_network create_firewall_tcp(range: options[:range]) create_firewall_ssh create_subnet(range: options[:range]) create_connector create_router create_external_ip create_nat Souls::Sql.new.invoke(:setup_private_ip) update_workflows update_env puts(Paint["Cloud NAT is All Set!\n", :white]) puts( Paint % [ "Your Worker's External IP: %{white_text}", :green, { white_text: [get_external_ip.to_s, :white] } ] ) puts(Paint["\nYou can add this IP to third party white list", :white]) puts(Paint["\nPlease git push to update your github workflow now!", :yellow]) true end private def update_env instance_name = Souls.configuration.instance_name private_instance_ip = `gcloud sql instances list | grep #{instance_name} | awk '{print $6}'`.strip Dir.chdir(Souls.get_mother_path.to_s) do file_path = ".env.production" env_production = File.readlines(file_path) env_production[0] = "SOULS_DB_HOST=#{private_instance_ip}\n" File.open(file_path, "w") { |f| f.write(env_production.join) } end system("gh secret set DB_HOST -b #{private_instance_ip}") end def get_external_ip app_name = Souls.configuration.app `gcloud compute addresses list | grep #{app_name}-worker-ip | awk '{print $2}'`.strip end def create_network app_name = Souls.configuration.app system("gcloud compute networks create #{app_name}") end def create_firewall_tcp(range: "10.124.0.0/28") app_name = Souls.configuration.app system( "gcloud compute firewall-rules create #{app_name} \ --network #{app_name} --allow tcp,udp,icmp --source-ranges #{range}" ) end def create_firewall_ssh app_name = Souls.configuration.app system( "gcloud compute firewall-rules create #{app_name}-ssh --network #{app_name} \ --allow tcp:22,tcp:3389,icmp" ) end def create_subnet(range: "10.124.0.0/28") app_name = Souls.configuration.app region = Souls.configuration.region system( "gcloud compute networks subnets create #{app_name}-subnet \ --range=#{range} --network=#{app_name} --region=#{region}" ) end def create_connector app_name = Souls.configuration.app project_id = Souls.configuration.project_id region = Souls.configuration.region system( "gcloud compute networks vpc-access connectors create #{app_name}-connector \ --region=#{region} \ --subnet-project=#{project_id} \ --subnet=#{app_name}-subnet" ) end def create_router app_name = Souls.configuration.app region = Souls.configuration.region system("gcloud compute routers create #{app_name}-router --network=#{app_name} --region=#{region}") end def create_external_ip app_name = Souls.configuration.app region = Souls.configuration.region system("gcloud compute addresses create #{app_name}-worker-ip --region=#{region}") end def create_nat app_name = Souls.configuration.app region = Souls.configuration.region system( "gcloud compute routers nats create #{app_name}-worker-nat \ --router=#{app_name}-router \ --region=#{region} \ --nat-custom-subnet-ip-ranges=#{app_name}-subnet \ --nat-external-ip-pool=#{app_name}-worker-ip" ) end def network_list system("gcloud compute networks list") end def update_workflows app_name = Souls.configuration.app Dir.chdir(Souls.get_mother_path.to_s) do workflow_paths = Dir[".github/workflows/*.yml"] workflow_paths.each do |file_path| workflow = File.readlines(file_path) index = workflow.index { |e| e =~ /.*--memory=.*/ } + 1 egress_index = workflow.index { |e| e =~ /.*--vpc-egress=.*/ } connector_index = workflow.index { |e| e =~ /.*--vpc-connector=.*/ } if !file_path.end_with?("/api.yml") && egress_index.nil? workflow.insert(index, " --vpc-egress=all \\\n") end workflow.insert(index, " --vpc-connector=#{app_name}-connector \\\n") if connector_index.nil? File.open(file_path, "w") { |f| f.write(workflow.join) } puts(Paint % ["Updated file! : %{white_text}", :green, { white_text: [file_path.to_s, :white] }]) end end end end end
35.211268
114
0.6172
18261a5cb81ea704c89c7f84e5c0855496d5f654
1,206
module Api class LabelsController < ApplicationController include Contributable before_action :ensure_signed_in, except: [:index, :show] def create @label = Label.new(label_params) if @label.save render json: @label else render json: @label.errors.full_messages, status: 422 end end def update @label = Label.find(params[:id]) if @label.update(label_update_params) add_contribution(@label) render json: @label else render json @label.errors.full_messages, status: 422 end end def show @label = Label .includes(records: :artist) .includes(:comments) .includes(:contributors) .find(params[:id]) @records = @label .records .page(params[:page]) render :show end def index @labels = Label .order_by(params[:order]) .page(params[:page]) render :index end private def label_params params .require(:label) .permit(:title) end def label_update_params params .require(:label) .permit(:profile, :image) end end end
18.84375
61
0.579602
791dd0dcf4c716549f42959d84db98e8a3c93208
1,441
require 'active_model' require 'models/helpers/metadata_helpers' require 'messages/metadata_validator_helper' module VCAP::CloudController::Validators class LabelSelectorRequirementValidator < ActiveModel::Validator MAX_REQUIREMENTS = 50 MISSING_LABEL_SELECTOR_ERROR = 'Missing label_selector value'.freeze TOO_MANY_REQUIREMENTS_ERROR = "Too many label_selector requirements (maximum is #{MAX_REQUIREMENTS})".freeze INVALID_LABEL_SELECTOR_ERROR = 'Invalid label_selector value'.freeze def validate(record) if record.requirements.empty? record.errors[:base] << MISSING_LABEL_SELECTOR_ERROR return end if record.requirements.length > MAX_REQUIREMENTS record.errors[:base] << TOO_MANY_REQUIREMENTS_ERROR return end record.requirements.each do |r| res = valid_requirement?(r) record.errors[:base] << res.message unless res.is_valid? end end private def valid_requirement?(requirement) return VCAP::CloudController::MetadataError.error(INVALID_LABEL_SELECTOR_ERROR) if requirement.nil? res = MetadataValidatorHelper.new(key: requirement.key).key_error return res unless res.is_valid? requirement.values.each do |v| res = MetadataValidatorHelper.new(value: v).value_error return res unless res.is_valid? end VCAP::CloudController::MetadataError.none end end end
31.326087
112
0.729355
d5e74d4a60e09fa38cf10f400bcaddc4ee398b82
8,781
Revs::Application.routes.draw do root :to => "catalog#index" get "bookmarks", :to => "application#routing_error" # we are not using blacklight bookmarks, so a request to get them should fail nicely Blacklight.add_routes(self) # override devise controllers as needed devise_for :users, :controllers => { :sessions => "sessions", :registrations=>"registrations", :passwords=>"passwords" } # extend the default devise session controller with our own to override some methods # ajax calls to confirm uniqueness of email and username as a convience to user before they submit the form devise_scope :user do match 'check_username', :to=>"registrations#check_username", :via=>:post match 'check_email', :to=>"registrations#check_email", :via=>:post match 'users/edit_account', :to=>"registrations#edit_account", :as=>'edit_user_account', :via=>:get match 'users/update_account', :to=>"registrations#update_account", :as=>'update_user_account', :via=>:put match "users/webauth_login" => "sessions#webauth_login", :as => "webauth_login", :via=>:get match "users/webauth_logout" => "sessions#webauth_logout", :as => "webauth_logout", :via=>:delete end # version and faq pages get 'version', :to=>'about#show', :defaults => {:id=>'version'}, :as => 'version' get 'faq', :to=>'about#show', :defaults => {:id=>'faq'}, :as => 'faq' get 'search', :to=> 'catalog#index', :as=>'search' match 'autocomplete', :to=>'catalog#autocomplete', :as=>'autocomplete', :via=>:get match 'notice_dismissed', :to=>'catalog#notice_dismissed', :as=>'notice_dismissed', :via=>:post # all collections pages helper route get 'collection', :to => 'collection#index', :as => 'all_collections' # ajax call from home page to get more images for the carousel get 'update_carousel', :to => 'catalog#update_carousel', :as => 'update_carousel' # ajax call from item page to show collections grid at bottom of the page get 'show_collection_members_grid/:id', :to => 'catalog#show_collection_members_grid', :as => 'show_collection_members_grid' # helper routes to we can have a friendly URL for items and collections get ':id', :to=>'catalog#show', :constraints => {:id => /[a-z]{2}\d{3}[a-z]{2}\d{4}/} # so that /DRUID goes to the item page get 'item/:id', :to=> 'catalog#show', :as =>'item', :constraints => {:id => /[a-z]{2}\d{3}[a-z]{2}\d{4}/} get 'collection/:id', :to=> 'catalog#show', :as =>'collection', :constraints => {:id => /[a-z]{2}\d{3}[a-z]{2}\d{4}/} # public user profile pages resources :user do collection do match ':id/favorites', :to=>'user#favorites', :as=>'user_favorites', :via=>:get, :constraints => {:id => /\w+.+/} match ':id/galleries', :to=>'user#galleries', :as=>'user_galleries', :via=>:get, :constraints => {:id => /\w+.+/} match ':id/annotations', :to=>'user#annotations', :as=>'user_annotations', :via=>:get, :constraints => {:id => /\w+.+/} match ':id/flags', :to=>'user#flags', :as=>'user_flags', :via=>:get, :constraints => {:id => /\w+.+/} match ':id/edits', :to=>'user#edits', :as=>'user_edits', :via=>:get, :constraints => {:id => /\w+.+/} match ':id', :to=>'user#show', :via=>:get, :constraints => {:id => /\w+.+/} end end # Handles all About pages. get 'about', :to => 'about#show', :as => 'about_project', :defaults => {:id=>'project'} # no page specified, go to project page match 'contact', :to=> 'about#contact', :as=>'contact_us', :via=>:get get 'about/contact', :to=> 'about#contact' # specific contact us about page post 'about/contact', :to=> 'about#send_contact', :as=>'send_contact' get 'about/tutorials', :to=> 'about#tutorials', :as => 'tutorials' # specific tutorials list page get 'about/boom', :to => 'about#boom' # test exception handling get 'about/:id', :to => 'about#show', :as=>'about_pages' # catch anything else and direct to show page with ID parameter of partial to show # term acceptance dialog match 'accept_terms', :to=> 'application#accept_terms', :as=> 'accept_terms', :via=>:post # bulk metadata editing post 'catalog', :to=>'catalog#index', :as=>'bulk_edit' resources :annotations do collection do get 'for_image/:id', :to => 'annotations#index_by_druid',:constraints => {:id => /[a-z]{2}\d{3}[a-z]{2}\d{4}/} get 'show_image_number/:id', :to => 'annotations#show_image_number',:constraints => {:id => /[a-z]{2}\d{3}[a-z]{2}\d{4}/}, :as=>'show_image_number' end end resources :galleries resources :lists resources :saved_items do collection do get 'cancel/:id', :to => 'saved_items#cancel', :as=>'cancel' post 'sort', :to => 'saved_items#sort', :as=>'sort' post 'manage', :to => 'saved_items#manage', :as=>'manage' end end resources :flags do collection do post 'bulk_update', :to=>'flags#bulk_update', :as=>'bulk_update' get 'for_image/:id', :to => 'flags#index_by_druid' get 'update_flag_table', :to => 'user#update_flag_table' get 'update_curator_flag_table', :to => 'user#curator_update_flag_table' end end # admin pages get 'admin', :to => 'admin#index', :as=>'admin_dashboard' # admin dashboard namespace :admin do resources :users do collection do post 'bulk_update_status', :to => 'users#bulk_update_status' post 'purge_inactive_users', :to => 'users#purge_inactive_users' end end resources :saved_queries do collection do post 'sort', :to => 'saved_queries#sort', :as=>'sort' end end resources :ontologies do collection do post 'update_terms/:field', :to =>'ontologies#update_terms', :as=>'update_terms' end end resources :collection_highlights do collection do post 'set_highlight/:id', :to => 'collection_highlights#set_highlight' end end resources :gallery_highlights do collection do post 'set_highlight/:id', :to => 'gallery_highlights#set_highlight' post 'sort', :to => 'gallery_highlights#sort', :as=>'sort' end end end # curator pages namespace :curator do resources :tasks do collection do post 'set_edit_mode/:id', :to => 'tasks#set_edit_mode' get 'autocomplete_user', :to => 'tasks#autocomplete_user' put 'item/:id/edit_metadata', :to => 'tasks#edit_metadata', :as => 'edit_metadata' put 'item/:id/set_top_priority_item', :to => 'tasks#set_top_priority_item', :as => 'set_top_priority_item' put 'item/:id/set_visibility', :to => 'tasks#set_visibility', :as => 'set_visibility' get 'annotations', :to => 'tasks#annotations', :as=>"annotations_table" get 'edits', :to => 'tasks#edits', :as=>"edits_table" get 'flags', :to => 'tasks#flags', :as=>"flags_table" get 'favorites', :to => 'tasks#favorites', :as=>"favorites_table" get 'galleries', :to => 'tasks#galleries', :as=>"galleries_table" end end resources :help do collection do get ':action(/:id)(.:format)' end end end match "*gibberish", :to => "application#routing_error", :via=>[:get,:post,:put] # The priority is based upon order of creation: # first created -> highest priority. # Sample of regular route: # match 'products/:id' => 'catalog#view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # resources :products # Sample resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Sample resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Sample resource route with more complex sub-resources # resources :products do # resources :comments # resources :sales do # get 'recent', :on => :collection # end # end # Sample resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end # See how all your routes lay out with "rake routes" # This is a legacy wild controller route that's not recommended for RESTful applications. # Note: This route will make all actions in every controller accessible via GET requests. # match ':controller(/:action(/:id))(.:format)' end
41.616114
207
0.643321
083d3d308a95e39e5428cdea41f65b8f77a87f9f
1,344
## -*- Ruby -*- ## Tree builder class for Japanese encoding ## 1998 by yoshidam require 'xml/dom/builder' module XML module DOM class JapaneseBuilder<Builder require 'kconv' include Kconv require 'uconv' include Uconv def nameConverter(str) u8toeuc(str) end def cdataConverter(str) u8toeuc(str) end def parseStream(stream, trim = false) ## empty file if ((xml = stream.gets).nil?); exit 1; end ## rewrite encoding in XML decl. if xml =~ /^<\?xml\sversion=.+\sencoding=.EUC-JP./i xml.sub!(/EUC-JP/i, "UTF-8") encoding = 'EUC-JP' elsif xml =~ /^<\?xml\sversion=.+\sencoding=.Shift_JIS./i xml.sub!(/Shift_JIS/i, "UTF-8") encoding = "Shift_JIS" elsif xml =~ /^<\?xml\sversion=.+\sencoding=.ISO-2022-JP./i xml.sub!(/ISO-2022-JP/i, "UTF-8") encoding = "ISO-2022-JP" end ## read body xml += String(stream.read) ## convert body encoding if encoding == "EUC-JP" xml = euctou8(xml) elsif encoding == "Shift_JIS" xml = euctou8(kconv(xml, EUC, SJIS)) elsif encoding == "ISO-2022-JP" xml = euctou8(kconv(xml, EUC, JIS)) end return parse(xml, trim) end def Uconv.unknown_unicode_handler(u) return '®' end end end end
22.779661
65
0.575149
2116f4a0d44560d1247152fa910fe151f2b20193
1,373
require 'logger' require 'nokogiri' require 'json' require './page_saver.rb' require './config_loader.rb' ############## Initialize conf = ConfigLoader.load('tennis.conf') JSON_OUTDIR = conf::JSON_OUT_DIR || 'file/json' HTML_OUTDIR = conf::HTML_OUT_DIR || 'file/html' logdir = conf::LOG_DIR || 'log' #$log = Logger.new("#{logdir}/#{File.basename(__FILE__)}.log",'daily') $log = Logger.new(STDOUT) $log.level = conf::LOG_LEVEL $log.info File.basename(__FILE__)+' start' ############# ranking convert html to json $log.info "converting ranking history page to json" id="RogerFederer" infile = "#{HTML_OUTDIR}/atp_player_ranking_history_#{id}.html" doc = File.open(infile) {|f| Nokogiri::HTML(f) } rankings = { :id => id, :ranking_history => [] } rows = doc.search('#playerRankHistoryContainer > table > tbody > tr') rows.each do |r| rankings[:ranking_history] << { :date => Date.parse(r.at('td:nth-child(1)').text.strip), :singles => r.at('td:nth-child(2)').text.strip, :doubles => r.at('td:nth-child(3)').text.strip, } end #$log.info JSON.pretty_generate(rankings) FileUtils.mkdir_p(JSON_OUTDIR) unless Dir.exist?(JSON_OUTDIR) outfile_full=File.join(JSON_OUTDIR,"rankings_#{id}.json") File.write(outfile_full, JSON.pretty_generate(rankings)) $log.info {"converted successful #{infile} to #{outfile_full}"} $log.info File.basename(__FILE__)+' end'
30.511111
70
0.694829
1a4da0a9eefadb3f61cc56c7cae44f6a7fc72fea
1,021
# # Be sure to run `pod lib lint RSDTesting.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 = "RSDTesting" s.version = "0.1.2" s.summary = "Helper code for tests written in Swift." s.description = <<-DESC Testing helpers for asynchronous code, faking, mocking, and swizzling DESC s.homepage = "https://github.com/RaviDesai/RSDTesting" s.license = 'MIT' s.author = { "RaviDesai" => "[email protected]" } s.source = { :git => "https://github.com/RaviDesai/RSDTesting.git", :tag => s.version.to_s } s.platform = :ios, '9.0' s.requires_arc = true s.source_files = 'Pod/Classes/**/*' # s.resource_bundles = { # 'RSDTesting' => ['Pod/Assets/*.png'] # } s.frameworks = 'UIKit', 'XCTest' end
30.939394
104
0.605289
79e234f6b655e02266fee2c92b69a16664a2716f
3,024
# 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::Network::Mgmt::V2018_12_01 module Models # # Response for ListFrontendIPConfiguration API service call. # class LoadBalancerFrontendIPConfigurationListResult include MsRestAzure include MsRest::JSONable # @return [Array<FrontendIPConfiguration>] A list of frontend IP # configurations in a load balancer. attr_accessor :value # @return [String] The URL to get the next set of results. attr_accessor :next_link # return [Proc] with next page method call. attr_accessor :next_method # # Gets the rest of the items for the request, enabling auto-pagination. # # @return [Array<FrontendIPConfiguration>] operation results. # def get_all_items items = @value page = self while page.next_link != nil && !page.next_link.strip.empty? do page = page.get_next_page items.concat(page.value) end items end # # Gets the next page of results. # # @return [LoadBalancerFrontendIPConfigurationListResult] with next page # content. # def get_next_page response = @next_method.call(@next_link).value! unless @next_method.nil? unless response.nil? @next_link = response.body.next_link @value = response.body.value self end end # # Mapper for LoadBalancerFrontendIPConfigurationListResult class as Ruby # Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'LoadBalancerFrontendIPConfigurationListResult', type: { name: 'Composite', class_name: 'LoadBalancerFrontendIPConfigurationListResult', model_properties: { value: { client_side_validation: true, required: false, serialized_name: 'value', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'FrontendIPConfigurationElementType', type: { name: 'Composite', class_name: 'FrontendIPConfiguration' } } } }, next_link: { client_side_validation: true, required: false, read_only: true, serialized_name: 'nextLink', type: { name: 'String' } } } } } end end end end
29.359223
80
0.549603
5d54d7f3975f3ee0363b146f0d819564c6f79cd0
5,275
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: peer/chaincode_shim.proto require 'google/protobuf' require 'peer/chaincode_event_pb' require 'peer/proposal_pb' require 'google/protobuf/timestamp_pb' Google::Protobuf::DescriptorPool.generated_pool.build do add_message 'protos.ChaincodeMessage' do optional :type, :enum, 1, 'protos.ChaincodeMessage.Type' optional :timestamp, :message, 2, 'google.protobuf.Timestamp' optional :payload, :bytes, 3 optional :txid, :string, 4 optional :proposal, :message, 5, 'protos.SignedProposal' optional :chaincode_event, :message, 6, 'protos.ChaincodeEvent' optional :channel_id, :string, 7 end add_enum 'protos.ChaincodeMessage.Type' do value :UNDEFINED, 0 value :REGISTER, 1 value :REGISTERED, 2 value :INIT, 3 value :READY, 4 value :TRANSACTION, 5 value :COMPLETED, 6 value :ERROR, 7 value :GET_STATE, 8 value :PUT_STATE, 9 value :DEL_STATE, 10 value :INVOKE_CHAINCODE, 11 value :RESPONSE, 13 value :GET_STATE_BY_RANGE, 14 value :GET_QUERY_RESULT, 15 value :QUERY_STATE_NEXT, 16 value :QUERY_STATE_CLOSE, 17 value :KEEPALIVE, 18 value :GET_HISTORY_FOR_KEY, 19 value :GET_STATE_METADATA, 20 value :PUT_STATE_METADATA, 21 end add_message 'protos.GetState' do optional :key, :string, 1 optional :collection, :string, 2 end add_message 'protos.GetStateMetadata' do optional :key, :string, 1 optional :collection, :string, 2 end add_message 'protos.PutState' do optional :key, :string, 1 optional :value, :bytes, 2 optional :collection, :string, 3 end add_message 'protos.PutStateMetadata' do optional :key, :string, 1 optional :collection, :string, 3 optional :metadata, :message, 4, 'protos.StateMetadata' end add_message 'protos.DelState' do optional :key, :string, 1 optional :collection, :string, 2 end add_message 'protos.GetStateByRange' do optional :startKey, :string, 1 optional :endKey, :string, 2 optional :collection, :string, 3 optional :metadata, :bytes, 4 end add_message 'protos.GetQueryResult' do optional :query, :string, 1 optional :collection, :string, 2 optional :metadata, :bytes, 3 end add_message 'protos.QueryMetadata' do optional :pageSize, :int32, 1 optional :bookmark, :string, 2 end add_message 'protos.GetHistoryForKey' do optional :key, :string, 1 end add_message 'protos.QueryStateNext' do optional :id, :string, 1 end add_message 'protos.QueryStateClose' do optional :id, :string, 1 end add_message 'protos.QueryResultBytes' do optional :resultBytes, :bytes, 1 end add_message 'protos.QueryResponse' do repeated :results, :message, 1, 'protos.QueryResultBytes' optional :has_more, :bool, 2 optional :id, :string, 3 optional :metadata, :bytes, 4 end add_message 'protos.QueryResponseMetadata' do optional :fetched_records_count, :int32, 1 optional :bookmark, :string, 2 end add_message 'protos.StateMetadata' do optional :metakey, :string, 1 optional :value, :bytes, 2 end add_message 'protos.StateMetadataResult' do repeated :entries, :message, 1, 'protos.StateMetadata' end end module Protos ChaincodeMessage = Google::Protobuf::DescriptorPool.generated_pool.lookup('protos.ChaincodeMessage').msgclass ChaincodeMessage::Type = Google::Protobuf::DescriptorPool.generated_pool.lookup('protos.ChaincodeMessage.Type').enummodule GetState = Google::Protobuf::DescriptorPool.generated_pool.lookup('protos.GetState').msgclass GetStateMetadata = Google::Protobuf::DescriptorPool.generated_pool.lookup('protos.GetStateMetadata').msgclass PutState = Google::Protobuf::DescriptorPool.generated_pool.lookup('protos.PutState').msgclass PutStateMetadata = Google::Protobuf::DescriptorPool.generated_pool.lookup('protos.PutStateMetadata').msgclass DelState = Google::Protobuf::DescriptorPool.generated_pool.lookup('protos.DelState').msgclass GetStateByRange = Google::Protobuf::DescriptorPool.generated_pool.lookup('protos.GetStateByRange').msgclass GetQueryResult = Google::Protobuf::DescriptorPool.generated_pool.lookup('protos.GetQueryResult').msgclass QueryMetadata = Google::Protobuf::DescriptorPool.generated_pool.lookup('protos.QueryMetadata').msgclass GetHistoryForKey = Google::Protobuf::DescriptorPool.generated_pool.lookup('protos.GetHistoryForKey').msgclass QueryStateNext = Google::Protobuf::DescriptorPool.generated_pool.lookup('protos.QueryStateNext').msgclass QueryStateClose = Google::Protobuf::DescriptorPool.generated_pool.lookup('protos.QueryStateClose').msgclass QueryResultBytes = Google::Protobuf::DescriptorPool.generated_pool.lookup('protos.QueryResultBytes').msgclass QueryResponse = Google::Protobuf::DescriptorPool.generated_pool.lookup('protos.QueryResponse').msgclass QueryResponseMetadata = Google::Protobuf::DescriptorPool.generated_pool.lookup('protos.QueryResponseMetadata').msgclass StateMetadata = Google::Protobuf::DescriptorPool.generated_pool.lookup('protos.StateMetadata').msgclass StateMetadataResult = Google::Protobuf::DescriptorPool.generated_pool.lookup('protos.StateMetadataResult').msgclass end
40.576923
124
0.753365
4a48ed915b4aac891dcb7a1eedca42f281836108
1,594
class Libu2fServer < Formula desc "Server-side of the Universal 2nd Factor (U2F) protocol" homepage "https://developers.yubico.com/libu2f-server/" url "https://developers.yubico.com/libu2f-server/Releases/libu2f-server-1.1.0.tar.xz" sha256 "8dcd3caeacebef6e36a42462039fd035e45fa85653dcb2013f45e15aad49a277" revision 1 bottle do cellar :any sha256 "8b2986796fde4c4af2ceea03780de6310932f5b26744118d56920694777e0738" => :high_sierra sha256 "90ec17a1fccbb6d6ed4e8cd95d6828ef1b0fe80f173435e7124fab938d3af812" => :sierra sha256 "566d3f52eef7dca1671f93f8f2b1f351e960b3c98a3737ed7f14843296d5a601" => :el_capitan end depends_on "check" => :build depends_on "gengetopt" => :build depends_on "help2man" => :build depends_on "pkg-config" => :build depends_on "json-c" depends_on "openssl" def install ENV["LIBSSL_LIBS"] = "-lssl -lcrypto -lz" ENV["LIBCRYPTO_LIBS"] = "-lcrypto -lz" ENV["PKG_CONFIG"] = "#{Formula["pkg-config"].opt_bin}/pkg-config" system "./configure", "--prefix=#{prefix}" system "make", "install" end test do (testpath/"test.c").write <<~EOS #include <u2f-server/u2f-server.h> int main() { if (u2fs_global_init(U2FS_DEBUG) != U2FS_OK) { return 1; } u2fs_ctx_t *ctx; if (u2fs_init(&ctx) != U2FS_OK) { return 1; } u2fs_done(ctx); u2fs_global_done(); return 0; } EOS system ENV.cc, "test.c", "-o", "test", "-I#{include}", "-L#{lib}", "-lu2f-server" system "./test" end end
28.464286
93
0.650565
4a5b03eb2b01548dd8477dcf84cb0ad00b6682e1
1,270
# frozen_string_literal: true called_from_env_rb = caller.detect { |f| f =~ /\/env\.rb:/ } if called_from_env_rb env_caller = File.dirname(called_from_env_rb) require 'rails' require 'cucumber/rails/application' ENV['RAILS_ENV'] ||= 'test' ENV['RAILS_ROOT'] ||= File.expand_path(env_caller + '/../..') require File.expand_path(ENV['RAILS_ROOT'] + '/config/environment') require 'cucumber/rails/action_dispatch' require 'rails/test_help' unless Rails.application.config.cache_classes || defined?(Spring) warn "WARNING: You have set Rails' config.cache_classes to false (Spring needs cache_classes set to false). This is known to cause problems with database transactions. Set config.cache_classes to true if you want to use transactions." end require 'cucumber/rails/world' require 'cucumber/rails/hooks' require 'cucumber/rails/capybara' require 'cucumber/rails/database' MultiTest.disable_autorun else warn "WARNING: Cucumber-rails required outside of env.rb. The rest of loading is being deferred until env.rb is called. To avoid this warning, move 'gem \'cucumber-rails\', require: false' under only group :test in your Gemfile. If already in the :test group, be sure you are specifying 'require: false'." end
37.352941
98
0.74252
2614d56af132f60010fe6571a33afbb4e2b7f292
1,222
require 'sidekiq/web' Rails.application.routes.draw do root to: 'static_pages#home' if Rails.env.production? Sidekiq::Web.use Rack::Auth::Basic do |username, password| ActiveSupport::SecurityUtils.secure_compare( ::Digest::SHA256.hexdigest(username), ::Digest::SHA256.hexdigest(Rails.application.credentials.dig(:sidekiq, :username)) ) && ActiveSupport::SecurityUtils.secure_compare( ::Digest::SHA256.hexdigest(password), ::Digest::SHA256.hexdigest(Rails.application.credentials.dig(:sidekiq, :password)) ) end end mount Sidekiq::Web, at: '/sidekiq' resources :offices, only: %i[index show] do get :suggest, on: :collection end resources :prosecutors, only: %i[index show] do get :suggest, on: :collection get :export, on: :collection end resources :statistics, only: :index, path: :criminality do get :suggest, on: :collection get :png, on: :collection get :export, on: :collection get :embed, on: :collection end # error pages %w[400 404 422 500 503].each { |code| get "/#{code}", to: 'errors#show', code: code } match '/:slug', via: :get, to: 'static_pages#show', as: :static_page end
29.095238
92
0.662029
ac31ddc0e6ccad407b261ae059a044dd5b6aa104
1,004
describe Transducers::Process do let(:base_process) { described_class.new(init: init, step: step, completion: completion) } let(:init) { instance_double(Proc) } let(:step) { instance_double(Proc) } let(:completion) { instance_double(Proc) } describe '#taking' do let(:process) { base_process.taking(2) } let(:inner_result) { double } let(:value) { double } before do allow(init).to receive(:call).and_return(inner_result) allow(step).to receive(:call).with(inner_result, value).and_return(inner_result) end it 'pass through until count met' do expect(step).to receive(:call).with(inner_result, value) .exactly(2).times .and_return(inner_result) result = process.init.call expect(result).to_not be_a(ReducedValue) result = process.step.call(result, value) expect(result).to_not be_a(ReducedValue) result = process.step.call(result, value) expect(result).to be_a(ReducedValue) end end end
29.529412
92
0.677291
f8276c9023dcc2c3bb82ed9a25adb2f2eaf3dd16
1,129
require File.dirname(__FILE__) + '/../../../spec_helper' not_supported_on :ironruby do has_tty? do # needed for CI until we figure out a better way require 'readline' describe "Readline::HISTORY.[]=" do before(:each) do Readline::HISTORY.push("1", "2", "3") end after(:each) do Readline::HISTORY.pop Readline::HISTORY.pop Readline::HISTORY.pop end it "returns the new value for the passed index" do (Readline::HISTORY[1] = "second test").should == "second test" end it "raises an IndexError when there is no item at the passed positive index" do lambda { Readline::HISTORY[10] = "test" }.should raise_error(IndexError) end it "sets the item at the given index" do Readline::HISTORY[0] = "test" Readline::HISTORY[0].should == "test" Readline::HISTORY[1] = "second test" Readline::HISTORY[1].should == "second test" end it "raises an IndexError when there is no item at the passed negative index" do lambda { Readline::HISTORY[10] = "test" }.should raise_error(IndexError) end end end end
28.225
83
0.641275
ed386e3a767f05db8f02984638b201ee84323647
89
FactoryGirl.define do factory :bitcoin do price 1.5 currency "MyString" end end
11.125
21
0.719101
8777659d8c74eaaf2b19562b3e71360fcdf82c16
409
# frozen_string_literal: true require 'test_helper' class Editor::UsersControllerTest < ActionDispatch::IntegrationTest test 'should get index' do get editor_users_index_url assert_response :success end test 'should get list' do get editor_users_list_url assert_response :success end test 'should get show' do get editor_users_show_url assert_response :success end end
19.47619
67
0.760391
18283d409100368e3f5100f7153ca059b5953c81
3,177
class Madlib < Formula desc "Library for scalable in-database analytics." homepage "https://madlib.incubator.apache.org/" url "https://github.com/apache/madlib/archive/rel/v1.12.tar.gz" sha256 "4f21b1f463f22ee7ddefbe2e4c52e254a7156aefef980f1b3f26479f5f8c1672" head "https://github.com/apache/madlib.git" bottle do sha256 "2b3b00b26a10a1a91c47b5110f97584ffa5fd3c32a0187d23af2c842b23840e4" => :sierra sha256 "e2e20a7dabb02a1912685611f5cf2481a91794b6f4396a94b07b286815b8bffd" => :el_capitan sha256 "307cb968d0799c3ac75db9cbfe691f2be89dd4170dcf3814df0b71be0f9d742b" => :yosemite end boost_opts = [] boost_opts << "c++11" if MacOS.version < :mavericks depends_on "[email protected]" => boost_opts depends_on "[email protected]" => boost_opts if build.with? "python" depends_on "cmake" => :build depends_on "postgresql" => ["with-python"] depends_on :python => :optional resource "pyxb" do url "https://downloads.sourceforge.net/project/pyxb/pyxb/1.2.4/PyXB-1.2.4.tar.gz" sha256 "024f9d4740fde187cde469dbe8e3c277fe522a3420458c4ba428085c090afa69" end resource "eigen" do url "https://bitbucket.org/eigen/eigen/get/3.2.10.tar.gz" sha256 "04f8a4fa4afedaae721c1a1c756afeea20d3cdef0ce3293982cf1c518f178502" end fails_with :clang do build 503 cause "See http://jira.madlib.net/browse/MADLIB-865" end fails_with :gcc do build 5666 cause "See http://jira.madlib.net/browse/MADLIB-865" end def install # http://jira.madlib.net/browse/MADLIB-913 ENV.libstdcxx if ENV.compiler == :clang resource("pyxb").fetch resource("eigen").fetch args = %W[ -DCMAKE_INSTALL_PREFIX=#{prefix} -DCMAKE_BUILD_TYPE=Release -DPYXB_TAR_SOURCE=#{resource("pyxb").cached_download} -DEIGEN_TAR_SOURCE=#{resource("eigen").cached_download} ] system "./configure", *args system "make", "install" # Replace symlink with real directory bin.delete bin.mkdir # MADlib has an unusual directory structure: bin is a symlink # to Current/bin, which in turn is a symlink to # Versions/<current version>/bin. Homebrew won't link # bin/madpack and, even if it did, madpack would not find # its dependencies. Hence, we create a shim script. bin.write_exec_script("#{prefix}/Current/bin/madpack") end def caveats; <<-EOS.undent MADlib must be rebuilt if you upgrade PostgreSQL: brew reinstall madlib EOS end test do # The following fails if madpack cannot find its dependencies. system "#{bin}/madpack", "-h" pg_bin = Formula["postgresql"].opt_bin pg_port = "55562" system "#{pg_bin}/initdb", testpath/"test" pid = fork { exec "#{pg_bin}/postgres", "-D", testpath/"test", "-p", pg_port } begin sleep 2 system "#{pg_bin}/createdb", "-p", pg_port, "test_madpack" system "#{bin}/madpack", "-p", "postgres", "-c", "#{ENV["USER"]}/@localhost:#{pg_port}/test_madpack", "install" system "#{bin}/madpack", "-p", "postgres", "-c", "#{ENV["USER"]}/@localhost:#{pg_port}/test_madpack", "install-check" ensure Process.kill 9, pid Process.wait pid end end end
33.09375
123
0.694051
1c404f8b1880a4fb48ebafe2d69ae190b5247215
283
require File.expand_path('../support/helpers', __FILE__) describe "apache2::mod_fastcgi" do include Helpers::Apache it 'enables fastcgi_module' do skip if %w{rhel fedora}.include?(node['platform_family']) apache_enabled_modules.must_include "fastcgi_module" end end
23.583333
61
0.756184
abd6ab0aff6aa65de33a64081650259ff33f49cb
1,420
require "ips_validator/version" require 'ips_validator/loader' require 'ips_validator/validator' module IpsValidator class Runner class << self def run(args) num_valid = 0 num_invalid = 0 num_error = 0 total = 0 puts "\n" statuses = [] types = [] categories = [] layers = [] xip = args[0].to_sym file_names = args[1..-1] file_names.map do |file_name| attributes = Loader.load(file_name) total+=1 begin validator = ValidatorFactory.make(xip) v = validator.new(attributes) if v.valid? num_valid+=1 else num_invalid+=1 puts "#{file_name} is NOT valid:\t #{v.errors.messages}" end statuses.push v.status rescue => e puts "Warning: #{file_name} \t #{e}" num_error+=1 end end puts "\n\ntotal:#{total}, valid:#{num_valid}, invalid:#{num_invalid}, errors:#{num_error}" puts "\tstatuses: #{aggregate(statuses)}" raise "#{num_invalid} invalid entities" unless num_invalid == 0 end private def aggregate(array) array.group_by{|k,v| k}.map{|k,v| [k,v.length]} end end end end
26.792453
99
0.493662
0383b77a344efb448c3b619266fde6d400edd6e0
155
class ApplicationController < ActionController::Base protect_from_forgery with: :exception def hello render html: "Hello world" end end
19.375
52
0.729032
7a3bda7c21ae1aa2df3367d89648316cf79c0426
634
class Micropost < ApplicationRecord # Joins microposts with user belongs_to :user # Default sorting default_scope -> { order(created_at: :desc) } # CarrierWave method, PictureUploader -> picture_uploader.rb mount_uploader :picture, PictureUploader # Makes sure that user is associated with post validates :user_id, presence: true # Mate sure that content exists and are not longer than 140 character long validates :content, length: { maximum: 140 }, presence: true private def picture_size if picture.size > 5.megabytes errors.add(:picture, 'should be less than 5MB') end end end
28.818182
76
0.722397
91e8d70e89026f97cdaa2421bbad4311cf3e9364
750
# frozen_string_literal: true module Importer module Eprints class JsonParser include Enumerable include LeafAddons::Importer::Eprints::JsonAttributes include LeafAddons::Importer::Eprints::JsonDownloader # For locally overriden methods include Importer::Eprints::JsonAttributesOverrides attr_accessor :attributes def initialize(file_name, downloads_directory) @file_name = file_name @downloads = downloads_directory end # @yieldparam attributes [Hash] the attributes from one eprint def each(&_block) JSON.parse(File.read(@file_name)).each do |eprint| create_attributes(eprint) yield attributes end end end end end
25.862069
68
0.685333
039fd2c2b01b36bf45d0ed7ed0f0d9e165dc6eac
14,064
# frozen_string_literal: true # Use this hook to configure devise mailer, warden hooks and so forth. # Many of these configuration options can be set straight in your model. Devise.setup do |config| # The secret key used by Devise. Devise uses this key to generate # random tokens. Changing this key will render invalid all existing # confirmation, reset password and unlock tokens in the database. # Devise will use the `secret_key_base` as its `secret_key` # by default. You can change it below and use your own secret key. # config.secret_key = '8582f5c5c64a89bf362bc3417084e5d8d13784950b5993bf9fed7e7938dbd16129741af26b5edf6c24e4aefc339b2086971e947a7b9d5483a2d35bade4d8923c' # ==> Controller configuration # Configure the parent class to the devise controllers. # config.parent_controller = 'DeviseController' # ==> Mailer Configuration # Configure the e-mail address which will be shown in Devise::Mailer, # note that it will be overwritten if you use your own mailer class # with default "from" parameter. config.mailer_sender = '[email protected]' # Configure the class responsible to send e-mails. # config.mailer = 'Devise::Mailer' # Configure the parent class responsible to send e-mails. # config.parent_mailer = 'ActionMailer::Base' # ==> ORM configuration # Load and configure the ORM. Supports :active_record (default) and # :mongoid (bson_ext recommended) by default. Other ORMs may be # available as additional gems. require 'devise/orm/active_record' # ==> Configuration for any authentication mechanism # Configure which keys are used when authenticating a user. The default is # just :email. You can configure it to use [:username, :subdomain], so for # authenticating a user, both parameters are required. Remember that those # parameters are used only when authenticating and not when retrieving from # session. If you need permissions, you should implement that in a before filter. # You can also supply a hash where the value is a boolean determining whether # or not authentication should be aborted when the value is not present. # config.authentication_keys = [:email] # Configure parameters from the request object used for authentication. Each entry # given should be a request method and it will automatically be passed to the # find_for_authentication method and considered in your model lookup. For instance, # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. # The same considerations mentioned for authentication_keys also apply to request_keys. # config.request_keys = [] # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. config.case_insensitive_keys = [:email] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. config.strip_whitespace_keys = [:email] # Tell if authentication through request.params is enabled. True by default. # It can be set to an array that will enable params authentication only for the # given strategies, for example, `config.params_authenticatable = [:database]` will # enable it only for database (email + password) authentication. # config.params_authenticatable = true # Tell if authentication through HTTP Auth is enabled. False by default. # It can be set to an array that will enable http authentication only for the # given strategies, for example, `config.http_authenticatable = [:database]` will # enable it only for database authentication. The supported strategies are: # :database = Support basic authentication with authentication key + password # config.http_authenticatable = false # If 401 status code should be returned for AJAX requests. True by default. # config.http_authenticatable_on_xhr = true # The realm used in Http Basic Authentication. 'Application' by default. # config.http_authentication_realm = 'Application' # It will change confirmation, password recovery and other workflows # to behave the same regardless if the e-mail provided was right or wrong. # Does not affect registerable. # config.paranoid = true # By default Devise will store the user in session. You can skip storage for # particular strategies by setting this option. # Notice that if you are skipping storage for all authentication paths, you # may want to disable generating routes to Devise's sessions controller by # passing skip: :sessions to `devise_for` in your config/routes.rb config.skip_session_storage = [:http_auth] # By default, Devise cleans up the CSRF token on authentication to # avoid CSRF token fixation attacks. This means that, when using AJAX # requests for sign in and sign up, you need to get a new CSRF token # from the server. You can disable this option at your own risk. # config.clean_up_csrf_token_on_authentication = true # When false, Devise will not attempt to reload routes on eager load. # This can reduce the time taken to boot the app but if your application # requires the Devise mappings to be loaded during boot time the application # won't boot properly. # config.reload_routes = true # ==> Configuration for :database_authenticatable # For bcrypt, this is the cost for hashing the password and defaults to 11. If # using other algorithms, it sets how many times you want the password to be hashed. # # Limiting the stretches to just one in testing will increase the performance of # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use # a value less than 10 in other environments. Note that, for bcrypt (the default # algorithm), the cost increases exponentially with the number of stretches (e.g. # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). config.stretches = Rails.env.test? ? 1 : 11 # Set up a pepper to generate the hashed password. # config.pepper = 'a2b2f6a3c94c5a67179b3573bc5a631c8cbbe1f5a44222fa12fcf50f1700014eede4cbb92c495a6e890996acd7cd817754867131634c28c9e943cf35c9f340aa' # Send a notification to the original email when the user's email is changed. # config.send_email_changed_notification = false # Send a notification email when the user's password is changed. # config.send_password_change_notification = false # ==> Configuration for :confirmable # A period that the user is allowed to access the website even without # confirming their account. For instance, if set to 2.days, the user will be # able to access the website for two days without confirming their account, # access will be blocked just in the third day. Default is 0.days, meaning # the user cannot access the website without confirming their account. # config.allow_unconfirmed_access_for = 2.days # A period that the user is allowed to confirm their account before their # token becomes invalid. For example, if set to 3.days, the user can confirm # their account within 3 days after the mail was sent, but on the fourth day # their account can't be confirmed with the token any more. # Default is nil, meaning there is no restriction on how long a user can take # before confirming their account. # config.confirm_within = 3.days # If true, requires any email changes to be confirmed (exactly the same way as # initial account confirmation) to be applied. Requires additional unconfirmed_email # db field (see migrations). Until confirmed, new email is stored in # unconfirmed_email column, and copied to email column on successful confirmation. config.reconfirmable = true # Defines which key will be used when confirming an account # config.confirmation_keys = [:email] # ==> Configuration for :rememberable # The time the user will be remembered without asking for credentials again. # config.remember_for = 2.weeks # Invalidates all the remember me tokens when the user signs out. config.expire_all_remember_me_on_sign_out = true # If true, extends the user's remember period when remembered via cookie. # config.extend_remember_period = false # Options to be passed to the created cookie. For instance, you can set # secure: true in order to force SSL only cookies. # config.rememberable_options = {} # ==> Configuration for :validatable # Range for password length. config.password_length = 6..128 # Email regex used to validate email formats. It simply asserts that # one (and only one) @ exists in the given string. This is mainly # to give user feedback and not to assert the e-mail validity. config.email_regexp = /\A[^@\s]+@[^@\s]+\z/ # ==> Configuration for :timeoutable # The time you want to timeout the user session without activity. After this # time the user will be asked for credentials again. Default is 30 minutes. # config.timeout_in = 30.minutes # ==> Configuration for :lockable # Defines which strategy will be used to lock an account. # :failed_attempts = Locks an account after a number of failed attempts to sign in. # :none = No lock strategy. You should handle locking by yourself. # config.lock_strategy = :failed_attempts # Defines which key will be used when locking and unlocking an account # config.unlock_keys = [:email] # Defines which strategy will be used to unlock an account. # :email = Sends an unlock link to the user email # :time = Re-enables login after a certain amount of time (see :unlock_in below) # :both = Enables both strategies # :none = No unlock strategy. You should handle unlocking by yourself. # config.unlock_strategy = :both # Number of authentication tries before locking an account if lock_strategy # is failed attempts. # config.maximum_attempts = 20 # Time interval to unlock the account if :time is enabled as unlock_strategy. # config.unlock_in = 1.hour # Warn on the last attempt before the account is locked. # config.last_attempt_warning = true # ==> Configuration for :recoverable # # Defines which key will be used when recovering the password for an account # config.reset_password_keys = [:email] # Time interval you can reset your password with a reset password key. # Don't put a too small interval or your users won't have the time to # change their passwords. config.reset_password_within = 6.hours # When set to false, does not sign a user in automatically after their password is # reset. Defaults to true, so a user is signed in automatically after a reset. # config.sign_in_after_reset_password = true # ==> Configuration for :encryptable # Allow you to use another hashing or encryption algorithm besides bcrypt (default). # You can use :sha1, :sha512 or algorithms from others authentication tools as # :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20 # for default behavior) and :restful_authentication_sha1 (then you should set # stretches to 10, and copy REST_AUTH_SITE_KEY to pepper). # # Require the `devise-encryptable` gem when using anything other than bcrypt # config.encryptor = :sha512 # ==> Scopes configuration # Turn scoped views on. Before rendering "sessions/new", it will first check for # "users/sessions/new". It's turned off by default because it's slower if you # are using only default views. # config.scoped_views = false # Configure the default scope given to Warden. By default it's the first # devise role declared in your routes (usually :user). # config.default_scope = :user # Set this configuration to false if you want /users/sign_out to sign out # only the current scope. By default, Devise signs out all scopes. # config.sign_out_all_scopes = true # ==> Navigation configuration # Lists the formats that should be treated as navigational. Formats like # :html, should redirect to the sign in page when the user does not have # access, but formats like :xml or :json, should return 401. # # If you have any extra navigational formats, like :iphone or :mobile, you # should add them to the navigational formats lists. # # The "*/*" below is required to match Internet Explorer requests. # config.navigational_formats = ['*/*', :html] # The default HTTP method used to sign out a resource. Default is :delete. config.sign_out_via = :delete # ==> OmniAuth # Add a new OmniAuth provider. Check the wiki for more information on setting # up on your models and hooks. # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' # ==> Warden configuration # If you want to use other strategies, that are not supported by Devise, or # change the failure app, you can configure them inside the config.warden block. # # config.warden do |manager| # manager.intercept_401 = false # manager.default_strategies(scope: :user).unshift :some_external_strategy # end # ==> Mountable engine configurations # When using Devise inside an engine, let's call it `MyEngine`, and this engine # is mountable, there are some extra configurations to be taken into account. # The following options are available, assuming the engine is mounted as: # # mount MyEngine, at: '/my_engine' # # The router that invoked `devise_for`, in the example above, would be: # config.router_name = :my_engine # # When using OmniAuth, Devise cannot automatically set OmniAuth path, # so you need to do it manually. For the users scope, it would be: # config.omniauth_path_prefix = '/my_engine/users/auth' # ==> Turbolinks configuration # If your app is using Turbolinks, Turbolinks::Controller needs to be included to make redirection work correctly: # # ActiveSupport.on_load(:devise_failure_app) do # include Turbolinks::Controller # end end
48.496552
154
0.751422
1dfb52a4fda43c7e8f7539101449223415b30a81
2,834
#!/usr/bin/ruby # # Copyright:: Copyright 2012 Trimble Navigation Ltd. # License:: Apache license, # Original Author:: Matt Lowrie # # Wrapper module for Win32 API constants and methods. # require 'win32/api' module ApiDefs # Constants # # Defined in winuser.h # MOUSEEVENTF_LEFTDOWN = '0002'.hex MOUSEEVENTF_LEFTUP = '0004'.hex MOUSEEVENTF_RIGHTDOWN = '0008'.hex MOUSEEVENTF_RIGHTUP = '0010'.hex PROCESS_QUERY_INFORMATION = '0400'.hex PROCESS_VM_READ = '0010'.hex WM_COMMAND = '0111'.hex WM_NOTIFY = '004e'.hex # Attributes # @enum_child_windows = Win32::API.new('EnumChildWindows', 'LKP', 'I', 'user32') @enum_windows = Win32::API.new('EnumWindows', 'KP', 'L', 'user32') @get_class_name = Win32::API.new('GetClassName', 'LPI', 'I', 'user32') @get_client_rect = Win32::API.new('GetClientRect', 'LP', 'I', 'user32') @get_process_image_file_name = Win32::API.new('GetProcessImageFileName', 'LPI', 'I', 'psapi') @get_window_long = Win32::API.new('GetWindowLong', 'LL', 'L', 'user32') @get_window_rect = Win32::API.new('GetWindowRect', 'LP', 'I', 'user32') @get_window_text = Win32::API.new('GetWindowText', 'LPI', 'I', 'user32') @get_window_thread_process_id = Win32::API.new('GetWindowThreadProcessId', 'LP', 'I','user32') @mouse_event = Win32::API.new('mouse_event', 'LIIII', 'I', 'user32') @move_window = Win32::API.new('MoveWindow', 'LIIIII', 'I', 'user32') @open_process = Win32::API.new('OpenProcess', 'LIL', 'I', 'kernel32') @send_message = Win32::API.new('SendMessage', 'LLLL', 'I', 'user32') @set_cursor_pos = Win32::API.new('SetCursorPos', 'II', 'I', 'user32') # Methods # # These wrapper methods simply return the API method object, so the call() # method on them still needs to be envoked, for example: # ApiDefs.get_class_name.call(hwnd, buffer, buf_size) # Forgetting to use the call() method will result in a ArgumentError with not # enough arguments. # def self.enum_child_windows @enum_child_windows end def self.enum_windows @enum_windows end def self.get_class_name @get_class_name end def self.get_client_rect @get_client_rect end def self.get_process_image_file_name @get_process_image_file_name end def self.get_window_long @get_window_long end def self.get_window_rect @get_window_rect end def self.get_window_text @get_window_text end def self.get_window_thread_process_id @get_window_thread_process_id end def self.mouse_event @mouse_event end def self.move_window @move_window end def self.open_process @open_process end def self.send_message @send_message end def self.set_cursor_pos @set_cursor_pos end end
26
80
0.674312
9193b83e968eae37a923b6c084548a87249aafb6
2,817
require "topological_inventory/satellite/logging" require "receptor_controller-client" module TopologicalInventory module Satellite class Connection class << self def connection(account_number) new(account_number) end end @sync = Mutex.new @receptor_client = nil class << self # Receptor client needs to be singleton due to processing of kafka responses def receptor_client @sync.synchronize do return @receptor_client if @receptor_client.present? @receptor_client = ReceptorController::Client.new(:logger => TopologicalInventory::Satellite.logger) @receptor_client.start end @receptor_client end alias start_receptor_client receptor_client # Stops thread with response worker def stop_receptor_client @sync.synchronize do @receptor_client&.stop end end end def initialize(account_number) self.account_number = account_number receptor_client.identity_header = identity_header end # This header is used only when ReceptorController::Client::Configuration.pre_shared_key is blank (x-rh-rbac-psk) # org_id with any number is required by receptor_client controller def identity_header(account = account_number) @identity ||= { "x-rh-identity" => Base64.strict_encode64( {"identity" => {"account_number" => account, "user" => {"is_org_admin" => true}, "internal" => {"org_id" => '000001'}}}.to_json ) } end def receptor_client self.class.receptor_client end def status(receptor_node_id) response = receptor_client.connection_status(account_number, receptor_node_id) response['status'] end # @return [String] UUID - message ID for callbacks def send_availability_check(source_ref, receptor_node_id, receiver) directive = receptor_client.directive(account_number, receptor_node_id, :directive => "receptor_satellite:health_check", :payload => {'satellite_instance_id' => source_ref.to_s}.to_json, :type => :non_blocking) directive.on_success { |msg_id, response| receiver.availability_check_response(msg_id, response) } .on_error { |msg_id, code, response| receiver.availability_check_error(msg_id, code, response) } .on_timeout { |msg_id| receiver.availability_check_timeout(msg_id) } directive.call end private attr_accessor :account_number end end end
34.353659
139
0.618388
e946375564b1f82e6ceb39284928291d70033d57
5,769
class RegistrationsController < DeviseController prepend_before_action :require_no_authentication, only: [:new, :create, :cancel] prepend_before_action :authenticate_scope!, only: [:edit, :update, :destroy] prepend_before_action :set_minimum_password_length, only: [:new, :edit] # GET /resource/sign_up def new build_resource yield resource if block_given? respond_with resource end # POST /resource def create build_resource(sign_up_params) resource.save yield resource if block_given? if resource.persisted? if resource.active_for_authentication? set_flash_message! :notice, :signed_up sign_up(resource_name, resource) respond_with resource, location: after_sign_up_path_for(resource) else set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}" expire_data_after_sign_in! respond_with resource, location: after_inactive_sign_up_path_for(resource) end else clean_up_passwords resource set_minimum_password_length respond_with resource end end # GET /resource/edit def edit render :edit end # PUT /resource # We need to use a copy of the resource because we don't want to change # the current user in place. def update self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key) prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email) resource_updated = update_resource(resource, account_update_params) yield resource if block_given? if resource_updated set_flash_message_for_update(resource, prev_unconfirmed_email) bypass_sign_in resource, scope: resource_name if sign_in_after_change_password? respond_with resource, location: after_update_path_for(resource) else clean_up_passwords resource set_minimum_password_length respond_with resource end end # DELETE /resource def destroy resource.destroy Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name) set_flash_message! :notice, :destroyed yield resource if block_given? respond_with_navigational(resource){ redirect_to after_sign_out_path_for(resource_name) } end # GET /resource/cancel # Forces the session data which is usually expired after sign # in to be expired now. This is useful if the user wants to # cancel oauth signing in/up in the middle of the process, # removing all OAuth session data. def cancel expire_data_after_sign_in! redirect_to new_registration_path(resource_name) end protected def update_needs_confirmation?(resource, previous) resource.respond_to?(:pending_reconfirmation?) && resource.pending_reconfirmation? && previous != resource.unconfirmed_email end # By default we want to require a password checks on update. # You can overwrite this method in your own RegistrationsController. def update_resource(resource, params) resource.update_with_password(params) end # Build a devise resource passing in the session. Useful to move # temporary session data to the newly created user. def build_resource(hash = {}) self.resource = resource_class.new_with_session(hash, session) end # Signs in a user on sign up. You can overwrite this method in your own # RegistrationsController. def sign_up(resource_name, resource) sign_in(resource_name, resource) end # The path used after sign up. You need to overwrite this method # in your own RegistrationsController. def after_sign_up_path_for(resource) after_sign_in_path_for(resource) if is_navigational_format? end # The path used after sign up for inactive accounts. You need to overwrite # this method in your own RegistrationsController. def after_inactive_sign_up_path_for(resource) scope = Devise::Mapping.find_scope!(resource) router_name = Devise.mappings[scope].router_name context = router_name ? send(router_name) : self context.respond_to?(:root_path) ? context.root_path : "/" end # The default url to be used after updating a resource. You need to overwrite # this method in your own RegistrationsController. def after_update_path_for(resource) sign_in_after_change_password? ? signed_in_root_path(resource) : new_session_path(resource_name) end # Authenticates the current scope and gets the current resource from the session. def authenticate_scope! send(:"authenticate_#{resource_name}!", force: true) self.resource = send(:"current_#{resource_name}") end def sign_up_params devise_parameter_sanitizer.sanitize(:sign_up) end def account_update_params devise_parameter_sanitizer.sanitize(:account_update) end def translation_scope 'devise.registrations' end private def set_flash_message_for_update(resource, prev_unconfirmed_email) return unless is_flashing_format? flash_key = if update_needs_confirmation?(resource, prev_unconfirmed_email) :update_needs_confirmation elsif sign_in_after_change_password? :updated else :updated_but_not_signed_in end set_flash_message :notice, flash_key end def sign_in_after_change_password? return true if account_update_params[:password].blank? Devise.sign_in_after_change_password end end
34.54491
102
0.705668
2601d8802c085e1e676acfd79f5bd1b5c36fb690
897
# frozen_string_literal: true require 'spec_helper' RSpec.describe Keycloak do it 'has a version number' do expect(Keycloak::VERSION).not_to be nil end describe 'Module configuration' do describe '.installation_file=' do it 'should raise an error if given file does not exist' do expect{ Keycloak.installation_file = 'random/file.json' }.to raise_error(Keycloak::InstallationFileNotFound) end end describe '.installation_file' do it 'should return default installation file' do expect(Keycloak.installation_file).to eq(Keycloak::KEYCLOAK_JSON_FILE) end it 'should return custom installation file location if previously set' do Keycloak.installation_file = 'spec/fixtures/test_installation.json' expect(Keycloak.installation_file).to eq('spec/fixtures/test_installation.json') end end end end
30.931034
116
0.722408
626c43a6ac1fe48131bc0cdb41626afe2b015618
1,227
# Uncomment this if you reference any of your controllers in activate # require_dependency 'application' class <%= class_name %> < Spree::Extension version "1.0" description "Describe your extension here" url "http://yourwebsite.com/<%= file_name %>" # Please use <%= file_name %>/config/routes.rb instead for extension routes. # def self.require_gems(config) # config.gem "gemname-goes-here", :version => '1.2.3' # end def activate # Add your extension tab to the admin. # Requires that you have defined an admin controller: # app/controllers/admin/yourextension_controller # and that you mapped your admin in config/routes #Admin::BaseController.class_eval do # before_filter :add_yourextension_tab # # def add_yourextension_tab # # add_extension_admin_tab takes an array containing the same arguments expected # # by the tab helper method: # # [ :extension_name, { :label => "Your Extension", :route => "/some/non/standard/route" } ] # add_extension_admin_tab [ :yourextension ] # end #end # make your helper avaliable in all views # Spree::BaseController.class_eval do # helper YourHelper # end end end
31.461538
102
0.684597
268a3c5d4fd5f17bae03118c7e74a69de7d38abb
5,367
require "timeout" require "log4r" require_relative "helper" require_relative "shell" require_relative "command_filter" module VagrantPlugins module CommunicatorWinRM # Provides communication channel for Vagrant commands via WinRM. class Communicator < Vagrant.plugin("2", :communicator) def self.match?(machine) # This is useless, and will likely be removed in the future (this # whole method). true end def initialize(machine) @cmd_filter = CommandFilter.new() @logger = Log4r::Logger.new("vagrant::communication::winrm") @machine = machine @shell = nil @logger.info("Initializing WinRMCommunicator") end def ready? @logger.info("Checking whether WinRM is ready...") Timeout.timeout(@machine.config.winrm.timeout) do shell(true).powershell("hostname") end @logger.info("WinRM is ready!") return true rescue Vagrant::Errors::VagrantError => e # We catch a `VagrantError` which would signal that something went # wrong expectedly in the `connect`, which means we didn't connect. @logger.info("WinRM not up: #{e.inspect}") # We reset the shell to trigger calling of winrm_finder again. # This resolves a problem when using vSphere where the ssh_info was not refreshing # thus never getting the correct hostname. @shell = nil return false end def shell(reload=false) @shell = nil if reload @shell ||= create_shell end def execute(command, opts={}, &block) # If this is a *nix command with no Windows equivilant, don't run it command = @cmd_filter.filter(command) return 0 if command.empty? opts = { command: command, elevated: false, error_check: true, error_class: Errors::ExecutionError, error_key: :execution_error, good_exit: 0, shell: :powershell, }.merge(opts || {}) opts[:good_exit] = Array(opts[:good_exit]) if opts[:elevated] guest_script_path = create_elevated_shell_script(command) command = "powershell -executionpolicy bypass -file #{guest_script_path}" end output = shell.send(opts[:shell], command, &block) execution_output(output, opts) end alias_method :sudo, :execute def test(command, opts=nil) # If this is a *nix command with no Windows equivilant, assume failure command = @cmd_filter.filter(command) return false if command.empty? opts = { error_check: false }.merge(opts || {}) execute(command, opts) == 0 end def upload(from, to) @logger.info("Uploading: #{from} to #{to}") shell.upload(from, to) end def download(from, to) @logger.info("Downloading: #{from} to #{to}") shell.download(from, to) end protected # This creates anew WinRMShell based on the information we know # about this machine. def create_shell winrm_info = Helper.winrm_info(@machine) WinRMShell.new( winrm_info[:host], @machine.config.winrm.username, @machine.config.winrm.password, port: winrm_info[:port], timeout_in_seconds: @machine.config.winrm.timeout, max_tries: @machine.config.winrm.max_tries, ) end # Creates and uploads a PowerShell script which wraps the specified # command in a scheduled task. The scheduled task allows commands to # run on the guest as a true local admin without any of the restrictions # that WinRM puts in place. # # @return The path to elevated_shell.ps1 on the guest def create_elevated_shell_script(command) path = File.expand_path("../scripts/elevated_shell.ps1", __FILE__) script = Vagrant::Util::TemplateRenderer.render(path, options: { username: shell.username, password: shell.password, command: command, }) guest_script_path = "c:/tmp/vagrant-elevated-shell.ps1" file = Tempfile.new(["vagrant-elevated-shell", "ps1"]) begin file.write(script) file.fsync file.close upload(file.path, guest_script_path) ensure file.close file.unlink end guest_script_path end # Handles the raw WinRM shell result and converts it to a # standard Vagrant communicator result def execution_output(output, opts) if opts[:shell] == :wql return output elsif opts[:error_check] && \ !opts[:good_exit].include?(output[:exitcode]) raise_execution_error(output, opts) end output[:exitcode] end def raise_execution_error(output, opts) # The error classes expect the translation key to be _key, but that makes for an ugly # configuration parameter, so we set it here from `error_key` msg = "Command execution failed with an exit code of #{output[:exitcode]}" error_opts = opts.merge(_key: opts[:error_key], message: msg) raise opts[:error_class], error_opts end end #WinRM class end end
32.331325
93
0.617105
1a105eb3bacffdab1c16af6192803419f46a6481
3,899
require "os/mac/architecture_list" module CctoolsMachO # @private OTOOL_RX = /\t(.*) \(compatibility version (?:\d+\.)*\d+, current version (?:\d+\.)*\d+\)/ # Mach-O binary methods, see: # /usr/include/mach-o/loader.h # /usr/include/mach-o/fat.h # @private def mach_data @mach_data ||= begin offsets = [] mach_data = [] header = read(8).unpack("N2") case header[0] when 0xcafebabe # universal header[1].times do |i| # header[1] is the number of struct fat_arch in the file. # Each struct fat_arch is 20 bytes, and the 'offset' member # begins 8 bytes into the struct, with an additional 8 byte # offset due to the struct fat_header at the beginning of # the file. offsets << read(4, 20*i + 16).unpack("N")[0] end when 0xcefaedfe, 0xcffaedfe, 0xfeedface, 0xfeedfacf # Single arch offsets << 0 when 0x7f454c46 # ELF arch = case read(2, 18).unpack("v")[0] when 3 then :i386 when 62 then :x86_64 else :dunno end type = case read(2, 16).unpack("v")[0] when 2 then :executable when 3 then :dylib else :dunno end return [{ :arch => arch, :type => type }] else raise "Not a Mach-O binary." end offsets.each do |offset| arch = case read(8, offset).unpack("N2") when [0xcefaedfe, 0x07000000] then :i386 when [0xcffaedfe, 0x07000001] then :x86_64 when [0xfeedface, 0x00000012] then :ppc7400 when [0xfeedfacf, 0x01000012] then :ppc64 else :dunno end type = case read(4, offset + 12).unpack("N")[0] when 0x00000002, 0x02000000 then :executable when 0x00000006, 0x06000000 then :dylib when 0x00000008, 0x08000000 then :bundle else :dunno end mach_data << { :arch => arch, :type => type } end mach_data rescue [] end end def archs mach_data.map { |m| m.fetch :arch }.extend(ArchitectureListExtension) end def arch case archs.length when 0 then :dunno when 1 then archs.first else :universal end end def universal? arch == :universal end def i386? arch == :i386 end def x86_64? arch == :x86_64 end def ppc7400? arch == :ppc7400 end def ppc64? arch == :ppc64 end # @private def dylib? mach_data.any? { |m| m.fetch(:type) == :dylib } end # @private def mach_o_executable? mach_data.any? { |m| m.fetch(:type) == :executable } end # @private def mach_o_bundle? mach_data.any? { |m| m.fetch(:type) == :bundle } end # @private class Metadata attr_reader :path, :dylib_id, :dylibs def initialize(path) @path = path @dylib_id, @dylibs = parse_otool_L_output end def parse_otool_L_output return nil, [] unless OS.mac? args = ["-L", path.expand_path.to_s] libs = Utils.popen_read(OS::Mac.otool, *args).split("\n") unless $?.success? raise ErrorDuringExecution.new(OS::Mac.otool, args) end libs.shift # first line is the filename id = libs.shift[OTOOL_RX, 1] if path.dylib? libs.map! { |lib| lib[OTOOL_RX, 1] }.compact! return id, libs end end # @private def mach_metadata @mach_metadata ||= Metadata.new(self) end # Returns an array containing all dynamically-linked libraries, based on the # output of otool. This returns the install names, so these are not guaranteed # to be absolute paths. # Returns an empty array both for software that links against no libraries, # and for non-mach objects. # @private def dynamically_linked_libraries mach_metadata.dylibs end # @private def dylib_id mach_metadata.dylib_id end end
24.067901
92
0.595794
086c66ccc6c00e2b8599398421f8f4e64d91b1bb
2,351
module Jekyll module SidebarItemFilter def docs_sidebar_link(item) return sidebar_helper(item, 'docs') end def ios_sidebar_link(item) return sidebar_helper(item, 'ios') end def android_sidebar_link(item) return sidebar_helper(item, 'android') end def unity_sidebar_link(item) return sidebar_helper(item, 'unity') end def windows_sidebar_link(item) return sidebar_helper(item, 'windows') end def guides_sidebar_link(item) return sidebar_helper(item, 'guides') end def mobile_usecases_sidebar_link(item) return sidebar_helper(item, 'mobile-usecases') end def panel_sidebar_link(item) return sidebar_helper(item, 'panel') end def javascript_sidebar_link(item) return sidebar_helper(item, 'javascript') end def react_native_sidebar_link(item) return sidebar_helper(item, 'react-native') end def react_native_bridge_sidebar_link(item) return sidebar_helper(item, 'react-native-bridge') end def rest_api_sidebar_link(item) return sidebar_helper(item, 'rest-api') end def sidebar_helper(item, group) forceInternal = item["forceInternal"] subItems = item["subitems"] pageID = @context.registers[:page]["id"] itemID = item["id"] if item["href"] != nil href = "#{pageID}.html##{item["href"]}" || "/#{group}/#{itemID}.html" itemID = pageID else href = item["href"] || "/#{group}/#{itemID}.html" end classes = [] if pageID == itemID classes.push("active") end if item["href"] && (forceInternal == nil) classes.push("external") end className = classes.size > 0 ? " class=\"#{classes.join(' ')}\"" : "" result = "" if subItems != nil && pageID == itemID result = "<ul><a href=\"#{href}\"#{className}>#{item["title"]}</a>" subItems.each {|curItem| result += "<li><a style='font-size: 12px;' href=\"#{pageID}.html##{curItem["href"]}\">#{curItem["title"]}</a></li>" } result += "</ul>" else result = "<a href=\"#{href}\"#{className}>#{item["title"]}</a>" end return result end end end Liquid::Template.register_filter(Jekyll::SidebarItemFilter)
26.41573
125
0.598894
1dc3ed12a7751850687d06d0e28129745dbc94c5
6,503
module Pod class Command class Spec < Command class Lint < Spec self.summary = 'Validates a spec file' self.description = <<-DESC Validates `NAME.podspec`. If a `DIRECTORY` is provided, it validates the podspec files found, including subfolders. In case the argument is omitted, it defaults to the current working dir. DESC self.arguments = [ CLAide::Argument.new(%w(NAME.podspec DIRECTORY http://PATH/NAME.podspec), false, true), ] def self.options [ ['--quick', 'Lint skips checks that would require to download and build the spec'], ['--allow-warnings', 'Lint validates even if warnings are present'], ['--subspec=NAME', 'Lint validates only the given subspec'], ['--no-subspecs', 'Lint skips validation of subspecs'], ['--no-clean', 'Lint leaves the build directory intact for inspection'], ['--fail-fast', 'Lint stops on the first failing platform or subspec'], ['--use-libraries', 'Lint uses static libraries to install the spec'], ['--use-modular-headers', 'Lint uses modular headers during installation'], ['--sources=https://github.com/artsy/Specs,master', 'The sources from which to pull dependent pods ' \ '(defaults to https://github.com/CocoaPods/Specs.git). ' \ 'Multiple sources must be comma-delimited.'], ['--platforms=ios,macos', 'Lint against specific platforms' \ '(defaults to all platforms supported by the podspec).' \ 'Multiple platforms must be comma-delimited'], ['--private', 'Lint skips checks that apply only to public specs'], ['--swift-version=VERSION', 'The SWIFT_VERSION that should be used to lint the spec. ' \ 'This takes precedence over the Swift versions specified by the spec or a `.swift-version` file.'], ['--skip-import-validation', 'Lint skips validating that the pod can be imported'], ['--skip-tests', 'Lint skips building and running tests during validation'], ].concat(super) end def initialize(argv) @quick = argv.flag?('quick') @allow_warnings = argv.flag?('allow-warnings') @clean = argv.flag?('clean', true) @fail_fast = argv.flag?('fail-fast', false) @subspecs = argv.flag?('subspecs', true) @only_subspec = argv.option('subspec') @use_frameworks = !argv.flag?('use-libraries') @use_modular_headers = argv.flag?('use-modular-headers') @source_urls = argv.option('sources', 'https://github.com/CocoaPods/Specs.git').split(',') @platforms = argv.option('platforms', '').split(',') @private = argv.flag?('private', false) @swift_version = argv.option('swift-version', nil) @skip_import_validation = argv.flag?('skip-import-validation', false) @skip_tests = argv.flag?('skip-tests', false) @podspecs_paths = argv.arguments! super end def run UI.puts failure_reasons = [] podspecs_to_lint.each do |podspec| validator = Validator.new(podspec, @source_urls, @platforms) validator.quick = @quick validator.no_clean = !@clean validator.fail_fast = @fail_fast validator.allow_warnings = @allow_warnings validator.no_subspecs = !@subspecs || @only_subspec validator.only_subspec = @only_subspec validator.use_frameworks = @use_frameworks validator.use_modular_headers = @use_modular_headers validator.ignore_public_only_results = @private validator.swift_version = @swift_version validator.skip_import_validation = @skip_import_validation validator.skip_tests = @skip_tests validator.validate failure_reasons << validator.failure_reason unless @clean UI.puts "Pods workspace available at `#{validator.validation_dir}/App.xcworkspace` for inspection." UI.puts end end count = podspecs_to_lint.count UI.puts "Analyzed #{count} #{'podspec'.pluralize(count)}.\n\n" failure_reasons.compact! if failure_reasons.empty? lint_passed_message = count == 1 ? "#{podspecs_to_lint.first.basename} passed validation." : 'All the specs passed validation.' UI.puts lint_passed_message.green << "\n\n" else raise Informative, if count == 1 "The spec did not pass validation, due to #{failure_reasons.first}." else "#{failure_reasons.count} out of #{count} specs failed validation." end end podspecs_tmp_dir.rmtree if podspecs_tmp_dir.exist? end private def podspecs_to_lint @podspecs_to_lint ||= begin files = [] @podspecs_paths << '.' if @podspecs_paths.empty? @podspecs_paths.each do |path| if path =~ %r{https?://} require 'cocoapods/open-uri' output_path = podspecs_tmp_dir + File.basename(path) output_path.dirname.mkpath begin open(path) do |io| output_path.open('w') { |f| f << io.read } end rescue => e raise Informative, "Downloading a podspec from `#{path}` failed: #{e}" end files << output_path elsif (pathname = Pathname.new(path)).directory? files += Pathname.glob(pathname + '*.podspec{.json,}') raise Informative, 'No specs found in the current directory.' if files.empty? else files << (pathname = Pathname.new(path)) raise Informative, "Unable to find a spec named `#{path}'." unless pathname.exist? && path.include?('.podspec') end end files end end def podspecs_tmp_dir Pathname.new(Dir.tmpdir) + 'CocoaPods/Lint_podspec' end end end end end
46.120567
139
0.564509
bf2d52e11803792b6420577f1d2ed2865b435ccd
589
require 'spec_helper' require 'ddtrace/opentracer' RSpec.describe Datadog::OpenTracer::ScopeManager do subject(:scope_manager) { described_class.new } describe '#activate' do subject(:activate) { scope_manager.activate(span, finish_on_close: finish_on_close) } let(:span) { instance_double(Datadog::OpenTracer::Span) } let(:finish_on_close) { true } it { is_expected.to be(OpenTracing::Scope::NOOP_INSTANCE) } end describe '#activate' do subject(:active) { scope_manager.active } it { is_expected.to be(OpenTracing::Scope::NOOP_INSTANCE) } end end
25.608696
89
0.726655
38da49eb7fca59e1f6098a166d09d2ae143d3de1
1,012
# == Schema Information # # Table name: shipping_addresses # # id :integer not null, primary key # transaction_id :integer not null # status :string(255) # name :string(255) # phone :string(255) # postal_code :string(255) # city :string(255) # country :string(255) # state_or_province :string(255) # street1 :string(255) # street2 :string(255) # created_at :datetime not null # updated_at :datetime not null # country_code :string(8) # class ShippingAddress < ActiveRecord::Base attr_accessible( :transaction_id, :status, :name, :phone, :postal_code, :city, :country, :country_code, :state_or_province, :street1, :street2 ) validates_presence_of :name, :city, :street1, :postal_code, :state_or_province, :phone belongs_to :tx, class_name: "Transaction", foreign_key: "transaction_id" end
25.948718
88
0.583992
217b028545dbe16ccd79198babdf14eebe732074
81,719
# 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/master/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE module Aws::EC2 class Vpc extend Aws::Deprecations # @overload def initialize(id, options = {}) # @param [String] id # @option options [Client] :client # @overload def initialize(options = {}) # @option options [required, String] :id # @option options [Client] :client def initialize(*args) options = Hash === args.last ? args.pop.dup : {} @id = extract_id(args, options) @data = options.delete(:data) @client = options.delete(:client) || Client.new(options) @waiter_block_warned = false end # @!group Read-Only Attributes # @return [String] def id @id end alias :vpc_id :id # The primary IPv4 CIDR block for the VPC. # @return [String] def cidr_block data[:cidr_block] end # The ID of the set of DHCP options you've associated with the VPC (or # `default` if the default options are associated with the VPC). # @return [String] def dhcp_options_id data[:dhcp_options_id] end # The current state of the VPC. # @return [String] def state data[:state] end # The ID of the AWS account that owns the VPC. # @return [String] def owner_id data[:owner_id] end # The allowed tenancy of instances launched into the VPC. # @return [String] def instance_tenancy data[:instance_tenancy] end # Information about the IPv6 CIDR blocks associated with the VPC. # @return [Array<Types::VpcIpv6CidrBlockAssociation>] def ipv_6_cidr_block_association_set data[:ipv_6_cidr_block_association_set] end # Information about the IPv4 CIDR blocks associated with the VPC. # @return [Array<Types::VpcCidrBlockAssociation>] def cidr_block_association_set data[:cidr_block_association_set] end # Indicates whether the VPC is the default VPC. # @return [Boolean] def is_default data[:is_default] end # Any tags assigned to the VPC. # @return [Array<Types::Tag>] def tags data[:tags] end # @!endgroup # @return [Client] def client @client end # Loads, or reloads {#data} for the current {Vpc}. # Returns `self` making it possible to chain methods. # # vpc.reload.data # # @return [self] def load resp = @client.describe_vpcs(vpc_ids: [@id]) @data = resp.vpcs[0] self end alias :reload :load # @return [Types::Vpc] # Returns the data for this {Vpc}. Calls # {Client#describe_vpcs} if {#data_loaded?} is `false`. def data load unless @data @data end # @return [Boolean] # Returns `true` if this resource is loaded. Accessing attributes or # {#data} on an unloaded resource will trigger a call to {#load}. def data_loaded? !!@data end # @param [Hash] options ({}) # @return [Boolean] # Returns `true` if the Vpc exists. def exists?(options = {}) begin wait_until_exists(options.merge(max_attempts: 1)) true rescue Aws::Waiters::Errors::UnexpectedError => e raise e.error rescue Aws::Waiters::Errors::WaiterFailed false end end # @param [Hash] options ({}) # @option options [Integer] :max_attempts (40) # @option options [Float] :delay (15) # @option options [Proc] :before_attempt # @option options [Proc] :before_wait # @return [Vpc] def wait_until_available(options = {}, &block) options, params = separate_params_and_options(options) waiter = Waiters::VpcAvailable.new(options) yield_waiter_and_warn(waiter, &block) if block_given? waiter.wait(params.merge(vpc_ids: [@id])) Vpc.new({ id: @id, client: @client }) end # @param [Hash] options ({}) # @option options [Integer] :max_attempts (5) # @option options [Float] :delay (1) # @option options [Proc] :before_attempt # @option options [Proc] :before_wait # @return [Vpc] def wait_until_exists(options = {}, &block) options, params = separate_params_and_options(options) waiter = Waiters::VpcExists.new(options) yield_waiter_and_warn(waiter, &block) if block_given? waiter.wait(params.merge(vpc_ids: [@id])) Vpc.new({ id: @id, client: @client }) end # @deprecated Use [Aws::EC2::Client] #wait_until instead # # Waiter polls an API operation until a resource enters a desired # state. # # @note The waiting operation is performed on a copy. The original resource # remains unchanged. # # ## Basic Usage # # Waiter will polls until it is successful, it fails by # entering a terminal state, or until a maximum number of attempts # are made. # # # polls in a loop until condition is true # resource.wait_until(options) {|resource| condition} # # ## Example # # instance.wait_until(max_attempts:10, delay:5) do |instance| # instance.state.name == 'running' # end # # ## Configuration # # You can configure the maximum number of polling attempts, and the # delay (in seconds) between each polling attempt. The waiting condition is # set by passing a block to {#wait_until}: # # # poll for ~25 seconds # resource.wait_until(max_attempts:5,delay:5) {|resource|...} # # ## Callbacks # # You can be notified before each polling attempt and before each # delay. If you throw `:success` or `:failure` from these callbacks, # it will terminate the waiter. # # started_at = Time.now # # poll for 1 hour, instead of a number of attempts # proc = Proc.new do |attempts, response| # throw :failure if Time.now - started_at > 3600 # end # # # disable max attempts # instance.wait_until(before_wait:proc, max_attempts:nil) {...} # # ## Handling Errors # # When a waiter is successful, it returns the Resource. When a waiter # fails, it raises an error. # # begin # resource.wait_until(...) # rescue Aws::Waiters::Errors::WaiterFailed # # resource did not enter the desired state in time # end # # @yieldparam [Resource] resource to be used in the waiting condition. # # @raise [Aws::Waiters::Errors::FailureStateError] Raised when the waiter # terminates because the waiter has entered a state that it will not # transition out of, preventing success. # # yet successful. # # @raise [Aws::Waiters::Errors::UnexpectedError] Raised when an error is # encountered while polling for a resource that is not expected. # # @raise [NotImplementedError] Raised when the resource does not # # @option options [Integer] :max_attempts (10) Maximum number of # attempts # @option options [Integer] :delay (10) Delay between each # attempt in seconds # @option options [Proc] :before_attempt (nil) Callback # invoked before each attempt # @option options [Proc] :before_wait (nil) Callback # invoked before each wait # @return [Resource] if the waiter was successful def wait_until(options = {}, &block) self_copy = self.dup attempts = 0 options[:max_attempts] = 10 unless options.key?(:max_attempts) options[:delay] ||= 10 options[:poller] = Proc.new do attempts += 1 if block.call(self_copy) [:success, self_copy] else self_copy.reload unless attempts == options[:max_attempts] :retry end end Aws::Waiters::Waiter.new(options).wait({}) end # @!group Actions # @example Request syntax with placeholder values # # vpc.associate_dhcp_options({ # dhcp_options_id: "DefaultingDhcpOptionsId", # required # dry_run: false, # }) # @param [Hash] options ({}) # @option options [required, String] :dhcp_options_id # The ID of the DHCP options set, or `default` to associate no DHCP # options with the VPC. # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @return [EmptyStructure] def associate_dhcp_options(options = {}) options = options.merge(vpc_id: @id) resp = @client.associate_dhcp_options(options) resp.data end # @example Request syntax with placeholder values # # vpc.attach_classic_link_instance({ # dry_run: false, # groups: ["String"], # required # instance_id: "InstanceId", # required # }) # @param [Hash] options ({}) # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @option options [required, Array<String>] :groups # The ID of one or more of the VPC's security groups. You cannot # specify security groups from a different VPC. # @option options [required, String] :instance_id # The ID of an EC2-Classic instance to link to the ClassicLink-enabled # VPC. # @return [Types::AttachClassicLinkVpcResult] def attach_classic_link_instance(options = {}) options = options.merge(vpc_id: @id) resp = @client.attach_classic_link_vpc(options) resp.data end # @example Request syntax with placeholder values # # vpc.attach_internet_gateway({ # dry_run: false, # internet_gateway_id: "InternetGatewayId", # required # }) # @param [Hash] options ({}) # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @option options [required, String] :internet_gateway_id # The ID of the internet gateway. # @return [EmptyStructure] def attach_internet_gateway(options = {}) options = options.merge(vpc_id: @id) resp = @client.attach_internet_gateway(options) resp.data end # @example Request syntax with placeholder values # # networkacl = vpc.create_network_acl({ # dry_run: false, # tag_specifications: [ # { # resource_type: "client-vpn-endpoint", # accepts client-vpn-endpoint, customer-gateway, dedicated-host, dhcp-options, elastic-ip, elastic-gpu, export-image-task, export-instance-task, fleet, fpga-image, host-reservation, image, import-image-task, import-snapshot-task, instance, internet-gateway, key-pair, launch-template, local-gateway-route-table-vpc-association, natgateway, network-acl, network-interface, placement-group, reserved-instances, route-table, security-group, snapshot, spot-fleet-request, spot-instances-request, subnet, traffic-mirror-filter, traffic-mirror-session, traffic-mirror-target, transit-gateway, transit-gateway-attachment, transit-gateway-multicast-domain, transit-gateway-route-table, volume, vpc, vpc-peering-connection, vpn-connection, vpn-gateway, vpc-flow-log # tags: [ # { # key: "String", # value: "String", # }, # ], # }, # ], # }) # @param [Hash] options ({}) # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @option options [Array<Types::TagSpecification>] :tag_specifications # The tags to assign to the network ACL. # @return [NetworkAcl] def create_network_acl(options = {}) options = options.merge(vpc_id: @id) resp = @client.create_network_acl(options) NetworkAcl.new( id: resp.data.network_acl.network_acl_id, data: resp.data.network_acl, client: @client ) end # @example Request syntax with placeholder values # # routetable = vpc.create_route_table({ # dry_run: false, # tag_specifications: [ # { # resource_type: "client-vpn-endpoint", # accepts client-vpn-endpoint, customer-gateway, dedicated-host, dhcp-options, elastic-ip, elastic-gpu, export-image-task, export-instance-task, fleet, fpga-image, host-reservation, image, import-image-task, import-snapshot-task, instance, internet-gateway, key-pair, launch-template, local-gateway-route-table-vpc-association, natgateway, network-acl, network-interface, placement-group, reserved-instances, route-table, security-group, snapshot, spot-fleet-request, spot-instances-request, subnet, traffic-mirror-filter, traffic-mirror-session, traffic-mirror-target, transit-gateway, transit-gateway-attachment, transit-gateway-multicast-domain, transit-gateway-route-table, volume, vpc, vpc-peering-connection, vpn-connection, vpn-gateway, vpc-flow-log # tags: [ # { # key: "String", # value: "String", # }, # ], # }, # ], # }) # @param [Hash] options ({}) # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @option options [Array<Types::TagSpecification>] :tag_specifications # The tags to assign to the route table. # @return [RouteTable] def create_route_table(options = {}) options = options.merge(vpc_id: @id) resp = @client.create_route_table(options) RouteTable.new( id: resp.data.route_table.route_table_id, data: resp.data.route_table, client: @client ) end # @example Request syntax with placeholder values # # securitygroup = vpc.create_security_group({ # description: "String", # required # group_name: "String", # required # tag_specifications: [ # { # resource_type: "client-vpn-endpoint", # accepts client-vpn-endpoint, customer-gateway, dedicated-host, dhcp-options, elastic-ip, elastic-gpu, export-image-task, export-instance-task, fleet, fpga-image, host-reservation, image, import-image-task, import-snapshot-task, instance, internet-gateway, key-pair, launch-template, local-gateway-route-table-vpc-association, natgateway, network-acl, network-interface, placement-group, reserved-instances, route-table, security-group, snapshot, spot-fleet-request, spot-instances-request, subnet, traffic-mirror-filter, traffic-mirror-session, traffic-mirror-target, transit-gateway, transit-gateway-attachment, transit-gateway-multicast-domain, transit-gateway-route-table, volume, vpc, vpc-peering-connection, vpn-connection, vpn-gateway, vpc-flow-log # tags: [ # { # key: "String", # value: "String", # }, # ], # }, # ], # dry_run: false, # }) # @param [Hash] options ({}) # @option options [required, String] :description # A description for the security group. This is informational only. # # Constraints: Up to 255 characters in length # # Constraints for EC2-Classic: ASCII characters # # Constraints for EC2-VPC: a-z, A-Z, 0-9, spaces, and # .\_-:/()#,@\[\]+=&amp;;\\\{\\}!$* # @option options [required, String] :group_name # The name of the security group. # # Constraints: Up to 255 characters in length. Cannot start with `sg-`. # # Constraints for EC2-Classic: ASCII characters # # Constraints for EC2-VPC: a-z, A-Z, 0-9, spaces, and # .\_-:/()#,@\[\]+=&amp;;\\\{\\}!$* # @option options [Array<Types::TagSpecification>] :tag_specifications # The tags to assign to the security group. # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @return [SecurityGroup] def create_security_group(options = {}) options = options.merge(vpc_id: @id) resp = @client.create_security_group(options) SecurityGroup.new( id: resp.data.group_id, client: @client ) end # @example Request syntax with placeholder values # # subnet = vpc.create_subnet({ # tag_specifications: [ # { # resource_type: "client-vpn-endpoint", # accepts client-vpn-endpoint, customer-gateway, dedicated-host, dhcp-options, elastic-ip, elastic-gpu, export-image-task, export-instance-task, fleet, fpga-image, host-reservation, image, import-image-task, import-snapshot-task, instance, internet-gateway, key-pair, launch-template, local-gateway-route-table-vpc-association, natgateway, network-acl, network-interface, placement-group, reserved-instances, route-table, security-group, snapshot, spot-fleet-request, spot-instances-request, subnet, traffic-mirror-filter, traffic-mirror-session, traffic-mirror-target, transit-gateway, transit-gateway-attachment, transit-gateway-multicast-domain, transit-gateway-route-table, volume, vpc, vpc-peering-connection, vpn-connection, vpn-gateway, vpc-flow-log # tags: [ # { # key: "String", # value: "String", # }, # ], # }, # ], # availability_zone: "String", # availability_zone_id: "String", # cidr_block: "String", # required # ipv_6_cidr_block: "String", # outpost_arn: "String", # dry_run: false, # }) # @param [Hash] options ({}) # @option options [Array<Types::TagSpecification>] :tag_specifications # The tags to assign to the subnet. # @option options [String] :availability_zone # The Availability Zone or Local Zone for the subnet. # # Default: AWS selects one for you. If you create more than one subnet # in your VPC, we do not necessarily select a different zone for each # subnet. # # To create a subnet in a Local Zone, set this value to the Local Zone # ID, for example `us-west-2-lax-1a`. For information about the Regions # that support Local Zones, see [Available Regions][1] in the *Amazon # Elastic Compute Cloud User Guide*. # # To create a subnet in an Outpost, set this value to the Availability # Zone for the Outpost and specify the Outpost ARN. # # # # [1]: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-regions # @option options [String] :availability_zone_id # The AZ ID or the Local Zone ID of the subnet. # @option options [required, String] :cidr_block # The IPv4 network range for the subnet, in CIDR notation. For example, # `10.0.0.0/24`. We modify the specified CIDR block to its canonical # form; for example, if you specify `100.68.0.18/18`, we modify it to # `100.68.0.0/18`. # @option options [String] :ipv_6_cidr_block # The IPv6 network range for the subnet, in CIDR notation. The subnet # size must use a /64 prefix length. # @option options [String] :outpost_arn # The Amazon Resource Name (ARN) of the Outpost. If you specify an # Outpost ARN, you must also specify the Availability Zone of the # Outpost subnet. # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @return [Subnet] def create_subnet(options = {}) options = options.merge(vpc_id: @id) resp = @client.create_subnet(options) Subnet.new( id: resp.data.subnet.subnet_id, data: resp.data.subnet, client: @client ) end # @example Request syntax with placeholder values # # tag = vpc.create_tags({ # dry_run: false, # tags: [ # required # { # key: "String", # value: "String", # }, # ], # }) # @param [Hash] options ({}) # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @option options [required, Array<Types::Tag>] :tags # The tags. The `value` parameter is required, but if you don't want # the tag to have a value, specify the parameter with no value, and we # set the value to an empty string. # @return [Tag::Collection] def create_tags(options = {}) batch = [] options = Aws::Util.deep_merge(options, resources: [@id]) resp = @client.create_tags(options) options[:tags].each do |t| batch << Tag.new( resource_id: @id, key: t[:key], value: t[:value], client: @client ) end Tag::Collection.new([batch], size: batch.size) end # @example Request syntax with placeholder values # # tag = vpc.delete_tags({ # dry_run: false, # tags: [ # { # key: "String", # value: "String", # }, # ], # }) # @param [Hash] options ({}) # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @option options [Array<Types::Tag>] :tags # The tags to delete. Specify a tag key and an optional tag value to # delete specific tags. If you specify a tag key without a tag value, we # delete any tag with this key regardless of its value. If you specify a # tag key with an empty string as the tag value, we delete the tag only # if its value is an empty string. # # If you omit this parameter, we delete all user-defined tags for the # specified resources. We do not delete AWS-generated tags (tags that # have the `aws:` prefix). # @return [Tag::Collection] def delete_tags(options = {}) batch = [] options = Aws::Util.deep_merge(options, resources: [@id]) resp = @client.delete_tags(options) options[:tags].each do |t| batch << Tag.new( resource_id: @id, key: t[:key], value: t[:value], client: @client ) end Tag::Collection.new([batch], size: batch.size) end # @example Request syntax with placeholder values # # vpc.delete({ # dry_run: false, # }) # @param [Hash] options ({}) # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @return [EmptyStructure] def delete(options = {}) options = options.merge(vpc_id: @id) resp = @client.delete_vpc(options) resp.data end # @example Request syntax with placeholder values # # vpc.describe_attribute({ # attribute: "enableDnsSupport", # required, accepts enableDnsSupport, enableDnsHostnames # dry_run: false, # }) # @param [Hash] options ({}) # @option options [required, String] :attribute # The VPC attribute. # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @return [Types::DescribeVpcAttributeResult] def describe_attribute(options = {}) options = options.merge(vpc_id: @id) resp = @client.describe_vpc_attribute(options) resp.data end # @example Request syntax with placeholder values # # vpc.detach_classic_link_instance({ # dry_run: false, # instance_id: "InstanceId", # required # }) # @param [Hash] options ({}) # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @option options [required, String] :instance_id # The ID of the instance to unlink from the VPC. # @return [Types::DetachClassicLinkVpcResult] def detach_classic_link_instance(options = {}) options = options.merge(vpc_id: @id) resp = @client.detach_classic_link_vpc(options) resp.data end # @example Request syntax with placeholder values # # vpc.detach_internet_gateway({ # dry_run: false, # internet_gateway_id: "InternetGatewayId", # required # }) # @param [Hash] options ({}) # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @option options [required, String] :internet_gateway_id # The ID of the internet gateway. # @return [EmptyStructure] def detach_internet_gateway(options = {}) options = options.merge(vpc_id: @id) resp = @client.detach_internet_gateway(options) resp.data end # @example Request syntax with placeholder values # # vpc.disable_classic_link({ # dry_run: false, # }) # @param [Hash] options ({}) # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @return [Types::DisableVpcClassicLinkResult] def disable_classic_link(options = {}) options = options.merge(vpc_id: @id) resp = @client.disable_vpc_classic_link(options) resp.data end # @example Request syntax with placeholder values # # vpc.enable_classic_link({ # dry_run: false, # }) # @param [Hash] options ({}) # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @return [Types::EnableVpcClassicLinkResult] def enable_classic_link(options = {}) options = options.merge(vpc_id: @id) resp = @client.enable_vpc_classic_link(options) resp.data end # @example Request syntax with placeholder values # # vpc.modify_attribute({ # enable_dns_hostnames: { # value: false, # }, # enable_dns_support: { # value: false, # }, # }) # @param [Hash] options ({}) # @option options [Types::AttributeBooleanValue] :enable_dns_hostnames # Indicates whether the instances launched in the VPC get DNS hostnames. # If enabled, instances in the VPC get DNS hostnames; otherwise, they do # not. # # You cannot modify the DNS resolution and DNS hostnames attributes in # the same request. Use separate requests for each attribute. You can # only enable DNS hostnames if you've enabled DNS support. # @option options [Types::AttributeBooleanValue] :enable_dns_support # Indicates whether the DNS resolution is supported for the VPC. If # enabled, queries to the Amazon provided DNS server at the # 169.254.169.253 IP address, or the reserved IP address at the base of # the VPC network range "plus two" succeed. If disabled, the Amazon # provided DNS service in the VPC that resolves public DNS hostnames to # IP addresses is not enabled. # # You cannot modify the DNS resolution and DNS hostnames attributes in # the same request. Use separate requests for each attribute. # @return [EmptyStructure] def modify_attribute(options = {}) options = options.merge(vpc_id: @id) resp = @client.modify_vpc_attribute(options) resp.data end # @example Request syntax with placeholder values # # vpcpeeringconnection = vpc.request_vpc_peering_connection({ # dry_run: false, # peer_owner_id: "String", # peer_vpc_id: "String", # peer_region: "String", # tag_specifications: [ # { # resource_type: "client-vpn-endpoint", # accepts client-vpn-endpoint, customer-gateway, dedicated-host, dhcp-options, elastic-ip, elastic-gpu, export-image-task, export-instance-task, fleet, fpga-image, host-reservation, image, import-image-task, import-snapshot-task, instance, internet-gateway, key-pair, launch-template, local-gateway-route-table-vpc-association, natgateway, network-acl, network-interface, placement-group, reserved-instances, route-table, security-group, snapshot, spot-fleet-request, spot-instances-request, subnet, traffic-mirror-filter, traffic-mirror-session, traffic-mirror-target, transit-gateway, transit-gateway-attachment, transit-gateway-multicast-domain, transit-gateway-route-table, volume, vpc, vpc-peering-connection, vpn-connection, vpn-gateway, vpc-flow-log # tags: [ # { # key: "String", # value: "String", # }, # ], # }, # ], # }) # @param [Hash] options ({}) # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @option options [String] :peer_owner_id # The AWS account ID of the owner of the accepter VPC. # # Default: Your AWS account ID # @option options [String] :peer_vpc_id # The ID of the VPC with which you are creating the VPC peering # connection. You must specify this parameter in the request. # @option options [String] :peer_region # The Region code for the accepter VPC, if the accepter VPC is located # in a Region other than the Region in which you make the request. # # Default: The Region in which you make the request. # @option options [Array<Types::TagSpecification>] :tag_specifications # The tags to assign to the peering connection. # @return [VpcPeeringConnection] def request_vpc_peering_connection(options = {}) options = options.merge(vpc_id: @id) resp = @client.create_vpc_peering_connection(options) VpcPeeringConnection.new( id: resp.data.vpc_peering_connection.vpc_peering_connection_id, data: resp.data.vpc_peering_connection, client: @client ) end # @!group Associations # @example Request syntax with placeholder values # # accepted_vpc_peering_connections = vpc.accepted_vpc_peering_connections({ # filters: [ # { # name: "String", # values: ["String"], # }, # ], # dry_run: false, # vpc_peering_connection_ids: ["VpcPeeringConnectionId"], # }) # @param [Hash] options ({}) # @option options [Array<Types::Filter>] :filters # One or more filters. # # * `accepter-vpc-info.cidr-block` - The IPv4 CIDR block of the accepter # VPC. # # * `accepter-vpc-info.owner-id` - The AWS account ID of the owner of # the accepter VPC. # # * `accepter-vpc-info.vpc-id` - The ID of the accepter VPC. # # * `expiration-time` - The expiration date and time for the VPC peering # connection. # # * `requester-vpc-info.cidr-block` - The IPv4 CIDR block of the # requester's VPC. # # * `requester-vpc-info.owner-id` - The AWS account ID of the owner of # the requester VPC. # # * `requester-vpc-info.vpc-id` - The ID of the requester VPC. # # * `status-code` - The status of the VPC peering connection # (`pending-acceptance` \| `failed` \| `expired` \| `provisioning` \| # `active` \| `deleting` \| `deleted` \| `rejected`). # # * `status-message` - A message that provides more information about # the status of the VPC peering connection, if applicable. # # * `tag`\:&lt;key&gt; - The key/value combination of a tag assigned to # the resource. Use the tag key in the filter name and the tag value # as the filter value. For example, to find all resources that have a # tag with the key `Owner` and the value `TeamA`, specify `tag:Owner` # for the filter name and `TeamA` for the filter value. # # * `tag-key` - The key of a tag assigned to the resource. Use this # filter to find all resources assigned a tag with a specific key, # regardless of the tag value. # # * `vpc-peering-connection-id` - The ID of the VPC peering connection. # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @option options [Array<String>] :vpc_peering_connection_ids # One or more VPC peering connection IDs. # # Default: Describes all your VPC peering connections. # @return [VpcPeeringConnection::Collection] def accepted_vpc_peering_connections(options = {}) batches = Enumerator.new do |y| options = Aws::Util.deep_merge(options, filters: [{ name: "accepter-vpc-info.vpc-id", values: [@id] }]) resp = @client.describe_vpc_peering_connections(options) resp.each_page do |page| batch = [] page.data.vpc_peering_connections.each do |v| batch << VpcPeeringConnection.new( id: v.vpc_peering_connection_id, data: v, client: @client ) end y.yield(batch) end end VpcPeeringConnection::Collection.new(batches) end # @return [DhcpOptions, nil] def dhcp_options if data[:dhcp_options_id] DhcpOptions.new( id: data[:dhcp_options_id], client: @client ) else nil end end # @example Request syntax with placeholder values # # instances = vpc.instances({ # filters: [ # { # name: "String", # values: ["String"], # }, # ], # instance_ids: ["InstanceId"], # dry_run: false, # }) # @param [Hash] options ({}) # @option options [Array<Types::Filter>] :filters # The filters. # # * `affinity` - The affinity setting for an instance running on a # Dedicated Host (`default` \| `host`). # # * `architecture` - The instance architecture (`i386` \| `x86_64` \| # `arm64`). # # * `availability-zone` - The Availability Zone of the instance. # # * `block-device-mapping.attach-time` - The attach time for an EBS # volume mapped to the instance, for example, # `2010-09-15T17:15:20.000Z`. # # * `block-device-mapping.delete-on-termination` - A Boolean that # indicates whether the EBS volume is deleted on instance termination. # # * `block-device-mapping.device-name` - The device name specified in # the block device mapping (for example, `/dev/sdh` or `xvdh`). # # * `block-device-mapping.status` - The status for the EBS volume # (`attaching` \| `attached` \| `detaching` \| `detached`). # # * `block-device-mapping.volume-id` - The volume ID of the EBS volume. # # * `client-token` - The idempotency token you provided when you # launched the instance. # # * `dns-name` - The public DNS name of the instance. # # * `group-id` - The ID of the security group for the instance. # EC2-Classic only. # # * `group-name` - The name of the security group for the instance. # EC2-Classic only. # # * `hibernation-options.configured` - A Boolean that indicates whether # the instance is enabled for hibernation. A value of `true` means # that the instance is enabled for hibernation. # # * `host-id` - The ID of the Dedicated Host on which the instance is # running, if applicable. # # * `hypervisor` - The hypervisor type of the instance (`ovm` \| `xen`). # The value `xen` is used for both Xen and Nitro hypervisors. # # * `iam-instance-profile.arn` - The instance profile associated with # the instance. Specified as an ARN. # # * `image-id` - The ID of the image used to launch the instance. # # * `instance-id` - The ID of the instance. # # * `instance-lifecycle` - Indicates whether this is a Spot Instance or # a Scheduled Instance (`spot` \| `scheduled`). # # * `instance-state-code` - The state of the instance, as a 16-bit # unsigned integer. The high byte is used for internal purposes and # should be ignored. The low byte is set based on the state # represented. The valid values are: 0 (pending), 16 (running), 32 # (shutting-down), 48 (terminated), 64 (stopping), and 80 (stopped). # # * `instance-state-name` - The state of the instance (`pending` \| # `running` \| `shutting-down` \| `terminated` \| `stopping` \| # `stopped`). # # * `instance-type` - The type of instance (for example, `t2.micro`). # # * `instance.group-id` - The ID of the security group for the instance. # # * `instance.group-name` - The name of the security group for the # instance. # # * `ip-address` - The public IPv4 address of the instance. # # * `kernel-id` - The kernel ID. # # * `key-name` - The name of the key pair used when the instance was # launched. # # * `launch-index` - When launching multiple instances, this is the # index for the instance in the launch group (for example, 0, 1, 2, # and so on). # # * `launch-time` - The time when the instance was launched. # # * `metadata-options.http-tokens` - The metadata request authorization # state (`optional` \| `required`) # # * `metadata-options.http-put-response-hop-limit` - The http metadata # request put response hop limit (integer, possible values `1` to # `64`) # # * `metadata-options.http-endpoint` - Enable or disable metadata access # on http endpoint (`enabled` \| `disabled`) # # * `monitoring-state` - Indicates whether detailed monitoring is # enabled (`disabled` \| `enabled`). # # * `network-interface.addresses.private-ip-address` - The private IPv4 # address associated with the network interface. # # * `network-interface.addresses.primary` - Specifies whether the IPv4 # address of the network interface is the primary private IPv4 # address. # # * `network-interface.addresses.association.public-ip` - The ID of the # association of an Elastic IP address (IPv4) with a network # interface. # # * `network-interface.addresses.association.ip-owner-id` - The owner ID # of the private IPv4 address associated with the network interface. # # * `network-interface.association.public-ip` - The address of the # Elastic IP address (IPv4) bound to the network interface. # # * `network-interface.association.ip-owner-id` - The owner of the # Elastic IP address (IPv4) associated with the network interface. # # * `network-interface.association.allocation-id` - The allocation ID # returned when you allocated the Elastic IP address (IPv4) for your # network interface. # # * `network-interface.association.association-id` - The association ID # returned when the network interface was associated with an IPv4 # address. # # * `network-interface.attachment.attachment-id` - The ID of the # interface attachment. # # * `network-interface.attachment.instance-id` - The ID of the instance # to which the network interface is attached. # # * `network-interface.attachment.instance-owner-id` - The owner ID of # the instance to which the network interface is attached. # # * `network-interface.attachment.device-index` - The device index to # which the network interface is attached. # # * `network-interface.attachment.status` - The status of the attachment # (`attaching` \| `attached` \| `detaching` \| `detached`). # # * `network-interface.attachment.attach-time` - The time that the # network interface was attached to an instance. # # * `network-interface.attachment.delete-on-termination` - Specifies # whether the attachment is deleted when an instance is terminated. # # * `network-interface.availability-zone` - The Availability Zone for # the network interface. # # * `network-interface.description` - The description of the network # interface. # # * `network-interface.group-id` - The ID of a security group associated # with the network interface. # # * `network-interface.group-name` - The name of a security group # associated with the network interface. # # * `network-interface.ipv6-addresses.ipv6-address` - The IPv6 address # associated with the network interface. # # * `network-interface.mac-address` - The MAC address of the network # interface. # # * `network-interface.network-interface-id` - The ID of the network # interface. # # * `network-interface.owner-id` - The ID of the owner of the network # interface. # # * `network-interface.private-dns-name` - The private DNS name of the # network interface. # # * `network-interface.requester-id` - The requester ID for the network # interface. # # * `network-interface.requester-managed` - Indicates whether the # network interface is being managed by AWS. # # * `network-interface.status` - The status of the network interface # (`available`) \| `in-use`). # # * `network-interface.source-dest-check` - Whether the network # interface performs source/destination checking. A value of `true` # means that checking is enabled, and `false` means that checking is # disabled. The value must be `false` for the network interface to # perform network address translation (NAT) in your VPC. # # * `network-interface.subnet-id` - The ID of the subnet for the network # interface. # # * `network-interface.vpc-id` - The ID of the VPC for the network # interface. # # * `owner-id` - The AWS account ID of the instance owner. # # * `placement-group-name` - The name of the placement group for the # instance. # # * `placement-partition-number` - The partition in which the instance # is located. # # * `platform` - The platform. To list only Windows instances, use # `windows`. # # * `private-dns-name` - The private IPv4 DNS name of the instance. # # * `private-ip-address` - The private IPv4 address of the instance. # # * `product-code` - The product code associated with the AMI used to # launch the instance. # # * `product-code.type` - The type of product code (`devpay` \| # `marketplace`). # # * `ramdisk-id` - The RAM disk ID. # # * `reason` - The reason for the current state of the instance (for # example, shows "User Initiated \[date\]" when you stop or # terminate the instance). Similar to the state-reason-code filter. # # * `requester-id` - The ID of the entity that launched the instance on # your behalf (for example, AWS Management Console, Auto Scaling, and # so on). # # * `reservation-id` - The ID of the instance's reservation. A # reservation ID is created any time you launch an instance. A # reservation ID has a one-to-one relationship with an instance launch # request, but can be associated with more than one instance if you # launch multiple instances using the same launch request. For # example, if you launch one instance, you get one reservation ID. If # you launch ten instances using the same launch request, you also get # one reservation ID. # # * `root-device-name` - The device name of the root device volume (for # example, `/dev/sda1`). # # * `root-device-type` - The type of the root device volume (`ebs` \| # `instance-store`). # # * `source-dest-check` - Indicates whether the instance performs # source/destination checking. A value of `true` means that checking # is enabled, and `false` means that checking is disabled. The value # must be `false` for the instance to perform network address # translation (NAT) in your VPC. # # * `spot-instance-request-id` - The ID of the Spot Instance request. # # * `state-reason-code` - The reason code for the state change. # # * `state-reason-message` - A message that describes the state change. # # * `subnet-id` - The ID of the subnet for the instance. # # * `tag`\:&lt;key&gt; - The key/value combination of a tag assigned to # the resource. Use the tag key in the filter name and the tag value # as the filter value. For example, to find all resources that have a # tag with the key `Owner` and the value `TeamA`, specify `tag:Owner` # for the filter name and `TeamA` for the filter value. # # * `tag-key` - The key of a tag assigned to the resource. Use this # filter to find all resources that have a tag with a specific key, # regardless of the tag value. # # * `tenancy` - The tenancy of an instance (`dedicated` \| `default` \| # `host`). # # * `virtualization-type` - The virtualization type of the instance # (`paravirtual` \| `hvm`). # # * `vpc-id` - The ID of the VPC that the instance is running in. # @option options [Array<String>] :instance_ids # The instance IDs. # # Default: Describes all your instances. # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @return [Instance::Collection] def instances(options = {}) batches = Enumerator.new do |y| options = Aws::Util.deep_merge(options, filters: [{ name: "vpc-id", values: [@id] }]) resp = @client.describe_instances(options) resp.each_page do |page| batch = [] page.data.reservations.each do |r| r.instances.each do |i| batch << Instance.new( id: i.instance_id, data: i, client: @client ) end end y.yield(batch) end end Instance::Collection.new(batches) end # @example Request syntax with placeholder values # # internet_gateways = vpc.internet_gateways({ # filters: [ # { # name: "String", # values: ["String"], # }, # ], # dry_run: false, # internet_gateway_ids: ["InternetGatewayId"], # }) # @param [Hash] options ({}) # @option options [Array<Types::Filter>] :filters # One or more filters. # # * `attachment.state` - The current state of the attachment between the # gateway and the VPC (`available`). Present only if a VPC is # attached. # # * `attachment.vpc-id` - The ID of an attached VPC. # # * `internet-gateway-id` - The ID of the Internet gateway. # # * `owner-id` - The ID of the AWS account that owns the internet # gateway. # # * `tag`\:&lt;key&gt; - The key/value combination of a tag assigned to # the resource. Use the tag key in the filter name and the tag value # as the filter value. For example, to find all resources that have a # tag with the key `Owner` and the value `TeamA`, specify `tag:Owner` # for the filter name and `TeamA` for the filter value. # # * `tag-key` - The key of a tag assigned to the resource. Use this # filter to find all resources assigned a tag with a specific key, # regardless of the tag value. # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @option options [Array<String>] :internet_gateway_ids # One or more internet gateway IDs. # # Default: Describes all your internet gateways. # @return [InternetGateway::Collection] def internet_gateways(options = {}) batches = Enumerator.new do |y| options = Aws::Util.deep_merge(options, filters: [{ name: "attachment.vpc-id", values: [@id] }]) resp = @client.describe_internet_gateways(options) resp.each_page do |page| batch = [] page.data.internet_gateways.each do |i| batch << InternetGateway.new( id: i.internet_gateway_id, data: i, client: @client ) end y.yield(batch) end end InternetGateway::Collection.new(batches) end # @example Request syntax with placeholder values # # network_acls = vpc.network_acls({ # filters: [ # { # name: "String", # values: ["String"], # }, # ], # dry_run: false, # network_acl_ids: ["NetworkAclId"], # }) # @param [Hash] options ({}) # @option options [Array<Types::Filter>] :filters # One or more filters. # # * `association.association-id` - The ID of an association ID for the # ACL. # # * `association.network-acl-id` - The ID of the network ACL involved in # the association. # # * `association.subnet-id` - The ID of the subnet involved in the # association. # # * `default` - Indicates whether the ACL is the default network ACL for # the VPC. # # * `entry.cidr` - The IPv4 CIDR range specified in the entry. # # * `entry.icmp.code` - The ICMP code specified in the entry, if any. # # * `entry.icmp.type` - The ICMP type specified in the entry, if any. # # * `entry.ipv6-cidr` - The IPv6 CIDR range specified in the entry. # # * `entry.port-range.from` - The start of the port range specified in # the entry. # # * `entry.port-range.to` - The end of the port range specified in the # entry. # # * `entry.protocol` - The protocol specified in the entry (`tcp` \| # `udp` \| `icmp` or a protocol number). # # * `entry.rule-action` - Allows or denies the matching traffic (`allow` # \| `deny`). # # * `entry.rule-number` - The number of an entry (in other words, rule) # in the set of ACL entries. # # * `network-acl-id` - The ID of the network ACL. # # * `owner-id` - The ID of the AWS account that owns the network ACL. # # * `tag`\:&lt;key&gt; - The key/value combination of a tag assigned to # the resource. Use the tag key in the filter name and the tag value # as the filter value. For example, to find all resources that have a # tag with the key `Owner` and the value `TeamA`, specify `tag:Owner` # for the filter name and `TeamA` for the filter value. # # * `tag-key` - The key of a tag assigned to the resource. Use this # filter to find all resources assigned a tag with a specific key, # regardless of the tag value. # # * `vpc-id` - The ID of the VPC for the network ACL. # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @option options [Array<String>] :network_acl_ids # One or more network ACL IDs. # # Default: Describes all your network ACLs. # @return [NetworkAcl::Collection] def network_acls(options = {}) batches = Enumerator.new do |y| options = Aws::Util.deep_merge(options, filters: [{ name: "vpc-id", values: [@id] }]) resp = @client.describe_network_acls(options) resp.each_page do |page| batch = [] page.data.network_acls.each do |n| batch << NetworkAcl.new( id: n.network_acl_id, data: n, client: @client ) end y.yield(batch) end end NetworkAcl::Collection.new(batches) end # @example Request syntax with placeholder values # # network_interfaces = vpc.network_interfaces({ # filters: [ # { # name: "String", # values: ["String"], # }, # ], # dry_run: false, # network_interface_ids: ["NetworkInterfaceId"], # }) # @param [Hash] options ({}) # @option options [Array<Types::Filter>] :filters # One or more filters. # # * `addresses.private-ip-address` - The private IPv4 addresses # associated with the network interface. # # * `addresses.primary` - Whether the private IPv4 address is the # primary IP address associated with the network interface. # # * `addresses.association.public-ip` - The association ID returned when # the network interface was associated with the Elastic IP address # (IPv4). # # * `addresses.association.owner-id` - The owner ID of the addresses # associated with the network interface. # # * `association.association-id` - The association ID returned when the # network interface was associated with an IPv4 address. # # * `association.allocation-id` - The allocation ID returned when you # allocated the Elastic IP address (IPv4) for your network interface. # # * `association.ip-owner-id` - The owner of the Elastic IP address # (IPv4) associated with the network interface. # # * `association.public-ip` - The address of the Elastic IP address # (IPv4) bound to the network interface. # # * `association.public-dns-name` - The public DNS name for the network # interface (IPv4). # # * `attachment.attachment-id` - The ID of the interface attachment. # # * `attachment.attach-time` - The time that the network interface was # attached to an instance. # # * `attachment.delete-on-termination` - Indicates whether the # attachment is deleted when an instance is terminated. # # * `attachment.device-index` - The device index to which the network # interface is attached. # # * `attachment.instance-id` - The ID of the instance to which the # network interface is attached. # # * `attachment.instance-owner-id` - The owner ID of the instance to # which the network interface is attached. # # * `attachment.status` - The status of the attachment (`attaching` \| # `attached` \| `detaching` \| `detached`). # # * `availability-zone` - The Availability Zone of the network # interface. # # * `description` - The description of the network interface. # # * `group-id` - The ID of a security group associated with the network # interface. # # * `group-name` - The name of a security group associated with the # network interface. # # * `ipv6-addresses.ipv6-address` - An IPv6 address associated with the # network interface. # # * `mac-address` - The MAC address of the network interface. # # * `network-interface-id` - The ID of the network interface. # # * `owner-id` - The AWS account ID of the network interface owner. # # * `private-ip-address` - The private IPv4 address or addresses of the # network interface. # # * `private-dns-name` - The private DNS name of the network interface # (IPv4). # # * `requester-id` - The ID of the entity that launched the instance on # your behalf (for example, AWS Management Console, Auto Scaling, and # so on). # # * `requester-managed` - Indicates whether the network interface is # being managed by an AWS service (for example, AWS Management # Console, Auto Scaling, and so on). # # * `source-dest-check` - Indicates whether the network interface # performs source/destination checking. A value of `true` means # checking is enabled, and `false` means checking is disabled. The # value must be `false` for the network interface to perform network # address translation (NAT) in your VPC. # # * `status` - The status of the network interface. If the network # interface is not attached to an instance, the status is `available`; # if a network interface is attached to an instance the status is # `in-use`. # # * `subnet-id` - The ID of the subnet for the network interface. # # * `tag`\:&lt;key&gt; - The key/value combination of a tag assigned to # the resource. Use the tag key in the filter name and the tag value # as the filter value. For example, to find all resources that have a # tag with the key `Owner` and the value `TeamA`, specify `tag:Owner` # for the filter name and `TeamA` for the filter value. # # * `tag-key` - The key of a tag assigned to the resource. Use this # filter to find all resources assigned a tag with a specific key, # regardless of the tag value. # # * `vpc-id` - The ID of the VPC for the network interface. # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @option options [Array<String>] :network_interface_ids # One or more network interface IDs. # # Default: Describes all your network interfaces. # @return [NetworkInterface::Collection] def network_interfaces(options = {}) batches = Enumerator.new do |y| options = Aws::Util.deep_merge(options, filters: [{ name: "vpc-id", values: [@id] }]) resp = @client.describe_network_interfaces(options) resp.each_page do |page| batch = [] page.data.network_interfaces.each do |n| batch << NetworkInterface.new( id: n.network_interface_id, data: n, client: @client ) end y.yield(batch) end end NetworkInterface::Collection.new(batches) end # @example Request syntax with placeholder values # # requested_vpc_peering_connections = vpc.requested_vpc_peering_connections({ # filters: [ # { # name: "String", # values: ["String"], # }, # ], # dry_run: false, # vpc_peering_connection_ids: ["VpcPeeringConnectionId"], # }) # @param [Hash] options ({}) # @option options [Array<Types::Filter>] :filters # One or more filters. # # * `accepter-vpc-info.cidr-block` - The IPv4 CIDR block of the accepter # VPC. # # * `accepter-vpc-info.owner-id` - The AWS account ID of the owner of # the accepter VPC. # # * `accepter-vpc-info.vpc-id` - The ID of the accepter VPC. # # * `expiration-time` - The expiration date and time for the VPC peering # connection. # # * `requester-vpc-info.cidr-block` - The IPv4 CIDR block of the # requester's VPC. # # * `requester-vpc-info.owner-id` - The AWS account ID of the owner of # the requester VPC. # # * `requester-vpc-info.vpc-id` - The ID of the requester VPC. # # * `status-code` - The status of the VPC peering connection # (`pending-acceptance` \| `failed` \| `expired` \| `provisioning` \| # `active` \| `deleting` \| `deleted` \| `rejected`). # # * `status-message` - A message that provides more information about # the status of the VPC peering connection, if applicable. # # * `tag`\:&lt;key&gt; - The key/value combination of a tag assigned to # the resource. Use the tag key in the filter name and the tag value # as the filter value. For example, to find all resources that have a # tag with the key `Owner` and the value `TeamA`, specify `tag:Owner` # for the filter name and `TeamA` for the filter value. # # * `tag-key` - The key of a tag assigned to the resource. Use this # filter to find all resources assigned a tag with a specific key, # regardless of the tag value. # # * `vpc-peering-connection-id` - The ID of the VPC peering connection. # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @option options [Array<String>] :vpc_peering_connection_ids # One or more VPC peering connection IDs. # # Default: Describes all your VPC peering connections. # @return [VpcPeeringConnection::Collection] def requested_vpc_peering_connections(options = {}) batches = Enumerator.new do |y| options = Aws::Util.deep_merge(options, filters: [{ name: "requester-vpc-info.vpc-id", values: [@id] }]) resp = @client.describe_vpc_peering_connections(options) resp.each_page do |page| batch = [] page.data.vpc_peering_connections.each do |v| batch << VpcPeeringConnection.new( id: v.vpc_peering_connection_id, data: v, client: @client ) end y.yield(batch) end end VpcPeeringConnection::Collection.new(batches) end # @example Request syntax with placeholder values # # route_tables = vpc.route_tables({ # filters: [ # { # name: "String", # values: ["String"], # }, # ], # dry_run: false, # route_table_ids: ["RouteTableId"], # }) # @param [Hash] options ({}) # @option options [Array<Types::Filter>] :filters # One or more filters. # # * `association.route-table-association-id` - The ID of an association # ID for the route table. # # * `association.route-table-id` - The ID of the route table involved in # the association. # # * `association.subnet-id` - The ID of the subnet involved in the # association. # # * `association.main` - Indicates whether the route table is the main # route table for the VPC (`true` \| `false`). Route tables that do # not have an association ID are not returned in the response. # # * `owner-id` - The ID of the AWS account that owns the route table. # # * `route-table-id` - The ID of the route table. # # * `route.destination-cidr-block` - The IPv4 CIDR range specified in a # route in the table. # # * `route.destination-ipv6-cidr-block` - The IPv6 CIDR range specified # in a route in the route table. # # * `route.destination-prefix-list-id` - The ID (prefix) of the AWS # service specified in a route in the table. # # * `route.egress-only-internet-gateway-id` - The ID of an egress-only # Internet gateway specified in a route in the route table. # # * `route.gateway-id` - The ID of a gateway specified in a route in the # table. # # * `route.instance-id` - The ID of an instance specified in a route in # the table. # # * `route.nat-gateway-id` - The ID of a NAT gateway. # # * `route.transit-gateway-id` - The ID of a transit gateway. # # * `route.origin` - Describes how the route was created. # `CreateRouteTable` indicates that the route was automatically # created when the route table was created; `CreateRoute` indicates # that the route was manually added to the route table; # `EnableVgwRoutePropagation` indicates that the route was propagated # by route propagation. # # * `route.state` - The state of a route in the route table (`active` \| # `blackhole`). The blackhole state indicates that the route's target # isn't available (for example, the specified gateway isn't attached # to the VPC, the specified NAT instance has been terminated, and so # on). # # * `route.vpc-peering-connection-id` - The ID of a VPC peering # connection specified in a route in the table. # # * `tag`\:&lt;key&gt; - The key/value combination of a tag assigned to # the resource. Use the tag key in the filter name and the tag value # as the filter value. For example, to find all resources that have a # tag with the key `Owner` and the value `TeamA`, specify `tag:Owner` # for the filter name and `TeamA` for the filter value. # # * `tag-key` - The key of a tag assigned to the resource. Use this # filter to find all resources assigned a tag with a specific key, # regardless of the tag value. # # * `vpc-id` - The ID of the VPC for the route table. # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @option options [Array<String>] :route_table_ids # One or more route table IDs. # # Default: Describes all your route tables. # @return [RouteTable::Collection] def route_tables(options = {}) batches = Enumerator.new do |y| options = Aws::Util.deep_merge(options, filters: [{ name: "vpc-id", values: [@id] }]) resp = @client.describe_route_tables(options) resp.each_page do |page| batch = [] page.data.route_tables.each do |r| batch << RouteTable.new( id: r.route_table_id, data: r, client: @client ) end y.yield(batch) end end RouteTable::Collection.new(batches) end # @example Request syntax with placeholder values # # security_groups = vpc.security_groups({ # filters: [ # { # name: "String", # values: ["String"], # }, # ], # group_ids: ["String"], # group_names: ["SecurityGroupName"], # dry_run: false, # }) # @param [Hash] options ({}) # @option options [Array<Types::Filter>] :filters # The filters. If using multiple filters for rules, the results include # security groups for which any combination of rules - not necessarily a # single rule - match all filters. # # * `description` - The description of the security group. # # * `egress.ip-permission.cidr` - An IPv4 CIDR block for an outbound # security group rule. # # * `egress.ip-permission.from-port` - For an outbound rule, the start # of port range for the TCP and UDP protocols, or an ICMP type number. # # * `egress.ip-permission.group-id` - The ID of a security group that # has been referenced in an outbound security group rule. # # * `egress.ip-permission.group-name` - The name of a security group # that has been referenced in an outbound security group rule. # # * `egress.ip-permission.ipv6-cidr` - An IPv6 CIDR block for an # outbound security group rule. # # * `egress.ip-permission.prefix-list-id` - The ID of a prefix list to # which a security group rule allows outbound access. # # * `egress.ip-permission.protocol` - The IP protocol for an outbound # security group rule (`tcp` \| `udp` \| `icmp` or a protocol number). # # * `egress.ip-permission.to-port` - For an outbound rule, the end of # port range for the TCP and UDP protocols, or an ICMP code. # # * `egress.ip-permission.user-id` - The ID of an AWS account that has # been referenced in an outbound security group rule. # # * `group-id` - The ID of the security group. # # * `group-name` - The name of the security group. # # * `ip-permission.cidr` - An IPv4 CIDR block for an inbound security # group rule. # # * `ip-permission.from-port` - For an inbound rule, the start of port # range for the TCP and UDP protocols, or an ICMP type number. # # * `ip-permission.group-id` - The ID of a security group that has been # referenced in an inbound security group rule. # # * `ip-permission.group-name` - The name of a security group that has # been referenced in an inbound security group rule. # # * `ip-permission.ipv6-cidr` - An IPv6 CIDR block for an inbound # security group rule. # # * `ip-permission.prefix-list-id` - The ID of a prefix list from which # a security group rule allows inbound access. # # * `ip-permission.protocol` - The IP protocol for an inbound security # group rule (`tcp` \| `udp` \| `icmp` or a protocol number). # # * `ip-permission.to-port` - For an inbound rule, the end of port range # for the TCP and UDP protocols, or an ICMP code. # # * `ip-permission.user-id` - The ID of an AWS account that has been # referenced in an inbound security group rule. # # * `owner-id` - The AWS account ID of the owner of the security group. # # * `tag`\:&lt;key&gt; - The key/value combination of a tag assigned to # the resource. Use the tag key in the filter name and the tag value # as the filter value. For example, to find all resources that have a # tag with the key `Owner` and the value `TeamA`, specify `tag:Owner` # for the filter name and `TeamA` for the filter value. # # * `tag-key` - The key of a tag assigned to the resource. Use this # filter to find all resources assigned a tag with a specific key, # regardless of the tag value. # # * `vpc-id` - The ID of the VPC specified when the security group was # created. # @option options [Array<String>] :group_ids # The IDs of the security groups. Required for security groups in a # nondefault VPC. # # Default: Describes all your security groups. # @option options [Array<String>] :group_names # \[EC2-Classic and default VPC only\] The names of the security groups. # You can specify either the security group name or the security group # ID. For security groups in a nondefault VPC, use the `group-name` # filter to describe security groups by name. # # Default: Describes all your security groups. # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @return [SecurityGroup::Collection] def security_groups(options = {}) batches = Enumerator.new do |y| options = Aws::Util.deep_merge(options, filters: [{ name: "vpc-id", values: [@id] }]) resp = @client.describe_security_groups(options) resp.each_page do |page| batch = [] page.data.security_groups.each do |s| batch << SecurityGroup.new( id: s.group_id, data: s, client: @client ) end y.yield(batch) end end SecurityGroup::Collection.new(batches) end # @example Request syntax with placeholder values # # subnets = vpc.subnets({ # filters: [ # { # name: "String", # values: ["String"], # }, # ], # subnet_ids: ["SubnetId"], # dry_run: false, # }) # @param [Hash] options ({}) # @option options [Array<Types::Filter>] :filters # One or more filters. # # * `availability-zone` - The Availability Zone for the subnet. You can # also use `availabilityZone` as the filter name. # # * `availability-zone-id` - The ID of the Availability Zone for the # subnet. You can also use `availabilityZoneId` as the filter name. # # * `available-ip-address-count` - The number of IPv4 addresses in the # subnet that are available. # # * `cidr-block` - The IPv4 CIDR block of the subnet. The CIDR block you # specify must exactly match the subnet's CIDR block for information # to be returned for the subnet. You can also use `cidr` or # `cidrBlock` as the filter names. # # * `default-for-az` - Indicates whether this is the default subnet for # the Availability Zone. You can also use `defaultForAz` as the filter # name. # # * `ipv6-cidr-block-association.ipv6-cidr-block` - An IPv6 CIDR block # associated with the subnet. # # * `ipv6-cidr-block-association.association-id` - An association ID for # an IPv6 CIDR block associated with the subnet. # # * `ipv6-cidr-block-association.state` - The state of an IPv6 CIDR # block associated with the subnet. # # * `owner-id` - The ID of the AWS account that owns the subnet. # # * `state` - The state of the subnet (`pending` \| `available`). # # * `subnet-arn` - The Amazon Resource Name (ARN) of the subnet. # # * `subnet-id` - The ID of the subnet. # # * `tag`\:&lt;key&gt; - The key/value combination of a tag assigned to # the resource. Use the tag key in the filter name and the tag value # as the filter value. For example, to find all resources that have a # tag with the key `Owner` and the value `TeamA`, specify `tag:Owner` # for the filter name and `TeamA` for the filter value. # # * `tag-key` - The key of a tag assigned to the resource. Use this # filter to find all resources assigned a tag with a specific key, # regardless of the tag value. # # * `vpc-id` - The ID of the VPC for the subnet. # @option options [Array<String>] :subnet_ids # One or more subnet IDs. # # Default: Describes all your subnets. # @option options [Boolean] :dry_run # Checks whether you have the required permissions for the action, # without actually making the request, and provides an error response. # If you have the required permissions, the error response is # `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`. # @return [Subnet::Collection] def subnets(options = {}) batches = Enumerator.new do |y| options = Aws::Util.deep_merge(options, filters: [{ name: "vpc-id", values: [@id] }]) resp = @client.describe_subnets(options) resp.each_page do |page| batch = [] page.data.subnets.each do |s| batch << Subnet.new( id: s.subnet_id, data: s, client: @client ) end y.yield(batch) end end Subnet::Collection.new(batches) end # @deprecated # @api private def identifiers { id: @id } end deprecated(:identifiers) private def extract_id(args, options) value = args[0] || options.delete(:id) case value when String then value when nil then raise ArgumentError, "missing required option :id" else msg = "expected :id to be a String, got #{value.class}" raise ArgumentError, msg end end def yield_waiter_and_warn(waiter, &block) if !@waiter_block_warned msg = "pass options to configure the waiter; "\ "yielding the waiter is deprecated" warn(msg) @waiter_block_warned = true end yield(waiter.waiter) end def separate_params_and_options(options) opts = Set.new( [:client, :max_attempts, :delay, :before_attempt, :before_wait] ) waiter_opts = {} waiter_params = {} options.each_pair do |key, value| if opts.include?(key) waiter_opts[key] = value else waiter_params[key] = value end end waiter_opts[:client] ||= @client [waiter_opts, waiter_params] end class Collection < Aws::Resources::Collection; end end end
40.077979
808
0.618498
219fd4c2a45b9af96941e14865adf3c36d856583
2,588
# lib/api/v1/cloud.rb module API module V1 class Cloud < Grape::API resource :cloud do desc 'Get pricing for cloud providers', { notes: <<-NOTE Cette methode permet de connaitre toutes les informations sur les prix par heure de differents providers. ## Requête * Le paramètre de provider `:provider` est obligatoire * Pour le moment, seuls Amazon `aws` et Google Compute Engine `gce` sont disponibles. NOTE } params do requires :provider, type: String, values: Settings.cloud['providers'], desc: "Define provider to get" end get '/:provider/pricing' do case params[:provider] when 'aws' begin aws = JSON.parse(open(Settings.cloud['provider_aws_url']).read) rescue error!("api #{params[:provider]} not available", 503) end result = {} aws.each do |instance| result[instance['instance_type']] = { spec: { vcpu: instance['vCPU'], memory: instance['memory'], network: instance['network_performance'], storage: instance['storage'], }, pricing: instance['pricing'] } end result when 'gce' begin gce = JSON.parse(open(Settings.cloud['provider_gce_url']).read) rescue error!("api #{params[:provider]} not available", 503) end result = {} gce['gcp_price_list'].each do |instance, details| if (instance =~ /^CP\-COMPUTEENGINE/) result[instance.gsub('CP-COMPUTEENGINE-VMIMAGE-', '').underscore.gsub('_','-')] = { spec: { vcpu: details['cores'], memory: details['memory'], network: 'N/A', storage: { ssd: details['ssd'] }, }, pricing: { europe: details['eu'], usa: details['us'], asia_pacific: details['apac'] } } end end result end end end end end end
33.179487
119
0.428516
ac85014af7df0798963532e04a63a75cdf53c0f8
1,100
# options to add to the keystone.conf as secrets (will not be saved in node # attribute) default['openstack']['identity']['conf_secrets'] = {} default['openstack']['identity']['conf'].tap do |conf| # [DEFAULT] if node['openstack']['identity']['syslog']['use'] # [DEFAULT] option in keystone.conf to read additional logging.conf conf['DEFAULT']['log_config_append'] = '/etc/openstack/logging.conf' else # [DEFAULT] option in keystone.conf to set keystone log dir conf['DEFAULT']['log_dir'] = '/var/log/keystone' end if node['openstack']['identity']['notification_driver'] == 'messaging' # [DEFAULT] option in keystone.conf to define mq notification topics conf['DEFAULT']['notification_topics'] = 'notifications' end # [assignment] option in keystone.conf to set driver conf['assignment']['driver'] = 'sql' # [cache] option in keystone.conf to set oslo backend conf['cache']['enabled'] = true conf['cache']['backend'] = 'oslo_cache.memcache_pool' # [policy] option in keystone.conf to set policy backend driver conf['policy']['driver'] = 'sql' end
39.285714
75
0.688182
2183386e0b1e133a9cd2086668bb3c0a253f985d
651
require_relative '../test_config' class ShowPostTest < MiniTest::Test include DatabaseTesting def context @context ||= OpenStruct.new end def test_will_show_post form = CreatePost::Form.new :email => '[email protected]' creation = CreatePost.new context, form post = creation.output.first interactor = ShowPost.new context, post.id assert_equal :found, interactor.outcome assert_equal post, interactor.output.first end def test_will_return_not_found_for_no_post interactor = ShowPost.new context, '1' assert_equal :not_found, interactor.outcome assert_equal '1', interactor.output.first end end
27.125
60
0.743472
bf08e14c2bacc9e998bfce20a50a6a7df435a461
5,349
module Squall # OnApp User class User < Base # Public: Lists all users. # # Returns an Array. def list response = request(:get, '/users.json') response.collect { |user| user['user'] } end # Public: Create a new User # # options - Params for creating the User: # :login - Login name # :email - Email address # :first_name - First name # :last_name - Last name # :password - Password # :passwor_confirmation - Password # :role - Role to be assigned to user # :time_zone - Time zone for user. If not provided it # will be set automatically. # :locale - Locale for user. If not provided it will # be set automatically. # :status - User's status: `active`, `suspended`, # `deleted` # :billing_plan_id - ID of billing plan to be applied to # user's account # :role_ids - Array of IDs of roles to be assigned to # the user # :suspend_after_hours - Number of hours after which the account # will be automatically suspended # :suspend_at - Time after which the account will # automatically be suspended, formatted # as +YYYYMMDD ThhmmssZ+ # # Example # # create login: 'bob', # email: '[email protected]', # password: 'secret', # password_confirmation: 'secret' # first_name: 'Bob', # last_name: 'Smith' # # Returns a Hash. def create(options = {}) request(:post, '/users.json', default_params(options)) end # Public: Edit a user # # id - ID of user # options - Params for creating the user, see `#create` # # Returns a Hash. def edit(id, options = {}) request(:put, "/users/#{id}.json", default_params(options)) end # Public: Get info for a user. # # id - ID of user # # Returns a Hash. def show(id) response = request(:get, "/users/#{id}.json") response["user"] end # Public: Create a new API Key for a user. # # id - ID of user # # Return a Hash. def generate_api_key(id) response = request(:post, "/users/#{id}/make_new_api_key.json") response["user"] end # Public: Suspend a user. # # id - ID of user # # Return a Hash. def suspend(id) response = request(:get, "/users/#{id}/suspend.json") response["user"] end # Public: Activate a user. # # id - ID of user # # Return a Hash. def activate(id) response = request(:get, "/users/#{id}/activate_user.json") response["user"] end alias_method :unsuspend, :activate # Public: Delete a user. # # id - ID of user # # Note: this does not delete remove a user from the database. First, # their status will be set to "Deleted." If you call this method again, # the user will be completely removed. # # Return a Hash. def delete(id) request(:delete, "/users/#{id}.json") end # Public: Get the stats for each of a User's VirtualMachines # # id - ID of user # # Return a Hash. def stats(id) request(:get, "/users/#{id}/vm_stats.json") end # Public: List a User's bills. # # id - ID of user # # Return a Hash. def monthly_bills(id) request(:get, "/users/#{id}/monthly_bills.json") end # Public: List User's VirtualMachines. # # id - ID of user # # Return a Hash. def virtual_machines(id) response = request(:get, "/users/#{id}/virtual_machines.json") response.collect { |vm| vm['virtual_machine']} end # Public: List Hypervisors for a User's VirtualMachines. # # id - ID of user # # Return a Hash. def hypervisors(id) response = request(:get, "/users/#{id}/hypervisors.json") response.collect { |vm| vm['hypervisor']} end # Public: List data store zones associated with user. # # id - ID of user # # Return a Hash. def data_store_zones(id) response = request(:get, "/users/#{id}/data_store_zones.json") response.collect { |vm| vm['data-store-group']} end # Public: List network zones associated with user. # # id - ID of user # # Return a Hash. def network_zones(id) response = request(:get, "/users/#{id}/network_zones.json") response.collect { |vm| vm['network_group']} end # Public: Show resources available to a user for creating a virtual machine. # # id - ID of user # # Returns a Hash. def limits(id) response = request(:get, "/users/#{id}/limits.json") response["limits"] end end end
28.913514
80
0.511684
28b09510f4814e1271b1026a83945f0ffa890cfc
52
module GovukTechDocs VERSION = "2.3.0".freeze end
13
26
0.730769
797ed755976fd1d83f7099ca58d10bfefd83d85d
535
COMMON_SESSION = { :boot_wait => "10", :cpu_count => "1", :disk_format => "VDI", :disk_size => "40960", :hostiocache => "off", :ioapic => "on", :iso_download_timeout => "1000", :kickstart_port => "7122", :kickstart_timeout => "10000", :memory_size=> "384", :pae => "on", :postinstall_timeout => "10000", :ssh_guest_port => "22", :ssh_host_port => "7222", :ssh_key => "", :ssh_login_timeout => "1000", :ssh_password => "vagrant", :ssh_user => "vagrant", :sudo_cmd => "echo '%p'|sudo -S sh '%f'", }
24.318182
43
0.575701
6134b782d220bc91b0b124cb7d02019d379eb7e3
659
require File.expand_path("../../Abstract/abstract-php-extension", __FILE__) class Php56Mongo < AbstractPhp56Extension init homepage 'http://pecl.php.net/package/mongo' url 'http://pecl.php.net/get/mongo-1.5.4.tgz' sha1 'd4d34c7450630726a44c1fd3d4fc4c5a8d738f25' head 'https://github.com/mongodb/mongo-php-driver.git' def install Dir.chdir "mongo-#{version}" unless build.head? ENV.universal_binary if build.universal? safe_phpize system "./configure", "--prefix=#{prefix}", phpconfig system "make" prefix.install "modules/mongo.so" write_config_file if build.with? "config-file" end end
28.652174
75
0.694992
6a9594796cbfa3196c2a7874f241ebc3394f5155
2,973
require 'spec_helper_acceptance' test_name 'client -> 1 server without TLS' describe 'rsyslog client -> 1 server without TLS' do let(:client){ only_host_with_role( hosts, 'client' ) } let(:server){ hosts_with_role( hosts, 'server' ).first } let(:client_fqdn){ fact_on( client, 'fqdn' ) } let(:server_fqdn){ fact_on( server, 'fqdn' ) } let(:hieradata) { <<-EOS --- iptables::disable : false rsyslog::server::enable_firewall : true EOS } let(:client_manifest) { <<-EOS class { 'rsyslog': log_servers => ['server-1'], logrotate => true, enable_tls_logging => false, pki => false, } rsyslog::rule::remote { 'send_the_logs': rule => 'prifilt(\\'*.*\\')' } EOS } let(:server_manifest) { <<-EOS # Turns off firewalld in EL7. Presumably this would already be done. include 'iptables' iptables::listen::tcp_stateful { 'ssh': dports => 22, trusted_nets => ['any'], } class { 'rsyslog': tcp_server => true, logrotate => true, enable_tls_logging => false, pki => false, trusted_nets => ['any'], } class { 'rsyslog::server': enable_firewall => true, enable_selinux => false, enable_tcpwrappers => false, } # define a dynamic file with an rsyslog template # NOTE: puppet doesn't need to manage missing directories in this path; # rsyslog will create them as needed. rsyslog::template::string { 'log_everything_by_host': string => '/var/log/hosts/%HOSTNAME%/everything.log', } # log all messages to the dynamic file we just defined ^^ rsyslog::rule::local { 'all_the_logs': rule => 'prifilt(\\'*.*\\')', dyna_file => 'log_everything_by_host', } EOS } context 'client -> 1 server without TLS' do it 'should configure server without errors' do set_hieradata_on(server, hieradata) apply_manifest_on(server, server_manifest, :catch_failures => true) # requires 2 runs to be idempotent on centos6 apply_manifest_on(server, server_manifest, :catch_failures => true) end it 'should configure server idempotently' do apply_manifest_on(server, server_manifest, :catch_changes => true) end it 'should configure client without errors' do apply_manifest_on(client, client_manifest, :catch_failures => true) end it 'should configure client idempotently' do apply_manifest_on(client, client_manifest, :catch_changes => true) end it 'should successfully send log messages' do on client, 'logger -t FOO TEST-WITHOUT-TLS' remote_log = "/var/log/hosts/#{client_fqdn}/everything.log" on server, "test -f #{remote_log}" on server, "grep TEST-WITHOUT-TLS #{remote_log}" end end end
29.147059
77
0.605113
b911f1df4ba91392b0a40215bee4c366c8adc093
1,596
require "log4r" require "json" module VagrantPlugins module AWS module Action # This terminates the running instance. class TerminateInstance def initialize(app, env) @app = app @logger = Log4r::Logger.new("vagrant_aws::action::terminate_instance") end def call(env) server = env[:aws_compute].servers.get(env[:machine].id) region = env[:machine].provider_config.region region_config = env[:machine].provider_config.get_region_config(region) elastic_ip = region_config.elastic_ip # Release the elastic IP ip_file = env[:machine].data_dir.join('elastic_ip') if ip_file.file? release_address(env,ip_file.read) ip_file.delete end # Destroy the server and remove the tracking ID env[:ui].info(I18n.t("vagrant_aws.terminating")) server.destroy env[:machine].id = nil @app.call(env) end # Release an elastic IP address def release_address(env,eip) h = JSON.parse(eip) # Use association_id and allocation_id for VPC, use public IP for EC2 if h['association_id'] env[:aws_compute].disassociate_address(nil,h['association_id']) env[:aws_compute].release_address(h['allocation_id']) else env[:aws_compute].disassociate_address(h['public_ip']) env[:aws_compute].release_address(h['public_ip']) end end end end end end
30.692308
82
0.595238
79524a026cc408483d0bb1542dab299aaff92e9f
2,697
#!/usr/bin/env rspec require 'spec_helper' init_param, = Puppet::Type.type(:init_param) describe init_param do let(:attribute_class) { @class.attrclass(attribute_name) } let(:attribute) {@resource.property(attribute_name)} before(:each) do @class = init_param @provider = double 'provider' allow(@provider).to receive(:name).and_return(:simple) allow(@class).to receive(:defaultprovider).and_return @provider class Puppet::Type::Init_param; def self.default_sid; 'TEST'; end; end @resource = @class.new({:name => 'MEMORY_TARGET'}) end it 'should have :name and :parameter_name be its namevar' do expect(@class.key_attributes).to eq([:name, :parameter_name, :instance]) end describe ':paremeter_name' do let(:attribute_class) { @class.attrclass(:parameter_name) } it 'should pick its value from element NAME' do raw_resource = InstancesResults['NAME','memory_target'] expect(attribute_class.translate_to_resource(raw_resource)).to eq 'memory_target' end it 'should raise an error when name not found in raw_results' do raw_resource = InstancesResults['NEMA','MY_NAME'] expect{attribute_class.translate_to_resource(raw_resource)}.to raise_error(RuntimeError) end it 'should munge to uppercase' do @resource[:parameter_name] = 'sga_target' expect(@resource[:parameter_name]).to eq 'sga_target' end it 'should not accept a name with whitespace' do expect{@resource[:parameter_name] = 'a a' }.to raise_error(Puppet::Error) end it 'should not accept an empty name' do expect{@resource[:parameter_name] = '' }.to raise_error(Puppet::Error) end it_behaves_like 'an easy_type attribute', { :attribute => :parameter_name, :result_identifier => 'NAME', :raw_value => 'MEMORY_TARGET', :test_value => 'MEMORY_TARGET', } end describe ':value' do let(:attribute_name) { :value} context "when geting data from the system" do it 'should raise an error when name not found in raw_results' do raw_resource = InstancesResults['NAME','MY_NAME'] expect{attribute_class.translate_to_resource(raw_resource)}.to raise_error(RuntimeError) end it 'should pick its value from element DISPLAY_VALUE' do raw_resource = InstancesResults['DISPLAY_VALUE','42G'] expect(attribute_class.translate_to_resource(raw_resource)).to eq '42G' end end context "base parameter settings" do it 'should accept a value and not modify it' do @resource[:value] = 'none' expect(@resource[:value]).to eq 'none' end end end end
29.637363
96
0.683352
e82ed43d85d59c27cf35c9ed1b9580ffd3a858e9
2,456
require_relative "./helper" class TestClassifier < Minitest::Test include Linguist def fixture(name) File.read(File.join(samples_path, name)) end def test_classify db = {} Classifier.train! db, "Ruby", fixture("Ruby/foo.rb") Classifier.train! db, "Objective-C", fixture("Objective-C/Foo.h") Classifier.train! db, "Objective-C", fixture("Objective-C/Foo.m") results = Classifier.classify(db, fixture("Objective-C/hello.m")) assert_equal "Objective-C", results.first[0] tokens = Tokenizer.tokenize(fixture("Objective-C/hello.m")) results = Classifier.classify(db, tokens) assert_equal "Objective-C", results.first[0] end def test_restricted_classify db = {} Classifier.train! db, "Ruby", fixture("Ruby/foo.rb") Classifier.train! db, "Objective-C", fixture("Objective-C/Foo.h") Classifier.train! db, "Objective-C", fixture("Objective-C/Foo.m") results = Classifier.classify(db, fixture("Objective-C/hello.m"), ["Objective-C"]) assert_equal "Objective-C", results.first[0] results = Classifier.classify(db, fixture("Objective-C/hello.m"), ["Ruby"]) assert_equal "Ruby", results.first[0] end def test_instance_classify_empty results = Classifier.classify(Samples.cache, "") assert results.first[1] < 0.5, results.first.inspect end def test_instance_classify_nil assert_equal [], Classifier.classify(Samples.cache, nil) end def test_classify_ambiguous_languages # Skip extensions with catch-all heuristics (e.g. .sql) skip_extensions = Set.new Heuristics.all.each do |h| rules = h.instance_variable_get(:@rules) if rules[-1]['pattern'].is_a? AlwaysMatch skip_extensions |= Set.new(h.extensions) end end Samples.each do |sample| language = Linguist::Language.find_by_name(sample[:language]) languages = Language.find_by_filename(sample[:path]).map(&:name) next if languages.length == 1 languages = Language.find_by_extension(sample[:path]).map(&:name) next if languages.length <= 1 next if skip_extensions.include? sample[:extname] results = Classifier.classify(Samples.cache, File.read(sample[:path]), languages) assert_equal language.name, results.first[0], "#{sample[:path]}\n#{results.inspect}" end end def test_classify_empty_languages assert_equal [], Classifier.classify(Samples.cache, fixture("Ruby/foo.rb"), []) end end
32.746667
90
0.692997
393c68677948b1104df8e00e1b80a72b6598d096
2,211
require 'spec_helper' feature 'Tiered Calculator Promotions' do stub_authorization! let(:promotion) { create :promotion } before do visit spree.edit_admin_promotion_path(promotion) end it 'adding a tiered percent calculator', js: true do select2 'Create whole-order adjustment', from: 'Add action of type' within('#action_fields') { click_button 'Add' } select2 'Tiered Percent', from: 'Calculator' within('#actions_container') { click_button 'Update' } within('#actions_container .settings') do expect(page.body).to have_content('Base Percent') expect(page.body).to have_content('Tiers') click_button 'Add' end fill_in 'Base Percent', with: 5 within('.tier') do find('.js-base-input').set(100) page.execute_script("$('.js-base-input').change();") find('.js-value-input').set(10) page.execute_script("$('.js-value-input').change();") end within('#actions_container') { click_button 'Update' } first_action = promotion.actions.first expect(first_action.class).to eq Spree::Promotion::Actions::CreateAdjustment first_action_calculator = first_action.calculator expect(first_action_calculator.class).to eq Spree::Calculator::TieredPercent expect(first_action_calculator.preferred_base_percent).to eq 5 expect(first_action_calculator.preferred_tiers).to eq Hash[100.0 => 10.0] end context 'with an existing tiered flat rate calculator' do let(:promotion) { create :promotion, :with_order_adjustment } before do action = promotion.actions.first action.calculator = Spree::Calculator::TieredFlatRate.new action.calculator.preferred_base_amount = 5 action.calculator.preferred_tiers = Hash[100 => 10, 200 => 15, 300 => 20] action.calculator.save! visit spree.edit_admin_promotion_path(promotion) end it 'deleting a tier', js: true do within('.tier:nth-child(2)') do click_icon :delete end within('#actions_container') { click_button 'Update' } calculator = promotion.actions.first.calculator expect(calculator.preferred_tiers).to eq Hash[100.0 => 10.0, 300.0 => 20.0] end end end
31.140845
81
0.694256
b9b2d7a4e6a76c6cb5bb541897bf5d6a6b576571
68
# frozen_string_literal: true class Bearer VERSION = "3.0.1" end
11.333333
29
0.720588
4ab0c206dfe94feef352078f37ce73b326bbc02d
1,413
module Seek module Biosamples module PhenoTypesAndGenoTypes def self.included(base) base.has_many :phenotypes base.has_many :genotypes base.accepts_nested_attributes_for :genotypes,:allow_destroy=>true base.accepts_nested_attributes_for :phenotypes,:allow_destroy=>true base.before_destroy :destroy_genotypes_phenotypes end def genotype_info genotype_detail = [] genotypes.each do |genotype| genotype_detail << genotype.modification.try(:title).to_s + ' ' + genotype.gene.try(:title).to_s if genotype.gene end genotype_detail = genotype_detail.blank? ? 'wild-type' : genotype_detail.join(';') genotype_detail end def phenotype_info phenotype_detail = [] phenotypes.each do |phenotype| phenotype_detail << phenotype.try(:description) unless phenotype.try(:description).blank? end phenotype_detail = phenotype_detail.blank? ? 'wild-type' : phenotype_detail.join('; ') phenotype_detail end def destroy_genotypes_phenotypes genotypes = self.genotypes phenotypes = self.phenotypes (genotypes | phenotypes).each do |type| if (type.strain == self || type.strain.nil?) && (type.specimen==self || type.specimen.nil?) type.destroy end end end end end end
32.860465
123
0.650389
5d2db78f2da2ebd8ba561706024e502f305570e4
2,202
require 'okcomputer' # /status for 'upness' (Rails app is responding), e.g. for load balancer # /status/all to show all dependencies # /status/<name-of-check> for a specific check (e.g. for nagios warning) OkComputer.mount_at = 'status' OkComputer.check_in_parallel = true OkComputer::Registry.deregister 'database' # don't check (unused) ActiveRecord database conn # REQUIRED checks, required to pass for /status/all # individual checks also avail at /status/<name-of-check> OkComputer::Registry.register 'ruby_version', OkComputer::RubyVersionCheck.new # TODO: add app version check when okcomputer works with cap 3 (see https://github.com/sportngin/okcomputer/pull/112) # note that purl home page is very resource heavy purl_url_to_check = Settings.purl_url + (Settings.purl_url.end_with?('/') ? '' : '/') + 'status' OkComputer::Registry.register 'purl_url', OkComputer::HttpCheck.new(purl_url_to_check) OkComputer::Registry.register 'stacks_url', OkComputer::HttpCheck.new(Settings.stacks_url) OkComputer.make_optional ['stacks_url'] # ------------------------------------------------------------------------------ # NON-CRUCIAL (Optional) checks, avail at /status/<name-of-check> # - at individual endpoint, HTTP response code reflects the actual result # - in /status/all, these checks will display their result text, but will not affect HTTP response code if Settings.enable_media_viewer? stream_url = Settings.stream.url unless stream_url.start_with?(Settings.streaming.hls.protocol) stream_url = "#{Settings.streaming.hls.protocol}://#{stream_url}" end OkComputer::Registry.register 'streaming_url', OkComputer::HttpCheck.new(stream_url) OkComputer.make_optional ['streaming_url'] end OkComputer::Registry.register 'geo_web_services_url', OkComputer::HttpCheck.new(Settings.geo_wms_url) # Geo objects use this to link out to Earthworks' # check geo_external_url without the last part after the slash geo_ext_url_pieces = Settings.geo_external_url.split('/') url_to_check = geo_ext_url_pieces[0..-2].join('/') OkComputer::Registry.register 'geo_external_url', OkComputer::HttpCheck.new(url_to_check) OkComputer.make_optional %w(geo_web_services_url geo_external_url)
50.045455
117
0.754768
7a3ffc2afad035ce9f72c82e715ac520da15c4a5
325
require 'mxx_ru/cpp' require 'restinio/asio_helper.rb' MxxRu::Cpp::exe_target { target 'sample.hello_world' RestinioAsioHelper.attach_propper_asio( self ) required_prj 'nodejs/http_parser_mxxru/prj.rb' required_prj 'fmt_mxxru/prj.rb' required_prj 'restinio/platform_specific_libs.rb' cpp_source 'main.cpp' }
20.3125
51
0.778462
33743cdd918929e110806b875c82653a7e336ad6
340
class SpotifyNotifications < Cask version '0.4.8' sha256 '953028e9a1aad445005869598050cb8612980821a796563936f557e03b319f50' url 'https://github.com/citruspi/Spotify-Notifications/releases/download/0.4.8/Spotify.Notifications.-.0.4.8.zip' homepage 'http://spotify-notifications.citruspi.io/' link 'Spotify Notifications.app' end
34
115
0.797059
79e1f873802831c3dbba1914c92f4d4bdaf8289f
2,023
require 'fog/vcloud/models/compute/vdcs' require 'fog/vcloud/models/compute/vdc' Shindo.tests("Vcloud::Compute | vdc", ['vcloud']) do Fog::Vcloud::Compute::SUPPORTED_VERSIONS.each do |version| tests("api version #{version}") do pending if Fog.mocking? instance = Fog::Vcloud::Compute.new( :vcloud_host => 'vcloud.example.com', :vcloud_username => 'username', :vcloud_password => 'password', :vcloud_version => version ).get_vdc("https://vcloud.example.com/api#{(version == '1.0') ? '/v1.0' : ''}/vdc/1") instance.reload tests("#href").returns("https://vcloud.example.com/api#{(version == '1.0') ? '/v1.0' : ''}/vdc/1") { instance.href } tests("#name").returns("vDC1") { instance.name } tests('#organization').returns("Org1") { instance.organization.name } tests("#description").returns("Some Description") { instance.description } tests("#network_quota").returns(10) { instance.network_quota } tests("#nic_quota").returns(10) { instance.nic_quota } tests("#vm_quota").returns(10) { instance.vm_quota } tests("#is_enabled").returns(true) { instance.is_enabled } tests("#available_networks") do tests("#size").returns(2) { instance.available_networks.size } end tests("#storage_capacity") do tests("units").returns("MB") { instance.storage_capacity[:Units] } tests("allocated").returns("10240") { instance.storage_capacity[:Allocated] } end tests("#compute_capacity") do tests("cpu") do tests("allocated").returns("20000") { instance.compute_capacity[:Cpu][:Allocated] } tests("units").returns("MHz") { instance.compute_capacity[:Cpu][:Units] } end tests("memory") do tests("allocated").returns("1024") { instance.compute_capacity[:Memory][:Allocated] } tests("units").returns("MB") { instance.compute_capacity[:Memory][:Units] } end end end end end
41.285714
122
0.620366
ffb19da620a74fbeee4d0ea2b886b6a2a7c9cf42
1,010
# for serverspec documentation: http://serverspec.org/ require_relative 'spec_helper' pkgs = ['influxdb'] files = ['/etc/influxdb/influxdb.conf'] dirs = ['/var/lib/influxdb/data', '/var/lib/influxdb/meta', '/var/lib/influxdb/wal'] ports = ['8086', '2003'] pkgs.each do |pkg| describe package("#{pkg}") do it { should be_installed } end end files.each do |file| describe file("#{file}") do it { should be_file } end end dirs.each do |dir| describe file("#{dir}") do it { should be_directory } it { should be_owned_by 'influxdb' } end end describe service('influxdb') do it { should be_running } it { should be_enabled } end ports.each do |port| describe port("#{port}") do it { should be_listening } end end # let telegraf send first update # sleep(30) # # describe command('wget -qO- "http://localhost:8086/query?q=select+*+from+cpu+limit+1&db=telegraf" | grep -q dev-vagrant-usc1a-pr-10.0.1.15') do # its(:exit_status) { should eq 0 } # end
20.2
145
0.654455
d51c7dbedbfaa86a231ab83a6b1481324630b486
145
class KJess::Response class Version < KJess::Response keyword 'VERSION' arity 1 def version args.first end end end
13.181818
33
0.627586
f75fab05923f825e9e29d9b14d46eff424a84d65
288
require "codeclimate-test-reporter" CodeClimate::TestReporter.start $LOAD_PATH.unshift File.expand_path("../../lib", __FILE__) $LOAD_PATH.unshift File.expand_path("../../spec", __FILE__) require "blog/config/application.rb" require "rspec" require "rack/test" ENV["RACK_ENV"] = "test"
24
59
0.746528
7a05ca3fc886299b0c6d369a6254a45a71198345
441
# TODO class Spaceship @thruster_count = 2 def self.thruster_count end end class SpritelySpaceship < Spaceship @thruster_count = 4 def add(rval) @thruster_count + rval end end class EconolineSpaceship < Spaceship @thruster_count = 1 end puts SpritelySpaceship.thruster_count puts EconolineSpaceship.thruster_count spritelySpaceship = SpritelySpaceship.new puts spritelySpaceship.add 1000 puts Spaceship.thruster_count
16.961538
41
0.800454
21668f3dcbdc1f0896390a81a23f4204f0baaa61
9,808
# typed: true # frozen_string_literal: true require "extend/ENV/shared" require "development_tools" # ### Why `superenv`? # # 1. Only specify the environment we need (*NO* LDFLAGS for cmake) # 2. Only apply compiler-specific options when we are calling that compiler # 3. Force all incpaths and libpaths into the cc instantiation (fewer bugs) # 4. Cater toolchain usage to specific Xcode versions # 5. Remove flags that we don't want or that will break builds # 6. Simpler code # 7. Simpler formulae that *just work* # 8. Build-system agnostic configuration of the toolchain module Superenv extend T::Sig include SharedEnvExtension # @private attr_accessor :keg_only_deps, :deps, :run_time_deps sig { params(base: Superenv).void } def self.extended(base) base.keg_only_deps = [] base.deps = [] base.run_time_deps = [] end # The location of Homebrew's shims on this OS. sig { returns(Pathname) } def self.shims_path HOMEBREW_SHIMS_PATH/"super" end # @private sig { returns(T.nilable(Pathname)) } def self.bin; end sig { void } def reset super # Configure scripts generated by autoconf 2.61 or later export as_nl, which # we use as a heuristic for running under configure delete("as_nl") end # @private sig { params( formula: T.nilable(Formula), cc: T.nilable(String), build_bottle: T.nilable(T::Boolean), bottle_arch: T.nilable(String), testing_formula: T::Boolean, ).void } def setup_build_environment(formula: nil, cc: nil, build_bottle: false, bottle_arch: nil, testing_formula: false) super send(compiler) self["HOMEBREW_ENV"] = "super" self["MAKEFLAGS"] ||= "-j#{determine_make_jobs}" self["PATH"] = determine_path self["PKG_CONFIG_PATH"] = determine_pkg_config_path self["PKG_CONFIG_LIBDIR"] = determine_pkg_config_libdir self["HOMEBREW_CCCFG"] = determine_cccfg self["HOMEBREW_OPTIMIZATION_LEVEL"] = "Os" self["HOMEBREW_BREW_FILE"] = HOMEBREW_BREW_FILE.to_s self["HOMEBREW_PREFIX"] = HOMEBREW_PREFIX.to_s self["HOMEBREW_CELLAR"] = HOMEBREW_CELLAR.to_s self["HOMEBREW_OPT"] = "#{HOMEBREW_PREFIX}/opt" self["HOMEBREW_TEMP"] = HOMEBREW_TEMP.to_s self["HOMEBREW_OPTFLAGS"] = determine_optflags self["HOMEBREW_ARCHFLAGS"] = "" self["CMAKE_PREFIX_PATH"] = determine_cmake_prefix_path self["CMAKE_FRAMEWORK_PATH"] = determine_cmake_frameworks_path self["CMAKE_INCLUDE_PATH"] = determine_cmake_include_path self["CMAKE_LIBRARY_PATH"] = determine_cmake_library_path self["ACLOCAL_PATH"] = determine_aclocal_path self["M4"] = "#{HOMEBREW_PREFIX}/opt/m4/bin/m4" if deps.any? { |d| d.name == "libtool" } self["HOMEBREW_ISYSTEM_PATHS"] = determine_isystem_paths self["HOMEBREW_INCLUDE_PATHS"] = determine_include_paths self["HOMEBREW_LIBRARY_PATHS"] = determine_library_paths self["HOMEBREW_DEPENDENCIES"] = determine_dependencies self["HOMEBREW_FORMULA_PREFIX"] = @formula.prefix unless @formula.nil? # The HOMEBREW_CCCFG ENV variable is used by the ENV/cc tool to control # compiler flag stripping. It consists of a string of characters which act # as flags. Some of these flags are mutually exclusive. # # O - Enables argument refurbishing. Only active under the # make/bsdmake wrappers currently. # x - Enable C++11 mode. # g - Enable "-stdlib=libc++" for clang. # h - Enable "-stdlib=libstdc++" for clang. # K - Don't strip -arch <arch>, -m32, or -m64 # d - Don't strip -march=<target>. Use only in formulae that # have runtime detection of CPU features. # w - Pass -no_weak_imports to the linker # # These flags will also be present: # a - apply fix for apr-1-config path end alias generic_setup_build_environment setup_build_environment private sig { params(val: T.any(String, Pathname)).returns(String) } def cc=(val) self["HOMEBREW_CC"] = super end sig { params(val: T.any(String, Pathname)).returns(String) } def cxx=(val) self["HOMEBREW_CXX"] = super end sig { returns(String) } def determine_cxx determine_cc.to_s.gsub("gcc", "g++").gsub("clang", "clang++") end sig { returns(T::Array[Pathname]) } def homebrew_extra_paths [] end sig { returns(T.nilable(PATH)) } def determine_path path = PATH.new(Superenv.bin) # Formula dependencies can override standard tools. path.append(deps.map(&:opt_bin)) path.append(homebrew_extra_paths) path.append("/usr/bin", "/bin", "/usr/sbin", "/sbin") begin path.append(gcc_version_formula(T.must(homebrew_cc)).opt_bin) if homebrew_cc&.match?(GNU_GCC_REGEXP) rescue FormulaUnavailableError # Don't fail and don't add these formulae to the path if they don't exist. nil end path.existing end sig { returns(T::Array[Pathname]) } def homebrew_extra_pkg_config_paths [] end sig { returns(T.nilable(PATH)) } def determine_pkg_config_path PATH.new( deps.map { |d| d.opt_lib/"pkgconfig" }, deps.map { |d| d.opt_share/"pkgconfig" }, ).existing end sig { returns(T.nilable(PATH)) } def determine_pkg_config_libdir PATH.new( homebrew_extra_pkg_config_paths, ).existing end sig { returns(T.nilable(PATH)) } def determine_aclocal_path PATH.new( keg_only_deps.map { |d| d.opt_share/"aclocal" }, HOMEBREW_PREFIX/"share/aclocal", ).existing end sig { returns(T::Array[Pathname]) } def homebrew_extra_isystem_paths [] end sig { returns(T.nilable(PATH)) } def determine_isystem_paths PATH.new( HOMEBREW_PREFIX/"include", homebrew_extra_isystem_paths, ).existing end sig { returns(T.nilable(PATH)) } def determine_include_paths PATH.new(keg_only_deps.map(&:opt_include)).existing end sig { returns(T::Array[Pathname]) } def homebrew_extra_library_paths [] end sig { returns(T.nilable(PATH)) } def determine_library_paths paths = [] if compiler.match?(GNU_GCC_REGEXP) # Add path to GCC runtime libs for version being used to compile, # so that the linker will find those libs before any that may be linked in $HOMEBREW_PREFIX/lib. # https://github.com/cerisola/brew/pull/11459#issuecomment-851075936 begin f = gcc_version_formula(compiler.to_s) rescue FormulaUnavailableError nil else paths << (f.opt_lib/"gcc"/f.version.major) if f.any_version_installed? end end paths << keg_only_deps.map(&:opt_lib) paths << (HOMEBREW_PREFIX/"lib") paths += homebrew_extra_library_paths PATH.new(paths).existing end sig { returns(String) } def determine_dependencies deps.map(&:name).join(",") end sig { returns(T.nilable(PATH)) } def determine_cmake_prefix_path PATH.new( keg_only_deps.map(&:opt_prefix), HOMEBREW_PREFIX.to_s, ).existing end sig { returns(T::Array[Pathname]) } def homebrew_extra_cmake_include_paths [] end sig { returns(T.nilable(PATH)) } def determine_cmake_include_path PATH.new(homebrew_extra_cmake_include_paths).existing end sig { returns(T::Array[Pathname]) } def homebrew_extra_cmake_library_paths [] end sig { returns(T.nilable(PATH)) } def determine_cmake_library_path PATH.new(homebrew_extra_cmake_library_paths).existing end sig { returns(T::Array[Pathname]) } def homebrew_extra_cmake_frameworks_paths [] end sig { returns(T.nilable(PATH)) } def determine_cmake_frameworks_path PATH.new( deps.map(&:opt_frameworks), homebrew_extra_cmake_frameworks_paths, ).existing end sig { returns(String) } def determine_make_jobs Homebrew::EnvConfig.make_jobs end sig { returns(String) } def determine_optflags Hardware::CPU.optimization_flags.fetch(effective_arch) rescue KeyError odebug "Building a bottle for custom architecture (#{effective_arch})..." Hardware::CPU.arch_flag(effective_arch) end sig { returns(String) } def determine_cccfg "" end public # Removes the MAKEFLAGS environment variable, causing make to use a single job. # This is useful for makefiles with race conditions. # When passed a block, MAKEFLAGS is removed only for the duration of the block and is restored after its completion. sig { params(block: T.proc.returns(T.untyped)).returns(T.untyped) } def deparallelize(&block) old = delete("MAKEFLAGS") if block begin yield ensure self["MAKEFLAGS"] = old end end old end sig { returns(Integer) } def make_jobs self["MAKEFLAGS"] =~ /-\w*j(\d+)/ [Regexp.last_match(1).to_i, 1].max end sig { void } def permit_arch_flags append_to_cccfg "K" end sig { void } def runtime_cpu_detection append_to_cccfg "d" end sig { void } def cxx11 append_to_cccfg "x" append_to_cccfg "g" if homebrew_cc == "clang" end sig { void } def libcxx append_to_cccfg "g" if compiler == :clang end # @private sig { void } def refurbish_args append_to_cccfg "O" end # rubocop: disable Naming/MethodName # Fixes style error `Naming/MethodName: Use snake_case for method names.` sig { params(block: T.nilable(T.proc.void)).void } def O0(&block) if block with_env(HOMEBREW_OPTIMIZATION_LEVEL: "O0", &block) else self["HOMEBREW_OPTIMIZATION_LEVEL"] = "O0" end end sig { params(block: T.nilable(T.proc.void)).void } def O1(&block) if block with_env(HOMEBREW_OPTIMIZATION_LEVEL: "O1", &block) else self["HOMEBREW_OPTIMIZATION_LEVEL"] = "O1" end end # rubocop: enable Naming/MethodName end require "extend/os/extend/ENV/super"
27.019284
118
0.686378
79bc89645eeb533664561ab0795d9e6a4e641a22
6,108
# encoding: UTF-8 require 'gooddata' describe GoodData::Project do before(:all) do GoodData.logging_on @client = ConnectionHelper::create_default_connection @p = GoodData::Project.create_object(title: 'a', client: @client) @domain = @client.domain('dummy_domain') @roles = [ GoodData::ProjectRole.create_object(title: 'Test Role', summary: 'Test role summary', identifier: 'test_role', uri: '/roles/1', permissions: { "canManageFact" => "1", "canListInvitationsInProject" => "1" }), GoodData::ProjectRole.create_object(title: 'Test Role 2', summary: 'Test role 2 summary', identifier: 'test_role_2', uri: '/roles/2', permissions: { "canManageFact" => "1" }) ] @domain_members = [ GoodData::Profile.create_object(login: '[email protected]', uri: '/uri/john_domain'), ] @members = [ GoodData::Membership.create(login: '[email protected]', uri: '/uri/john'), GoodData::Membership.create(login: '[email protected]', uri: '/uri/jane') ] end describe 'verify_user_to_add' do it 'Can handle case with user login when user is in the project' do # we have to provide users from project to be able to do this by login a, b = @p.verify_user_to_add('[email protected]', 'test_role', project_users: @members, roles: @roles) expect(a).to eq "/uri/john" expect(b).to eq ["/roles/1"] end it 'Can handle case with user uri when user is in the project' do # we have to provide users from project to be able to do this by login a, b = @p.verify_user_to_add('/uri/john', 'test_role', project_users: @members, roles: @roles) expect(a).to eq "/uri/john" expect(b).to eq ["/roles/1"] end it 'can handle case with info with uri when user is in the project' do # we have to provide users from project to be able to do this by login a, b = @p.verify_user_to_add({uri: '/uri/john', first_name: 'John'}, 'test_role', project_users: @members, roles: @roles) expect(a).to eq "/uri/john" expect(b).to eq ["/roles/1"] end it 'can handle case with info with login when he is in the project' do # we have to provide users from project to be able to do this by login a, b = @p.verify_user_to_add({ login: '[email protected]', first_name: 'John' }, 'test_role', project_users: @members, roles: @roles) expect(a).to eq "/uri/john" expect(b).to eq ["/roles/1"] end it 'can handle case with member when he is in the project' do # we have to provide users from project to be able to do this by login a, b = @p.verify_user_to_add(@members.first, 'test_role_2', project_users: @members, roles: @roles) expect(a).to eq "/uri/john" expect(b).to eq ["/roles/2"] end it 'can handle case with profile when the user is in the project' do # we have to provide users from project to be able to do this by login a, b = @p.verify_user_to_add(@domain_members.first, 'test_role_2', project_users: @members, roles: @roles) expect(a).to eq "/uri/john_domain" expect(b).to eq ["/roles/2"] end it 'Can handle case with user login when user is in the domain' do # we have to provide users from project to be able to do this by login a, b = @p.verify_user_to_add('[email protected]', 'test_role', project_users: [], domain_users: @domain_members, roles: @roles, domain: @domain) expect(a).to eq "/uri/john_domain" expect(b).to eq ["/roles/1"] end it 'Can handle case with user uri when user is in the domain' do # we have to provide users from project to be able to do this by login a, b = @p.verify_user_to_add('/uri/john_domain', 'test_role', project_users: [], domain_users: @domain_members, roles: @roles, domain: @domain) expect(a).to eq "/uri/john_domain" expect(b).to eq ["/roles/1"] end it 'can handle case with info with uri when user is in the domain' do # we have to provide users from project to be able to do this by login a, b = @p.verify_user_to_add({uri: '/uri/john_domain', first_name: 'John'}, 'test_role', project_users: [], domain_users: @domain_members, roles: @roles, domain: @domain) expect(a).to eq "/uri/john_domain" expect(b).to eq ["/roles/1"] end it 'can handle case with info with login when he is in the domain' do # we have to provide users from project to be able to do this by login a, b = @p.verify_user_to_add({ login: '[email protected]', first_name: 'John' }, 'test_role', project_users: [], domain_users: @domain_members, roles: @roles, domain: @domain) expect(a).to eq "/uri/john_domain" expect(b).to eq ["/roles/1"] end it 'can handle case with member when he is in the domain' do # we have to provide users from project to be able to do this by login a, b = @p.verify_user_to_add(@domain_members.first, 'test_role_2', project_users: [], domain_users: @domain_members, roles: @roles, domain: @domain) expect(a).to eq "/uri/john_domain" expect(b).to eq ["/roles/2"] end it 'can handle case with profile when the user is in the domain' do # we have to provide users from project to be able to do this by login a, b = @p.verify_user_to_add(@domain_members.first, 'test_role_2', project_users: [], domain_users: @domain_members, roles: @roles) expect(a).to eq "/uri/john_domain" expect(b).to eq ["/roles/2"] end end end
49.658537
195
0.601343
ac5e98b6de224fb71fdb5ba9e9e052cb618b9456
19,904
=begin #Ahello REST API documentation #На данной странице вы можете выполнять запросы к API, для этого необходимо указать 'appId', который был передан вам сотрудниками тех. поддержки в поле api_key. Укажите также PartnerUserId (это CRM Id пользователя или его email ), partnerUserId передается в заголовке запроса. Важно!!! ApiKeys-аутентификация c указанием только ключа appId в ближайшее время будет работать только для данной страницы документации. Для реальных сценариев интеграции необходимо использовать HMAC-аутентификацию. В ближайшее время появится раздел помощи по основным вопросам работы с API OpenAPI spec version: v1 Contact: [email protected] Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.4.16 =end require 'uri' module AktionClient class StopListApiApi attr_accessor :api_client def initialize(api_client = ApiClient.default) @api_client = api_client end # Закрепляет существующего свободного клиента в стоп-лист # @param bind_model # @param [Hash] opts the optional parameters # @return [StopList] def stop_list_api_bind(bind_model, opts = {}) data, _status_code, _headers = stop_list_api_bind_with_http_info(bind_model, opts) data end # Закрепляет существующего свободного клиента в стоп-лист # @param bind_model # @param [Hash] opts the optional parameters # @return [Array<(StopList, Fixnum, Hash)>] StopList data, response status code and response headers def stop_list_api_bind_with_http_info(bind_model, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: StopListApiApi.stop_list_api_bind ...' end # verify the required parameter 'bind_model' is set if @api_client.config.client_side_validation && bind_model.nil? fail ArgumentError, "Missing the required parameter 'bind_model' when calling StopListApiApi.stop_list_api_bind" end # resource path local_var_path = '/stoplist/bind' # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json', 'text/json', 'application/xml', 'text/xml']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'text/json', 'application/xml', 'text/xml', 'application/x-www-form-urlencoded']) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(bind_model) auth_names = [] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'StopList') if @api_client.config.debugging @api_client.config.logger.debug "API called: StopListApiApi#stop_list_api_bind\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Создает нового клиента и закрепляет в стоп-лист # @param bind_model # @param [Hash] opts the optional parameters # @return [StopList] def stop_list_api_bind_new_customer(bind_model, opts = {}) data, _status_code, _headers = stop_list_api_bind_new_customer_with_http_info(bind_model, opts) data end # Создает нового клиента и закрепляет в стоп-лист # @param bind_model # @param [Hash] opts the optional parameters # @return [Array<(StopList, Fixnum, Hash)>] StopList data, response status code and response headers def stop_list_api_bind_new_customer_with_http_info(bind_model, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: StopListApiApi.stop_list_api_bind_new_customer ...' end # verify the required parameter 'bind_model' is set if @api_client.config.client_side_validation && bind_model.nil? fail ArgumentError, "Missing the required parameter 'bind_model' when calling StopListApiApi.stop_list_api_bind_new_customer" end # resource path local_var_path = '/stoplist/bind/new' # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json', 'text/json', 'application/xml', 'text/xml']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'text/json', 'application/xml', 'text/xml', 'application/x-www-form-urlencoded']) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(bind_model) auth_names = [] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'StopList') if @api_client.config.debugging @api_client.config.logger.debug "API called: StopListApiApi#stop_list_api_bind_new_customer\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Изменяет менеджера спопровождения на СЛ # @param model # @param [Hash] opts the optional parameters # @return [nil] def stop_list_api_change_manager(model, opts = {}) stop_list_api_change_manager_with_http_info(model, opts) nil end # Изменяет менеджера спопровождения на СЛ # @param model # @param [Hash] opts the optional parameters # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def stop_list_api_change_manager_with_http_info(model, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: StopListApiApi.stop_list_api_change_manager ...' end # verify the required parameter 'model' is set if @api_client.config.client_side_validation && model.nil? fail ArgumentError, "Missing the required parameter 'model' when calling StopListApiApi.stop_list_api_change_manager" end # resource path local_var_path = '/stoplist/changemanager' # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'text/json', 'application/xml', 'text/xml', 'application/x-www-form-urlencoded']) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(model) auth_names = [] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) if @api_client.config.debugging @api_client.config.logger.debug "API called: StopListApiApi#stop_list_api_change_manager\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Получает информацию по кол-ву стоп-листов для действующих менеджеров # @param [Hash] opts the optional parameters # @option opts [String] :partner_id # @return [Array<ManagerWithStopListInfo>] def stop_list_api_get_managers_with_stop_list_info(opts = {}) data, _status_code, _headers = stop_list_api_get_managers_with_stop_list_info_with_http_info(opts) data end # Получает информацию по кол-ву стоп-листов для действующих менеджеров # @param [Hash] opts the optional parameters # @option opts [String] :partner_id # @return [Array<(Array<ManagerWithStopListInfo>, Fixnum, Hash)>] Array<ManagerWithStopListInfo> data, response status code and response headers def stop_list_api_get_managers_with_stop_list_info_with_http_info(opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: StopListApiApi.stop_list_api_get_managers_with_stop_list_info ...' end # resource path local_var_path = '/stoplist/bymanagers' # query parameters query_params = {} query_params[:'partnerId'] = opts[:'partner_id'] if !opts[:'partner_id'].nil? # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json', 'text/json', 'application/xml', 'text/xml']) # form parameters form_params = {} # http body (model) post_body = nil auth_names = [] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'Array<ManagerWithStopListInfo>') if @api_client.config.debugging @api_client.config.logger.debug "API called: StopListApiApi#stop_list_api_get_managers_with_stop_list_info\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Получает стоп-лист партнера # @param [Hash] opts the optional parameters # @option opts [String] :partner_id # @return [Array<StopList>] def stop_list_api_get_stop_lists(opts = {}) data, _status_code, _headers = stop_list_api_get_stop_lists_with_http_info(opts) data end # Получает стоп-лист партнера # @param [Hash] opts the optional parameters # @option opts [String] :partner_id # @return [Array<(Array<StopList>, Fixnum, Hash)>] Array<StopList> data, response status code and response headers def stop_list_api_get_stop_lists_with_http_info(opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: StopListApiApi.stop_list_api_get_stop_lists ...' end # resource path local_var_path = '/stoplist/list' # query parameters query_params = {} query_params[:'partnerId'] = opts[:'partner_id'] if !opts[:'partner_id'].nil? # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json', 'text/json', 'application/xml', 'text/xml']) # form parameters form_params = {} # http body (model) post_body = nil auth_names = [] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'Array<StopList>') if @api_client.config.debugging @api_client.config.logger.debug "API called: StopListApiApi#stop_list_api_get_stop_lists\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Получает настройки стоп-листа для партнера # @param [Hash] opts the optional parameters # @option opts [String] :partner_id # @return [StopListSettings] def stop_list_api_get_stop_lists_settings(opts = {}) data, _status_code, _headers = stop_list_api_get_stop_lists_settings_with_http_info(opts) data end # Получает настройки стоп-листа для партнера # @param [Hash] opts the optional parameters # @option opts [String] :partner_id # @return [Array<(StopListSettings, Fixnum, Hash)>] StopListSettings data, response status code and response headers def stop_list_api_get_stop_lists_settings_with_http_info(opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: StopListApiApi.stop_list_api_get_stop_lists_settings ...' end # resource path local_var_path = '/stoplist/settings' # query parameters query_params = {} query_params[:'partnerId'] = opts[:'partner_id'] if !opts[:'partner_id'].nil? # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json', 'text/json', 'application/xml', 'text/xml']) # form parameters form_params = {} # http body (model) post_body = nil auth_names = [] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'StopListSettings') if @api_client.config.debugging @api_client.config.logger.debug "API called: StopListApiApi#stop_list_api_get_stop_lists_settings\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Продлевает закрепление клиента в стоп-листе # @param stop_list_id # @param [Hash] opts the optional parameters # @return [StopList] def stop_list_api_prolong(stop_list_id, opts = {}) data, _status_code, _headers = stop_list_api_prolong_with_http_info(stop_list_id, opts) data end # Продлевает закрепление клиента в стоп-листе # @param stop_list_id # @param [Hash] opts the optional parameters # @return [Array<(StopList, Fixnum, Hash)>] StopList data, response status code and response headers def stop_list_api_prolong_with_http_info(stop_list_id, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: StopListApiApi.stop_list_api_prolong ...' end # verify the required parameter 'stop_list_id' is set if @api_client.config.client_side_validation && stop_list_id.nil? fail ArgumentError, "Missing the required parameter 'stop_list_id' when calling StopListApiApi.stop_list_api_prolong" end # resource path local_var_path = '/stoplist/prolong/{stopListId}'.sub('{' + 'stopListId' + '}', stop_list_id.to_s) # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json', 'text/json', 'application/xml', 'text/xml']) # form parameters form_params = {} # http body (model) post_body = nil auth_names = [] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'StopList') if @api_client.config.debugging @api_client.config.logger.debug "API called: StopListApiApi#stop_list_api_prolong\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Устанавливает лимит стоп-листов для партнерского менеджера. # Чтобы очистить лимит необходимо установить значение -1 # @param model # @param [Hash] opts the optional parameters # @return [nil] def stop_list_api_set_limit(model, opts = {}) stop_list_api_set_limit_with_http_info(model, opts) nil end # Устанавливает лимит стоп-листов для партнерского менеджера. # Чтобы очистить лимит необходимо установить значение -1 # @param model # @param [Hash] opts the optional parameters # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def stop_list_api_set_limit_with_http_info(model, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: StopListApiApi.stop_list_api_set_limit ...' end # verify the required parameter 'model' is set if @api_client.config.client_side_validation && model.nil? fail ArgumentError, "Missing the required parameter 'model' when calling StopListApiApi.stop_list_api_set_limit" end # resource path local_var_path = '/stoplist/limit' # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'text/json', 'application/xml', 'text/xml', 'application/x-www-form-urlencoded']) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(model) auth_names = [] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) if @api_client.config.debugging @api_client.config.logger.debug "API called: StopListApiApi#stop_list_api_set_limit\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Открепляет клиента из стоп-листа # @param stop_list_id # @param [Hash] opts the optional parameters # @return [StopList] def stop_list_api_un_bind(stop_list_id, opts = {}) data, _status_code, _headers = stop_list_api_un_bind_with_http_info(stop_list_id, opts) data end # Открепляет клиента из стоп-листа # @param stop_list_id # @param [Hash] opts the optional parameters # @return [Array<(StopList, Fixnum, Hash)>] StopList data, response status code and response headers def stop_list_api_un_bind_with_http_info(stop_list_id, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: StopListApiApi.stop_list_api_un_bind ...' end # verify the required parameter 'stop_list_id' is set if @api_client.config.client_side_validation && stop_list_id.nil? fail ArgumentError, "Missing the required parameter 'stop_list_id' when calling StopListApiApi.stop_list_api_un_bind" end # resource path local_var_path = '/stoplist/unbind/{stopListId}'.sub('{' + 'stopListId' + '}', stop_list_id.to_s) # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json', 'text/json', 'application/xml', 'text/xml']) # form parameters form_params = {} # http body (model) post_body = nil auth_names = [] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'StopList') if @api_client.config.debugging @api_client.config.logger.debug "API called: StopListApiApi#stop_list_api_un_bind\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end end end
42.439232
568
0.689761
e27155c637b4d4f05760c8f962b175b7b1965b4e
125
name 'glance-server' description 'OpenStack glance service' run_list( 'role[glance-api]', 'role[glance-registry]', )
17.857143
38
0.704
6a51173955d2ceda95e787146c8d4b09c26d99cf
781
module Algs4ruby class Stack class LinkedList include Enumerable Node = Struct.new(:item, :next) attr_accessor :first, :size def initialize @size = 0 end def push(item) node = Node.new(item, first) self.first = node self.size += 1 nil end def pop raise 'Pop on empty stack' unless first item = first.item self.first = first.next self.size -= 1 item end def empty? first.nil? end def each return to_enum(:each) unless block_given? pointer = first size.times do yield pointer.item pointer = pointer.next end end end end end
16.270833
49
0.507042
bbd7cd0b3ac99d2a7411595a32368186c64c4b27
3,846
require 'capybara/poltergeist' require 'rspec/expectations' require 'capybara/rspec' require 'open-uri' module Scrape456 # Given a username and password, retrieves all event attendee data from 123Signup. # # Usage: # # csv_result = Scrape456::Download.new( # username: ENV['LOGIN_USER_1'], # password: ENV['LOGIN_PASSWORD_1'] # ).call # # puts csv_result class Download include ::RSpec::Matchers include ::Capybara::RSpecMatchers LOGIN_URL = 'https://redirect.123signup.com/login' ONLOAD_REDIRECT_XPATH = "//body[contains(@onload,'pageLoadRedirect')]" # Machine-generated: pulled from Firefox dev tools. But it works, where my # handcrafted XPath did not. REPORT_TAB_LINK_CSS_SELECTOR = 'body > form:nth-child(1) > table:nth-child(3) > ' + 'tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(2) > table:nth-child(1) > ' + 'tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(7) > a:nth-child(1)' THIRTY_SECONDS = 30 def initialize(username:, password:) @username = username @password = password set_up_capybara end def set_up_capybara options = {phantomjs_options: ['--ssl-protocol=any']} Capybara.register_driver :poltergeist do |app| Capybara::Poltergeist::Driver.new(app, options) end Capybara.current_driver = :poltergeist Capybara.javascript_driver = :poltergeist Capybara.run_server = false Capybara.default_max_wait_time = THIRTY_SECONDS end def log_in session.visit LOGIN_URL session.fill_in 'username', with: @username session.fill_in 'password', with: @password session.click_link 'SignInButton' end def session Capybara.current_session end def extract_redirect_url onload_value = session.find('body')['onload'] lines = onload_value.split(';') redirect_destination_abs_path = lines.grep(/pageLoadRedirect/).first.sub(/^.*"([^"]*)".*$/, '\1') session.current_host + redirect_destination_abs_path end def fetch_csv_response_body session.assert_selector('body') expect(session.find('body')).to ( have_text(/^SignupMemberID,/) ).or( match_xpath(ONLOAD_REDIRECT_XPATH) ) if session.find('body').matches_xpath?(ONLOAD_REDIRECT_XPATH) csv_url = extract_redirect_url session.visit(csv_url) STDERR.puts "Report generated by 123Signup. Fetching CSV..." csv_response_body = open(csv_url).read STDERR.puts "CSV found. First 10 lines:" STDERR.puts session.body.split("\n")[0..10].join("\n") else csv_response_body = session.body end csv_response_body end def extract_csv_from_full_response(full_response) strip_regex = /\A<html.*<pre[^>]*>(SignupMemberID,.*)<\/pre><\/body><\/html>\z/m full_response.sub(strip_regex, '\1') end def call csv_result = nil session = Capybara.current_session STDERR.puts 'Logging in to 123Signup...' log_in session.within_frame('FrameApplication') do session.within_frame('top_menu') do STDERR.puts 'Navigating to reports tab...' session.find(REPORT_TAB_LINK_CSS_SELECTOR).click end session.within_frame('contents') do session.within_frame('MenuList') do STDERR.puts 'Navigating to event reports...' session.click_link 'Event Reports' end session.within_frame('Results') do session.click_link('Event Attendee Data') session.click_button 'BottomDownloadReport' STDERR.puts 'Waiting on report download...' csv_result = extract_csv_from_full_response(fetch_csv_response_body) end end end csv_result end end end
31.785124
103
0.654446
fffb97fdb2d81b63819a12266bd32f4a88d2a452
2,288
describe Spaceship::TunesClient do describe '#login' do it 'raises an exception if authentication failed' do expect do subject.login('bad-username', 'bad-password') end.to raise_exception(Spaceship::Client::InvalidUserCredentialsError, "Invalid username and password combination. Used 'bad-username' as the username.") end end describe 'client' do it 'exposes the session cookie' do begin subject.login('bad-username', 'bad-password') rescue Spaceship::Client::InvalidUserCredentialsError expect(subject.cookie).to eq('session=invalid') end end end describe "Logged in" do subject { Spaceship::Tunes.client } let(:username) { '[email protected]' } let(:password) { 'so_secret' } before do Spaceship::Tunes.login(username, password) end it 'stores the username' do expect(subject.user).to eq('[email protected]') end it "#hostname" do expect(subject.class.hostname).to eq('https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/') end describe "#handle_itc_response" do it "raises an exception if something goes wrong" do data = JSON.parse(TunesStubbing.itc_read_fixture_file('update_app_version_failed.json'))['data'] expect do subject.handle_itc_response(data) end.to raise_error("[German]: The App Name you entered has already been used. [English]: The App Name you entered has already been used. You must provide an address line. There are errors on the page and for 2 of your localizations.") end it "does nothing if everything works as expected and returns the original data" do data = JSON.parse(TunesStubbing.itc_read_fixture_file('update_app_version_success.json'))['data'] expect(subject.handle_itc_response(data)).to eq(data) end it "identifies try again later responses" do data = JSON.parse(TunesStubbing.itc_read_fixture_file('update_app_version_temporarily_unable.json'))['data'] expect do subject.handle_itc_response(data) end.to raise_error(Spaceship::TunesClient::ITunesConnectTemporaryError, "We're temporarily unable to save your changes. Please try again later.") end end end end
38.779661
242
0.702797
4a9db404d0e3c8fe75f6de5c8233828cf8b1e19c
8,205
require_relative "rexml_test_utils" require 'rexml/sax2listener' require 'rexml/parsers/sax2parser' require 'rexml/document' class SAX2Tester < Test::Unit::TestCase include REXMLTestUtils include REXML def test_characters d = Document.new( "<A>@blah@</A>" ) txt = d.root.text p = Parsers::SAX2Parser.new "<A>@blah@</A>" p.listen(:characters) {|x| assert_equal txt, x} p.listen(:characters, ["A"]) {|x| assert_equal txt,x} p.parse end def test_entity_replacement source = '<!DOCTYPE foo [ <!ENTITY la "1234"> <!ENTITY lala "--&la;--"> <!ENTITY lalal "&la;&la;"> ]><a><la>&la;</la><lala>&lala;</lala></a>' sax = Parsers::SAX2Parser.new( source ) results = [] sax.listen(:characters) {|x| results << x } sax.parse assert_equal 2, results.size assert_equal '1234', results[0] assert_equal '--1234--', results[1] end def test_sax2 f = File.new(fixture_path("documentation.xml")) parser = Parsers::SAX2Parser.new( f ) # Listen to all events on the following elements count = 0 blok = proc { |uri,localname,qname,attributes| assert %w{ bugs todo }.include?(localname), "Mismatched name; we got '#{qname}'\nArgs were:\n\tURI: #{uri}\n\tLOCALNAME: #{localname}\n\tQNAME: #{qname}\n\tATTRIBUTES: #{attributes.inspect}\n\tSELF=#{blok}" count += 1 } start_document = 0 end_document = 0 parser.listen( :start_document ) { start_document += 1 } parser.listen( :end_document ) { end_document += 1 } parser.listen( :start_element, %w{ changelog bugs todo }, &blok ) # Listen to all events on the following elements. Synonymous with # listen( :start_element, %w{ ... } ) parser.listen( %w{ changelog bugs todo }, &blok ) # Listen for all start element events parser.listen( :start_element ) { |uri,localname,qname,attributes| } listener = MySAX2Listener.new # Listen for all events parser.listen( listener ) # Listen for all events on the given elements. Does not include children # events. Regular expressions work as well! parser.listen( %w{ /change/ bugs todo }, listener ) # Test the deafening method blok = proc { |uri,localname,qname,attributes| assert_fail "This listener should have been deafened!" } parser.listen( %w{ changelog }, &blok ) parser.deafen( &blok ) tc = 0 parser.listen( :characters, %w{version} ) {|text| assert(text=~/@ANT_VERSION@/, "version was '#{text}'") tc += 1 } begin parser.parse rescue => exception if exception.kind_of? Test::Unit::AssertionFailedError raise exception end puts $! puts exception.backtrace end assert_equal 2, count assert_equal 1, tc assert_equal 1, start_document assert_equal 1, end_document end # used by test_simple_doctype_listener # submitted by Jeff Barczewski class SimpleDoctypeListener include REXML::SAX2Listener attr_reader :name, :pub_sys, :long_name, :uri def initialize @name = @pub_sys = @long_name = @uri = nil end def doctype(name, pub_sys, long_name, uri) @name = name @pub_sys = pub_sys @long_name = long_name @uri = uri end end # test simple non-entity doctype in sax listener # submitted by Jeff Barczewski def test_simple_doctype_listener xml = <<-END <?xml version="1.0"?> <!DOCTYPE greeting PUBLIC "Hello Greeting DTD" "http://foo/hello.dtd"> <greeting>Hello, world!</greeting> END parser = Parsers::SAX2Parser.new(xml) dtl = SimpleDoctypeListener.new parser.listen(dtl) tname = nil tpub_sys = nil tlong_name = nil turi = nil parser.listen(:doctype) do |name, pub_sys, long_name, uri| tname = name tpub_sys = pub_sys tlong_name = long_name turi = uri end parser.parse assert_equal 'greeting', tname, 'simple doctype block listener failed - incorrect name' assert_equal 'PUBLIC', tpub_sys, 'simple doctype block listener failed - incorrect pub_sys' assert_equal 'Hello Greeting DTD', tlong_name, 'simple doctype block listener failed - incorrect long_name' assert_equal 'http://foo/hello.dtd', turi, 'simple doctype block listener failed - incorrect uri' assert_equal 'greeting', dtl.name, 'simple doctype listener failed - incorrect name' assert_equal 'PUBLIC', dtl.pub_sys, 'simple doctype listener failed - incorrect pub_sys' assert_equal 'Hello Greeting DTD', dtl.long_name, 'simple doctype listener failed - incorrect long_name' assert_equal 'http://foo/hello.dtd', dtl.uri, 'simple doctype listener failed - incorrect uri' end # test doctype with missing name, should throw ParseException # submitted by Jeff Barczewseki def test_doctype_with_mising_name_throws_exception xml = <<-END <?xml version="1.0"?> <!DOCTYPE > <greeting>Hello, world!</greeting> END parser = Parsers::SAX2Parser.new(xml) assert_raise(REXML::ParseException, 'doctype missing name did not throw ParseException') do parser.parse end end class KouListener include REXML::SAX2Listener attr_accessor :sdoc, :edoc attr_reader :selem, :decl, :pi def initialize @sdoc = @edoc = @selem = false @decl = 0 @pi = 0 end def start_document @sdoc = true end def end_document @edoc = true end def xmldecl( *arg ) @decl += 1 end def processing_instruction( *arg ) @pi += 1 end def start_element( *arg ) @selem = true end end # Submitted by Kou def test_begin_end_document parser = Parsers::SAX2Parser.new("<a/>") kl = KouListener.new parser.listen(kl) sd = false ed = false parser.listen(:start_document) { sd = true } parser.listen(:end_document) { ed = true } parser.parse assert( sd, ':start_document block failed' ) assert( ed, ':end_document block failed' ) assert( kl.sdoc, ':start_document listener failed' ) assert( kl.edoc, ':end_document listener failed' ) end # Submitted by Kou def test_listen_before_start # FIXME: the following comment should be a test for validity. (The xml declaration # is invalid). #parser = Parsers::SAX2Parser.new( "<?xml ?><?pi?><a><?pi?></a>") parser = Parsers::SAX2Parser.new( "<?xml version='1.0'?><?pi?><a><?pi?></a>") k1 = KouListener.new parser.listen( k1 ) xmldecl = false pi = 0 parser.listen( :xmldecl ) { xmldecl = true } parser.listen( :processing_instruction ) { pi += 1 } parser.parse assert( xmldecl, ':xmldecl failed' ) assert_equal( 2, pi, ':processing_instruction failed' ) assert( k1.decl, 'Listener for xmldecl failed' ) assert_equal( 2, k1.pi, 'Listener for processing instruction failed' ) end def test_socket require 'socket' server = TCPServer.new('127.0.0.1', 0) socket = TCPSocket.new('127.0.0.1', server.addr[1]) ok = false session = server.accept session << '<foo>' parser = REXML::Parsers::SAX2Parser.new(socket) Fiber.new do parser.listen(:start_element) do ok = true Fiber.yield end parser.parse end.resume assert(ok) end def test_char_ref_sax2() parser = REXML::Parsers::SAX2Parser.new('<ABC>&#252;</ABC>') result = nil parser.listen(:characters) {|text| result = text.unpack('U*')} parser.parse() assert_equal(1, result.size) assert_equal(252, result[0]) end def test_char_ref_dom() doc = REXML::Document.new('<ABC>&#252;</ABC>') result = doc.root.text.unpack('U*') assert_equal(1, result.size) assert_equal(252, result[0]) end class Ticket68 include REXML::SAX2Listener end def test_ticket_68 parser = REXML::Parsers::SAX2Parser.new(File.new(fixture_path('ticket_68.xml'))) parser.listen( Ticket68.new ) begin parser.parse rescue p parser.source.position p parser.source.current_line puts $!.backtrace.join("\n") flunk $!.message end end end class MySAX2Listener include REXML::SAX2Listener end
29.303571
168
0.650335
ed8a0860e407f85d399d754ae6fba206322acecb
1,222
require 'jshint' require 'jshint/reporters' namespace :jshint do desc "Runs JSHint, the JavaScript lint tool over this project's JavaScript assets" task :lint => :environment do |_, args| # Our own argument parsing, since rake jshint will push extra nil's. reporter_name = :Default file = nil reporter_name = args.extras[0] if args.extras.length >= 1 file = args.extras[1] if args.extras.length >= 2 linter = Jshint::Lint.new linter.lint reporter = Jshint::Reporters.const_get(reporter_name).new(linter.errors) printer = lambda do |stream| stream.puts reporter.report end if file Dir.mkdir(File.dirname(file)) File.open(file, 'w') do |stream| printer.call(stream) end else printer.call($stdout) end end desc "Copies the default JSHint options to your Rails application" task :install_config => :environment do source_file = File.join(Jshint.root, 'config', 'jshint.yml') source_dest = File.join(Rails.root, 'config', '') FileUtils.cp(source_file, source_dest) end task :all => [:lint] end desc "Runs JSHint, the JavaScript lint tool over this projects JavaScript assets" task :jshint => ["jshint:all"]
29.804878
84
0.684124
21876cbf25d23c910292431fddae7a5b5b6b2240
17,587
# frozen_string_literal: true module RailsCursorPagination # Use this Paginator class to effortlessly paginate through ActiveRecord # relations using cursor pagination. For more details on how this works, # read the top-level documentation of the `RailsCursorPagination` module. # # Usage: # RailsCursorPagination::Paginator # .new(relation, order_by: :author, first: 2, after: "WyJKYW5lIiw0XQ==") # .fetch # class Paginator # Generic error that gets raised when invalid parameters are passed to the # Paginator initializer class ParameterError < Error; end # Error that gets raised if a cursor given as `before` or `after` parameter # cannot be properly parsed class InvalidCursorError < ParameterError; end # Create a new instance of the `RailsCursorPagination::Paginator` # # @param relation [ActiveRecord::Relation] # Relation that will be paginated. # @param first [Integer, nil] # Number of records to return in a forward pagination. Can be combined # with `after`. # @param after [String, nil] # Cursor to paginate forward from. Can be combined with `first`. # @param last [Integer, nil] # Number of records to return. Must be used together with `before`. # @param before [String, nil] # Cursor to paginate upto (excluding). Can be combined with `last`. # @param order_by [Symbol, String, nil] # Column to order by. If none is provided, will default to ID column. # NOTE: this will cause the query to filter on both the given column as # well as the ID column. So you might want to add a compound index to your # database similar to: # ```sql # CREATE INDEX <index_name> ON <table_name> (<order_by_field>, id) # ``` # @param order [Symbol, nil] # Ordering to apply, either `:asc` or `:desc`. Defaults to `:asc`. # # @raise [RailsCursorPagination::Paginator::ParameterError] # If any parameter is not valid def initialize(relation, first: nil, after: nil, last: nil, before: nil, order_by: nil, order: nil) order_by ||= :id order ||= :asc ensure_valid_params!(relation, first, after, last, before, order) @order_field = order_by @order_direction = order @relation = relation @cursor = before || after @is_forward_pagination = before.blank? @page_size = first || last || RailsCursorPagination::Configuration.instance.default_page_size @memos = {} end # Get the paginated result, including the actual `page` with its data items # and cursors as well as some meta data in `page_info` and an optional # `total` of records across all pages. # # @param with_total [TrueClass, FalseClass] # @return [Hash] with keys :page, :page_info, and optional :total def fetch(with_total: false) { **(with_total ? { total: total } : {}), page_info: page_info, page: page } end private # Ensure that the parameters of this service are valid. Otherwise raise # a `RailsCursorPagination::Paginator::ParameterError`. # # @param relation [ActiveRecord::Relation] # Relation that will be paginated. # @param first [Integer, nil] # Optional, must be positive, cannot be combined with `last` # @param after [String, nil] # Optional, cannot be combined with `before` # @param last [Integer, nil] # Optional, must be positive, requires `before`, cannot be combined # with `first` # @param before [String, nil] # Optional, cannot be combined with `after` # @param order [Symbol] # Optional, must be :asc or :desc # # @raise [RailsCursorPagination::Paginator::ParameterError] # If any parameter is not valid def ensure_valid_params!(relation, first, after, last, before, order) unless relation.is_a?(ActiveRecord::Relation) raise ParameterError, 'The first argument must be an ActiveRecord::Relation, but was '\ "the #{relation.class} `#{relation.inspect}`" end unless %i[asc desc].include?(order) raise ParameterError, "`order` must be either :asc or :desc, but was `#{order}`" end if first.present? && last.present? raise ParameterError, '`first` cannot be combined with `last`' end if before.present? && after.present? raise ParameterError, '`before` cannot be combined with `after`' end if last.present? && before.blank? raise ParameterError, '`last` must be combined with `before`' end if first.present? && first.negative? raise ParameterError, "`first` cannot be negative, but was `#{first}`" end if last.present? && last.negative? raise ParameterError, "`last` cannot be negative, but was `#{last}`" end true end # Get meta information about the current page # # @return [Hash] def page_info { has_previous_page: previous_page?, has_next_page: next_page?, start_cursor: start_cursor, end_cursor: end_cursor } end # Get the records for the given page along with their cursors # # @return [Array<Hash>] List of hashes, each with a `cursor` and `data` def page memoize :page do records.map do |item| { cursor: cursor_for_record(item), data: item } end end end # Get the total number of records in the given relation # # @return [Integer] def total memoize(:total) { @relation.reorder('').size } end # Check if the pagination direction is forward # # @return [TrueClass, FalseClass] def paginate_forward? @is_forward_pagination end # Check if the user requested to order on a field different than the ID. If # a different field was requested, we have to change our pagination logic to # accommodate for this. # # @return [TrueClass, FalseClass] def custom_order_field? @order_field.downcase.to_sym != :id end # Check if there is a page before the current one. # # @return [TrueClass, FalseClass] def previous_page? if paginate_forward? # When paginating forward, we can only have a previous page if we were # provided with a cursor and there were records discarded after applying # this filter. These records would have to be on previous pages. @cursor.present? && filtered_and_sorted_relation.reorder('').size < total else # When paginating backwards, if we managed to load one more record than # requested, this record will be available on the previous page. records_plus_one.size > @page_size end end # Check if there is another page after the current one. # # @return [TrueClass, FalseClass] def next_page? if paginate_forward? # When paginating forward, if we managed to load one more record than # requested, this record will be available on the next page. records_plus_one.size > @page_size else # When paginating backward, if applying our cursor reduced the number # records returned, we know that the missing records will be on # subsequent pages. filtered_and_sorted_relation.reorder('').size < total end end # Load the correct records and return them in the right order # # @return [Array<ActiveRecord>] def records records = records_plus_one.first(@page_size) paginate_forward? ? records : records.reverse end # Apply limit to filtered and sorted relation that contains one item more # than the user-requested page size. This is useful for determining if there # is an additional page available without having to do a separate DB query. # Then, fetch the records from the database to prevent multiple queries to # load the records and count them. # # @return [ActiveRecord::Relation] def records_plus_one memoize :records_plus_one do filtered_and_sorted_relation.limit(@page_size + 1).load end end # Cursor of the first record on the current page # # @return [String, nil] def start_cursor return if page.empty? page.first[:cursor] end # Cursor of the last record on the current page # # @return [String, nil] def end_cursor return if page.empty? page.last[:cursor] end # Get the order we need to apply to our SQL query. In case we are paginating # backwards, this has to be the inverse of what the user requested, since # our database can only apply the limit to following records. In the case of # backward pagination, we then reverse the order of the loaded records again # in `#records` to return them in the right order to the user. # # Examples: # - first 2 after 4 ascending # -> SELECT * FROM table WHERE id > 4 ODER BY id ASC LIMIT 2 # - first 2 after 4 descending ^ as requested # -> SELECT * FROM table WHERE id < 4 ODER BY id DESC LIMIT 2 # but: ^ as requested # - last 2 before 4 ascending # -> SELECT * FROM table WHERE id < 4 ODER BY id DESC LIMIT 2 # - last 2 before 4 descending ^ reversed # -> SELECT * FROM table WHERE id > 4 ODER BY id ASC LIMIT 2 # ^ reversed # # @return [Symbol] Either :asc or :desc def pagination_sorting return @order_direction if paginate_forward? @order_direction == :asc ? :desc : :asc end # Get the right operator to use in the SQL WHERE clause for filtering based # on the given cursor. This is dependent on the requested order and # pagination direction. # # If we paginate forward and want ascending records, or if we paginate # backward and want descending records we need records that have a higher # value than our cursor. # # On the contrary, if we paginate forward but want descending records, or # if we paginate backwards and want ascending records, we need them to have # lower values than our cursor. # # Examples: # - first 2 after 4 ascending # -> SELECT * FROM table WHERE id > 4 ODER BY id ASC LIMIT 2 # - last 2 before 4 descending ^ records with higher value than cursor # -> SELECT * FROM table WHERE id > 4 ODER BY id ASC LIMIT 2 # but: ^ records with higher value than cursor # - first 2 after 4 descending # -> SELECT * FROM table WHERE id < 4 ODER BY id DESC LIMIT 2 # - last 2 before 4 ascending ^ records with lower value than cursor # -> SELECT * FROM table WHERE id < 4 ODER BY id DESC LIMIT 2 # ^ records with lower value than cursor # # @return [String] either '<' or '>' def filter_operator if paginate_forward? @order_direction == :asc ? '>' : '<' else @order_direction == :asc ? '<' : '>' end end # The value our relation is filtered by. This is either just the cursor's ID # if we use the default order, or it is the combination of the custom order # field's value and its ID, joined by a dash. # # @return [Integer, String] def filter_value return decoded_cursor_id unless custom_order_field? "#{decoded_cursor_field}-#{decoded_cursor_id}" end # Generate a cursor for the given record and ordering field. The cursor # encodes all the data required to then paginate based on it with the given # ordering field. # # If we only order by ID, the cursor doesn't need to include any other data. # But if we order by any other field, the cursor needs to include both the # value from this other field as well as the records ID to resolve the order # of duplicates in the non-ID field. # # @param record [ActiveRecord] Model instance for which we want the cursor # @return [String] def cursor_for_record(record) unencoded_cursor = if custom_order_field? [record[@order_field], record.id] else record.id end Base64.strict_encode64(unencoded_cursor.to_json) end # Decode the provided cursor. Either just returns the cursor's ID or in case # of pagination on any other field, returns a tuple of first the cursor # record's other field's value followed by its ID. # # @return [Integer, Array] def decoded_cursor memoize(:decoded_cursor) { JSON.parse(Base64.strict_decode64(@cursor)) } rescue ArgumentError, JSON::ParserError raise InvalidCursorError, "The given cursor `#{@cursor.inspect}` could not be decoded" end # Return the ID of the cursor's record. In case we use an ordering by ID, # this is all the data the cursor encodes. Otherwise, it's the second # element of the tuple encoded by the cursor. # # @return [Integer] def decoded_cursor_id return decoded_cursor unless decoded_cursor.is_a? Array decoded_cursor.last end # Return the value of the cursor's record's custom order field. Only exists # if the cursor was generated by a query with a custom order field. # Otherwise the cursor would only encode the ID and not be an array. # @raise [InvalidCursorError] in case the cursor is not a tuple # @return [Object] def decoded_cursor_field unless decoded_cursor.is_a? Array raise InvalidCursorError, "The given cursor `#{@cursor}` was decoded as "\ "`#{decoded_cursor.inspect}` but could not be parsed" end decoded_cursor.first end # Ensure that the relation has the ID column and any potential `order_by` # column selected. These are required to generate the record's cursor and # therefore it's crucial that they are part of the selected fields. # # @return [ActiveRecord::Relation] def relation_with_cursor_fields return @relation if @relation.select_values.blank? relation = @relation unless @relation.select_values.include?(:id) relation = relation.select(:id) end if custom_order_field? && [email protected]_values.include?(@order_field) relation = relation.select(@order_field) end relation end # The given relation with the right ordering applied. Takes custom order # columns as well as custom direction and pagination into account. # # @return [ActiveRecord::Relation] def sorted_relation unless custom_order_field? return relation_with_cursor_fields.reorder id: pagination_sorting.upcase end relation_with_cursor_fields .reorder(@order_field => pagination_sorting.upcase, id: pagination_sorting.upcase) end # Return a properly escaped reference to the ID column prefixed with the # table name. This prefixing is important in case of another model having # been joined to the passed relation. # # @return [String (frozen)] def id_column escaped_table_name = @relation.quoted_table_name escaped_id_column = @relation.connection.quote_column_name(:id) "#{escaped_table_name}.#{escaped_id_column}".freeze end # Applies the filtering based on the provided cursor and order column to the # sorted relation. # # In case a custom `order_by` field is provided, we have to filter based on # this field and the ID column to ensure reproducible results. # # To better understand this, let's consider our example with the `posts` # table. Say that we're paginating forward and add `order_by: :author` to # the call, and if the cursor that is passed encodes `['Jane', 4]`. In this # case we will have to select all posts that either have an author whose # name is alphanumerically greater than 'Jane', or if the author is 'Jane' # we have to ensure that the post's ID is greater than `4`. # # So our SQL WHERE clause needs to be something like: # WHERE author > 'Jane' OR author = 'Jane' AND id > 4 # # @return [ActiveRecord::Relation] def filtered_and_sorted_relation memoize :filtered_and_sorted_relation do next sorted_relation if @cursor.blank? unless custom_order_field? next sorted_relation.where "#{id_column} #{filter_operator} ?", decoded_cursor_id end sorted_relation .where("#{@order_field} #{filter_operator} ?", decoded_cursor_field) .or( sorted_relation .where("#{@order_field} = ?", decoded_cursor_field) .where("#{id_column} #{filter_operator} ?", decoded_cursor_id) ) end end # Ensures that given block is only executed exactly once and on subsequent # calls returns result from first execution. Useful for memoizing methods. # # @param key [Symbol] # Name or unique identifier of the method that is being memoized # @yieldreturn [Object] # @return [Object] Whatever the block returns def memoize(key, &_block) return @memos[key] if @memos.key?(key) @memos[key] = yield end end end
36.412008
80
0.64633
62b727ab7d8abc88b0a5f820a9dfedafd032dfa8
298
# encoding: UTF-8 class Tuneinstructor < Cask version '3.4' sha256 '7909eeaf0b3cbe41c511f2c450a6249c9d8a311a482547cf8fc11537b11ecbd4' url 'http://www.tune-instructor.de/_data/TuneInstructor3.4b.dmg' homepage 'http://www.tune-instructor.de/com/start.html' link 'Tune•Instructor.app' end
27.090909
75
0.778523
9198235286ef03c87032f9ee3c572e1e6f65f4ab
1,544
class Libdca < Formula desc "Library for decoding DTS Coherent Acoustics streams" homepage "https://www.videolan.org/developers/libdca.html" url "https://download.videolan.org/pub/videolan/libdca/0.0.7/libdca-0.0.7.tar.bz2" sha256 "3a0b13815f582c661d2388ffcabc2f1ea82f471783c400f765f2ec6c81065f6a" license "GPL-2.0" livecheck do url "https://download.videolan.org/pub/videolan/libdca/" regex(%r{href=.*?v?(\d+(?:\.\d+)+)[/"'>]}i) end bottle do cellar :any sha256 "123d7863f98b6fc1f56aaca440db706764b43c99fe1a5bd5286badf160f76d62" => :big_sur sha256 "d20b5e52384fcbb0da4501eb109e3aac6be3eb6f0e6a8f09de0c61b2f3c83361" => :arm64_big_sur sha256 "d9c4b3a350744867f5782db738d25d1212b9be89449030492083364574f914d7" => :catalina sha256 "594d6b26eb3ca16c3046ff2792de4f78a0f038dc94b1972c8827e86331a46fde" => :mojave sha256 "f8ba469ce443efa0e9fc87b51a87c6b4d510bd3e7bb91ae11d1f91e99f760acc" => :high_sierra sha256 "1f2d4aca102b49593d3ba3c31794f44e25e2b1d03686d4bf9d38f39fc3784436" => :x86_64_linux end depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build def install # Fixes "duplicate symbol ___sputc" error when building with clang # https://github.com/Homebrew/homebrew/issues/31456 ENV.append_to_cflags "-std=gnu89" system "autoreconf", "-fiv" system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make" system "make", "install" end end
39.589744
95
0.740285
ff876a25c94a16f32e74d36284fd7b34b7f730e0
1,507
require 'optparse' module Bini # An extension of [OptionParser] that behaves like a hash, with saving, loading, and # mashing in other hashs. class OptionParser < ::OptionParser def initialize super @options = {} on("-V", "--version", "Print version") { |version| @options[:version] = true} end # Parse out ARGV, includes a catch for returning version, otherwise just calls super. def parse!(*argv) super if Options[:version] && Bini.version puts Bini.version # don't exit if RSpec is around, we are in a testing environment. exit 0 if !Object.constants.include? :RSpec end end # These are the hash like bits. # Clear the contents of the builtin Hash. def clear @options.clear end # Get results from the builtin in Hash. # @param [Symbol,String,nil] key Either a single key or nil for the entire hash. # @return [Hash] a hash, empty or otherwise. def [](key = nil) return @options[key] if key return @options if @options.any? {} end # Set a key/value pair in the buildin Hash. def []=(k,v) @options[k] = v end # merge takes in a set of values and overwrites the previous values. # mash does this in reverse. def mash(h) h.merge! @options @options.clear h.each {|k,v| self[k] = v} end end # An automatically created entry point into the OptionParser class. Options = Bini::OptionParser.new end
25.982759
89
0.628401
5d8bb42a8462f74a982518a0a000d5fa9f335960
1,757
# This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # This file is the source Rails uses to define your schema when running `rails # db:schema:load`. When creating a new database, `rails db:schema:load` tends to # be faster and is potentially less error prone than running all of your # migrations from scratch. Old migrations may fail to apply correctly if those # migrations use external dependencies or application code. # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 2021_02_03_012448) do create_table "projects", force: :cascade do |t| t.string "name" t.string "contractor" t.text "description" t.datetime "date" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "tasks", force: :cascade do |t| t.string "item" t.float "price" t.integer "user_id", null: false t.integer "project_id", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.index ["project_id"], name: "index_tasks_on_project_id" t.index ["user_id"], name: "index_tasks_on_user_id" end create_table "users", force: :cascade do |t| t.string "username" t.string "email" t.string "password_digest" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.string "uid" end add_foreign_key "tasks", "projects" add_foreign_key "tasks", "users" end
37.382979
86
0.723392
e8eb3333b88e1e533a3e9e424aa80b726a2d6bcf
3,008
# frozen_string_literal: true require 'spec_helper' RSpec.describe Gitlab::Ci::Pipeline::Chain::Sequence do let_it_be(:project) { create(:project) } let_it_be(:user) { create(:user) } let(:pipeline) { build_stubbed(:ci_pipeline) } let(:command) { Gitlab::Ci::Pipeline::Chain::Command.new(project: project) } let(:first_step) { spy('first step', name: 'FirstStep') } let(:second_step) { spy('second step', name: 'SecondStep') } let(:sequence) { [first_step, second_step] } let(:histogram) { spy('prometheus metric') } subject do described_class.new(pipeline, command, sequence) end context 'when one of steps breaks the chain' do before do allow(first_step).to receive(:break?).and_return(true) end it 'does not process the second step' do subject.build! expect(second_step).not_to have_received(:perform!) end it 'returns a pipeline object' do expect(subject.build!).to eq pipeline end end context 'when all chains are executed correctly' do before do sequence.each do |step| allow(step).to receive(:break?).and_return(false) end end it 'iterates through entire sequence' do subject.build! expect(first_step).to have_received(:perform!) expect(second_step).to have_received(:perform!) end it 'returns a pipeline object' do expect(subject.build!).to eq pipeline end it 'adds sequence duration to duration histogram' do allow(command.metrics) .to receive(:pipeline_creation_duration_histogram) .and_return(histogram) subject.build! expect(histogram).to have_received(:observe) end it 'adds step sequence duration to duration histogram' do expect(command.metrics) .to receive(:pipeline_creation_step_duration_histogram) .twice .and_return(histogram) expect(histogram).to receive(:observe).with({ step: 'FirstStep' }, any_args).ordered expect(histogram).to receive(:observe).with({ step: 'SecondStep' }, any_args).ordered subject.build! end it 'records pipeline size by pipeline source in a histogram' do allow(command.metrics) .to receive(:pipeline_size_histogram) .and_return(histogram) subject.build! expect(histogram).to have_received(:observe) .with({ source: 'push' }, 0) end it 'records active jobs by pipeline plan in a histogram' do allow(command.metrics) .to receive(:active_jobs_histogram) .and_return(histogram) pipeline = create(:ci_pipeline, project: project, status: :running) create(:ci_build, :finished, project: project, pipeline: pipeline) create(:ci_build, :failed, project: project, pipeline: pipeline) create(:ci_build, :running, project: project, pipeline: pipeline) subject.build! expect(histogram).to have_received(:observe) .with(hash_including(plan: project.actual_plan_name), 3) end end end
29.490196
91
0.676529
33df41e3a43ca913fc17ca564f42d35088f32060
658
class Keyword < ActiveRecord::Base attr_accessible :keyword validates :keyword, presence: true has_many :keyword_data def self.topN(n) end def self.search(query) end def self.sorted(field) end def self.create_or_update(keyword, data) keyword_id = Keyword.find_or_create_by_name(keyword: keyword) collected_at = Date.today.at_midnight keyword_data_object = KeywordData .find_or_initialize_by_keyword_id_and_collected_at( keyword_id, collected_at ) keyword_data_object.update_attributes({ keyword_id: keyword_id, data: data, collected_at: collected_at }) end end
18.8
65
0.712766