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
|
---|---|---|---|---|---|
18dbe921b2cd8cdcebbbe7d19bd3e8fbdbb84a89 | 56 | def self.foo
7.77
end
def self.bar
8.88
end
| 7 | 13 | 0.571429 |
79e3dd6fc5e87a4f16980b5efac8307f7d7256f4 | 909 | # frozen_string_literal: true
module NumbersAndWords
module Strategies
module FiguresConverter
module Decorators
module PtBr
class Fractional < Base
def run
"#{super} #{fraction_significance}"
end
private
def fraction_significance
@strategy.translations.micros full_fraction.fraction_capacity, figures.join.to_i
end
def full_fraction
(0..zero_length).inject(figures.clone) { |result, _el| result.unshift 0 }.to_figures
end
def figures
@strategy.figures.reverse
end
def zero_length
fraction_length - figures.length
end
def fraction_length
@options[:fractional][:length].to_i
end
end
end
end
end
end
end
| 22.725 | 98 | 0.546755 |
335eb175b2d5409bc970463801e62ca48f6880df | 2,025 | # encoding: UTF-8
module Cantor
# @private
NullSet = Class.new(RelativeSet) do
def initialize
end
# @return [NullSet]
def build
self
end
# Yields each element in the set to the implicit block argument. Since
# there are no elements, the block is never executed
#
# @return [void]
def each
end
# Returns an {Array} containing each element in this set. Since there are
# no elements, the {Array} is empty
#
# @return [Array]
def to_a
[]
end
# @return false
def include?(other)
false
end
# @return true
def finite?
true
end
# @return [Set] other
def replace(other)
Cantor.build(other)
end
# @return 0
def size
0
end
# @return true
def empty?
true
end
# @group Set Operations
#########################################################################
# @return self
def map
self
end
# @return self
def select
self
end
# @return self
def reject
self
end
# @return UniversalSet
def complement
# ¬∅ = U
UniversalSet.build
end
# @return self
def intersection(other)
# ∅ ∩ A = ∅
self
end
# @return [Set] other
def union(other)
# ∅ ∪ A = A
Cantor.build(other)
end
# @return self
def difference(other)
# ∅ ∖ A = A
self
end
# @return [Set] other
def symmetric_difference(other)
# ∅ ⊖ A = A
Cantor.build(other)
end
# @group Set Ordering
#########################################################################
def ==(other)
eql?(other) or other.empty?
end
# @group Pretty Printing
#########################################################################
# @return [String]
def inspect
"NullSet"
end
# @endgroup
#########################################################################
end.new
end
| 16.330645 | 77 | 0.454321 |
33e5f4b29cfb83d5bcfd597e9f8bd010a28f7a36 | 2,037 | class Libgit2 < Formula
desc "C library of Git core methods that is re-entrant and linkable"
homepage "https://libgit2.github.com/"
url "https://github.com/libgit2/libgit2/archive/v0.27.5.tar.gz"
sha256 "15f2775f4f325951d9139ed906502b6c71fee6787cada9b045f5994072ccbd33"
head "https://github.com/libgit2/libgit2.git"
bottle do
cellar :any
sha256 "8669d420d0fd404a381601bea44e80b5987c24c657b03540e2dca897cedb04d4" => :mojave
sha256 "19b5bdc78b9020da2a149301d52db2b65d3fa906ef423c84e0f2eafd7321c21c" => :high_sierra
sha256 "b6b6492e018c515482ed97e23c75d1abc2b3a5ab47e7e39be9c4de04b1842046" => :sierra
end
depends_on "cmake" => :build
depends_on "pkg-config" => :build
depends_on "openssl" if MacOS.version <= :lion # Uses SecureTransport on >10.7
depends_on "libssh2" => :recommended
def install
args = std_cmake_args
args << "-DBUILD_EXAMPLES=YES"
args << "-DBUILD_CLAR=NO" # Don't build tests.
args << "-DUSE_SSH=NO" if build.without? "libssh2"
mkdir "build" do
system "cmake", "..", *args
system "make", "install"
cd "examples" do
(pkgshare/"examples").install "add", "blame", "cat-file", "cgit2",
"describe", "diff", "for-each-ref",
"general", "init", "log", "remote",
"rev-list", "rev-parse", "showindex",
"status", "tag"
end
system "make", "clean"
system "cmake", "..", "-DBUILD_SHARED_LIBS=OFF", *args
system "make"
lib.install "libgit2.a"
end
end
test do
(testpath/"test.c").write <<~EOS
#include <git2.h>
int main(int argc, char *argv[]) {
int options = git_libgit2_features();
return 0;
}
EOS
libssh2 = Formula["libssh2"]
flags = %W[
-I#{include}
-I#{libssh2.opt_include}
-L#{lib}
-lgit2
]
system ENV.cc, "test.c", "-o", "test", *flags
system "./test"
end
end
| 32.333333 | 93 | 0.600393 |
d5750390f81ad9f701f83a2fb96893be38272437 | 872 | name 'aws-parallelcluster'
maintainer 'Amazon Web Services'
maintainer_email ''
license 'Apache-2.0'
description 'Installs/Configures AWS ParallelCluster'
long_description 'Installs/Configures AWS ParallelCluster'
issues_url 'https://github.com/aws/aws-parallelcluster-cookbook/issues'
source_url 'https://github.com/aws/aws-parallelcluster-cookbook'
chef_version '14.2.0'
version '2.3.1'
supports 'amazon'
supports 'centos', '= 6'
supports 'centos', '= 7'
supports 'ubuntu', '= 14.04'
supports 'ubuntu', '= 16.04'
depends 'build-essential', '~> 8.1.1'
depends 'poise-python', '~> 1.7.0'
depends 'tar', '~> 2.1.1'
depends 'selinux', '~> 2.1.0'
depends 'nfs', '~> 2.5.1'
depends 'sysctl', '~> 1.0.5'
depends 'yum', '~> 5.1.0'
depends 'yum-epel', '~> 3.1.0'
depends 'openssh', '~> 2.6.3'
depends 'apt', '~> 7.0.0'
depends 'hostname', '~> 0.4.2'
depends 'line', '~> 1.0.6'
| 29.066667 | 71 | 0.680046 |
e9820011e9041988eccedeec8172981a04d79d83 | 1,612 | module MinispadeRails
class DirectiveProcessor < Sprockets::DirectiveProcessor
def process_source
super
if @spades
output = @spades.map do |spade|
# Create a custom context for the spade require
attributes = context.environment.attributes_for(spade)
spade_context = context.environment.context_class.new(context.environment, attributes.logical_path, spade)
# Add the minispade custom processor as the last item
processors = [ *attributes.processors, MinispadeRails::Compiler ]
# Remove the directive processors for the individual file
processors.delete(Sprockets::DirectiveProcessor)
# Evaluate the spade
spade_context.evaluate(spade, :processors => processors)
end
# Prepend the requires
@result = output.join("") + @result
end
@result
end
def process_require_spade_directive(path = ".")
if relative?(path)
root = pathname.dirname.join(path).expand_path
unless (stats = stat(root)) && stats.directory?
raise ArgumentError, "require_spade argument must be a directory"
end
context.depend_on(root)
@spades ||= []
each_entry(root) do |pathname|
if context.asset_requirable?(pathname)
context.depend_on pathname
@spades << pathname
end
end
else
# The path must be relative and start with a `./`.
raise ArgumentError, "require_spade argument must be a relative path"
end
nil
end
end
end
| 28.280702 | 116 | 0.633375 |
613ccff90e06495a11aa61df5e7dabac8b3bc8f2 | 520 | cask "pdfsam-basic" do
version "4.1.4"
sha256 "e75c82b5b1ace85aa9f81ee49e2e5ac4631f88ea79c46dfeb4718ec8018e7596"
# github.com/torakiki/pdfsam/ was verified as official when first introduced to the cask
url "https://github.com/torakiki/pdfsam/releases/download/v#{version}/PDFsam-#{version}.dmg"
appcast "https://github.com/torakiki/pdfsam/releases.atom"
name "PDFsam Basic"
desc "Extractas pages, splits, merges, mixes and rotates PDF files"
homepage "https://pdfsam.org/"
app "PDFsam Basic.app"
end
| 37.142857 | 94 | 0.763462 |
e2a961fb993bb1170dfd0480fd94a9b99ab423e5 | 12,995 | # frozen_string_literal: true
require 'thredded/base_migration'
# rubocop:disable Metrics/ClassLength
# rubocop:disable Metrics/MethodLength
class CreateThredded < Thredded::BaseMigration
def change
unless table_exists?(:friendly_id_slugs)
# The user might have installed FriendlyId separately already.
create_table :friendly_id_slugs do |t|
t.string :slug, null: false
t.integer :sluggable_id, null: false
t.string :sluggable_type, limit: 50
t.string :scope
t.datetime :created_at
end
add_index :friendly_id_slugs, :sluggable_id
add_index :friendly_id_slugs, %i[slug sluggable_type], length: { slug: 140, sluggable_type: 50 }
add_index :friendly_id_slugs, %i[slug sluggable_type scope],
length: { slug: 70, sluggable_type: 50, scope: 70 },
unique: true
add_index :friendly_id_slugs, :sluggable_type
end
create_table :thredded_categories do |t|
t.references :messageboard, null: false, index: false
t.text :name, null: false
t.text :description
t.timestamps null: false
t.text :slug, null: false
t.index %i[messageboard_id slug],
name: :index_thredded_categories_on_messageboard_id_and_slug,
unique: true,
length: { slug: max_key_length }
t.index [:messageboard_id], name: :index_thredded_categories_on_messageboard_id
end
DbTextSearch::CaseInsensitive.add_index connection, :thredded_categories, :name,
name: :thredded_categories_name_ci,
**(max_key_length ? { length: max_key_length } : {})
create_table :thredded_messageboards do |t|
t.text :name, null: false
t.text :slug
t.text :description
t.integer :topics_count, default: 0
t.integer :posts_count, default: 0
t.integer :position, null: false
t.references :last_topic, index: false
t.references :messageboard_group, index: false
t.timestamps null: false
t.boolean :locked, null: false, default: false
t.index [:messageboard_group_id], name: :index_thredded_messageboards_on_messageboard_group_id
t.index [:slug],
name: :index_thredded_messageboards_on_slug,
unique: true,
length: { slug: max_key_length }
end
create_table :thredded_posts do |t|
t.references :user, type: user_id_type, index: false
t.text :content, limit: 65_535
t.string :source, limit: 191, default: 'web'
t.references :postable, null: false, index: false
t.references :messageboard, null: false, index: false
t.integer :moderation_state, null: false
t.timestamps null: false
t.index %i[moderation_state updated_at],
order: { updated_at: :asc },
name: :index_thredded_posts_for_display
t.index [:messageboard_id], name: :index_thredded_posts_on_messageboard_id
t.index [:postable_id], name: :index_thredded_posts_on_postable_id
t.index %i[postable_id created_at], name: :index_thredded_posts_on_postable_id_and_created_at
t.index [:user_id], name: :index_thredded_posts_on_user_id
end
DbTextSearch::FullText.add_index connection, :thredded_posts, :content, name: :thredded_posts_content_fts
create_table :thredded_private_posts do |t|
t.references :user, type: user_id_type, index: false
t.text :content, limit: 65_535
t.references :postable, null: false, index: false
t.timestamps null: false
t.index %i[postable_id created_at], name: :index_thredded_private_posts_on_postable_id_and_created_at
end
create_table :thredded_private_topics do |t|
t.references :user, type: user_id_type, index: false
t.references :last_user, type: user_id_type, index: false
t.text :title, null: false
t.text :slug, null: false
t.integer :posts_count, default: 0
t.string :hash_id, limit: 20, null: false
t.datetime :last_post_at
t.timestamps null: false
t.index [:last_post_at], name: :index_thredded_private_topics_on_last_post_at
t.index [:hash_id], name: :index_thredded_private_topics_on_hash_id
t.index [:slug],
name: :index_thredded_private_topics_on_slug,
unique: true,
length: { slug: max_key_length }
end
create_table :thredded_private_users do |t|
t.references :private_topic, index: false
t.references :user, type: user_id_type, index: false
t.timestamps null: false
t.index [:private_topic_id], name: :index_thredded_private_users_on_private_topic_id
t.index [:user_id], name: :index_thredded_private_users_on_user_id
end
create_table :thredded_topic_categories do |t|
t.references :topic, null: false, index: false
t.references :category, null: false, index: false
t.index [:category_id], name: :index_thredded_topic_categories_on_category_id
t.index [:topic_id], name: :index_thredded_topic_categories_on_topic_id
end
create_table :thredded_topics do |t|
t.references :user, type: user_id_type, index: false
t.references :last_user, type: user_id_type, index: false
t.text :title, null: false
t.text :slug, null: false
t.references :messageboard, null: false, index: false
t.integer :posts_count, default: 0, null: false
t.boolean :sticky, default: false, null: false
t.boolean :locked, default: false, null: false
t.string :hash_id, limit: 20, null: false
t.integer :moderation_state, null: false
t.datetime :last_post_at
t.timestamps null: false
t.index %i[moderation_state sticky updated_at],
order: { sticky: :desc, updated_at: :desc },
name: :index_thredded_topics_for_display
t.index [:last_post_at], name: :index_thredded_topics_on_last_post_at
t.index [:hash_id], name: :index_thredded_topics_on_hash_id
t.index [:slug],
name: :index_thredded_topics_on_slug,
unique: true,
length: { slug: max_key_length }
t.index [:messageboard_id], name: :index_thredded_topics_on_messageboard_id
t.index [:user_id], name: :index_thredded_topics_on_user_id
end
DbTextSearch::FullText.add_index connection, :thredded_topics, :title, name: :thredded_topics_title_fts
create_table :thredded_user_details do |t|
t.references :user, type: user_id_type, null: false, index: false
t.datetime :latest_activity_at
t.integer :posts_count, default: 0
t.integer :topics_count, default: 0
t.datetime :last_seen_at
t.integer :moderation_state, null: false, default: 0 # pending_moderation
t.timestamp :moderation_state_changed_at
t.timestamps null: false
t.index %i[moderation_state moderation_state_changed_at],
order: { moderation_state_changed_at: :desc },
name: :index_thredded_user_details_for_moderations
t.index %i[latest_activity_at], name: :index_thredded_user_details_on_latest_activity_at
t.index %i[user_id], name: :index_thredded_user_details_on_user_id, unique: true
end
create_table :thredded_messageboard_users do |t|
t.references :thredded_user_detail, null: false, index: false
t.references :thredded_messageboard, null: false, index: false
t.datetime :last_seen_at, null: false
t.index %i[thredded_messageboard_id thredded_user_detail_id],
name: :index_thredded_messageboard_users_primary,
unique: true
t.index %i[thredded_messageboard_id last_seen_at],
name: :index_thredded_messageboard_users_for_recently_active
end
add_foreign_key :thredded_messageboard_users, :thredded_user_details,
column: :thredded_user_detail_id, on_delete: :cascade
add_foreign_key :thredded_messageboard_users, :thredded_messageboards,
column: :thredded_messageboard_id, on_delete: :cascade
create_table :thredded_user_preferences do |t|
t.references :user, type: user_id_type, null: false, index: false
t.boolean :follow_topics_on_mention, default: true, null: false
t.boolean :auto_follow_topics, default: false, null: false
t.timestamps null: false
t.index [:user_id], name: :index_thredded_user_preferences_on_user_id, unique: true
end
create_table :thredded_user_messageboard_preferences do |t|
t.references :user, type: user_id_type, null: false, index: false
t.references :messageboard, null: false, index: false
t.boolean :follow_topics_on_mention, default: true, null: false
t.boolean :auto_follow_topics, default: false, null: false
t.timestamps null: false
t.index %i[user_id messageboard_id],
name: :thredded_user_messageboard_preferences_user_id_messageboard_id,
unique: true
end
%i[topic private_topic].each do |topics_table|
table_name = :"thredded_user_#{topics_table}_read_states"
create_table table_name do |t|
t.references :messageboard, null: false, index: true if table_name == :thredded_user_topic_read_states
t.references :user, type: user_id_type, null: false, index: false
t.references :postable, null: false, index: false
t.integer :unread_posts_count, default: 0, null: false
t.integer :read_posts_count, :integer, default: 0, null: false
t.timestamp :read_at, null: false
t.index %i[user_id postable_id], name: :"#{table_name}_user_postable", unique: true
end
end
add_index :thredded_user_topic_read_states, %i[user_id messageboard_id],
name: :thredded_user_topic_read_states_user_messageboard
create_table :thredded_messageboard_groups do |t|
t.string :name
t.integer :position, null: false
t.timestamps null: false
end
create_table :thredded_user_topic_follows do |t|
t.references :user, type: user_id_type, null: false, index: false
t.references :topic, null: false, index: false
t.datetime :created_at, null: false
t.integer :reason, limit: 1
t.index %i[user_id topic_id], name: :thredded_user_topic_follows_user_topic, unique: true
end
create_table :thredded_post_moderation_records do |t|
t.references :post, index: false
t.references :messageboard, index: false
t.text :post_content, limit: 65_535
t.references :post_user, index: false
t.text :post_user_name
t.references :moderator, index: false
t.integer :moderation_state, null: false
t.integer :previous_moderation_state, null: false
t.timestamp :created_at, null: false
t.index %i[messageboard_id created_at],
order: { created_at: :desc },
name: :index_thredded_moderation_records_for_display
end
create_table :thredded_notifications_for_private_topics do |t|
t.references :user, null: false, index: false, type: user_id_type
t.string :notifier_key, null: false, limit: 90
t.boolean :enabled, default: true, null: false
t.index %i[user_id notifier_key],
name: 'thredded_notifications_for_private_topics_unique', unique: true
end
create_table :thredded_notifications_for_followed_topics do |t|
t.references :user, null: false, index: false, type: user_id_type
t.string :notifier_key, null: false, limit: 90
t.boolean :enabled, default: true, null: false
t.index %i[user_id notifier_key],
name: 'thredded_notifications_for_followed_topics_unique', unique: true
end
create_table :thredded_messageboard_notifications_for_followed_topics do |t|
t.references :user, null: false, index: false, type: user_id_type
t.references :messageboard, null: false, index: false
t.string :notifier_key, null: false, limit: 90
t.boolean :enabled, default: true, null: false
t.index %i[user_id messageboard_id notifier_key],
name: 'thredded_messageboard_notifications_for_followed_topics_unique', unique: true
end
create_table :thredded_user_post_notifications do |t|
t.references :user, null: false, index: false, type: user_id_type
t.references :post, null: false, index: false
t.datetime :notified_at, null: false
t.index :post_id, name: :index_thredded_user_post_notifications_on_post_id
t.index %i[user_id post_id], name: :index_thredded_user_post_notifications_on_user_id_and_post_id, unique: true
end
add_foreign_key :thredded_user_post_notifications,
Thredded.user_class.table_name, column: :user_id, on_delete: :cascade
add_foreign_key :thredded_user_post_notifications,
:thredded_posts, column: :post_id, on_delete: :cascade
end
end
# rubocop:enable Metrics/MethodLength
# rubocop:enable Metrics/ClassLength
| 46.913357 | 117 | 0.697961 |
1dfa309a6f8110a973c7d56cbc6d317d0b9d2c5c | 8,744 | require 'util/miq-xml'
module MiqLinux
class OSInfo
attr_reader :os, :networks
ETC = "/etc"
IFCFGFILE = "/etc/sysconfig/network-scripts"
DHCLIENTFILE = "/var/lib/dhclient/"
DEBIANDHCLIENTFILE = "/var/lib/dhcp3/"
DEBIANIFCFGILE = "/etc/network"
DISTRIBUTIONS = ["mandriva", "mandrake", "mandrakelinux", "gentoo", "SuSE", "fedora", "redhat", "knoppix", "debian", "lsb", "distro"]
def initialize(fs)
@fs = fs
@os_type = "Linux"
@distribution = nil
@description = nil
@hostname = nil
release_file = nil
version_file = nil
@networks = []
@os = {}
DISTRIBUTIONS.each do |dist|
release_file = File.join(ETC, dist + "-release")
if fs.fileExists?(release_file)
@distribution = dist
break
end
end
if @distribution == "lsb"
lsbd = ""
fs.fileOpen(release_file) { |fo| lsbd = fo.read }
dist = desc = chrome_dist = chrome_desc = nil
lsbd.each_line do |lsbl|
dist = $1 if lsbl =~ /^\s*DISTRIB_ID\s*=\s*(.*)$/
desc = $1 if lsbl =~ /^\s*DISTRIB_DESCRIPTION\s*=\s*(.*)$/
chrome_dist = $1 if lsbl =~ /^\s*CHROMEOS_RELEASE_NAME\s*=\s*(.*)$/
chrome_desc = $1 if lsbl =~ /^\s*CHROMEOS_RELEASE_DESCRIPTION\s*=\s*(.*)$/
end
chrome_desc = "#{chrome_dist} #{chrome_desc}" if chrome_dist && chrome_desc
@distribution = chrome_dist || dist if chrome_dist || dist
@description = chrome_desc || desc if chrome_desc || desc
elsif @distribution
fs.fileOpen(release_file) { |fo| @description = fo.read.to_s.chomp }
@distribution = "CentOS" if @distribution == "redhat" && @description.include?("CentOS")
@distribution = "rPath" if @distribution == "distro"
end
unless @distribution
DISTRIBUTIONS.each do |distrib|
version_file = File.join(ETC, distrib + "-release")
if fs.fileExists?(version_file)
@distribution = distrib
break
end
end
fs.fileOpen(version_file) { |fo| @description = fo.read.chomp } if @distribution
end
unless @distribution
read_file(fs, File.join(ETC, "issue")) do |line|
case line
when /\s*Hercules\s*/
@distribution = "hercules"
@description = "Hercules"
break
end
end
end
@distribution = "" unless @distribution
@description = "" unless @description
@description = @description.gsub(/^"/, "").gsub(/"$/, "")
["/etc/hostname", "/etc/HOSTNAME"].each do |hnf|
next unless fs.fileExists?(hnf)
fs.fileOpen(hnf) { |fo| @hostname = fo.read.chomp } if fs.fileExists?(hnf)
end
# return if @hostname
["/etc/conf.d/hostname", "/etc/sysconfig/network"].each do |hnf|
next unless fs.fileExists?(hnf)
next if fs.fileDirectory?(hnf)
hnfd = ""
fs.fileOpen(hnf) { |fo| hnfd = fo.read }
hnfd.each_line do |hnfl|
if hnfl =~ /^\s*HOSTNAME\s*=\s*(.*)$/
@hostname = $1
break
end
end
end
@hostname = "" unless @hostname
network_attrs = {:hostname => @hostname}
# Collect network settings
case @distribution.downcase
when "ubuntu" then networking_debian(fs, network_attrs)
when "redhat", "fedora" then networking_redhat(fs, network_attrs)
when "hercules" then networking_hercules(fs, network_attrs)
end
@os = {:type => "linux", :machine_name => @hostname, :product_type => @os_type, :distribution => @distribution, :product_name => @description}
$log.info "VM OS information: [#{@os.inspect}]" if $log
end
def networking_debian(fs, attrs)
read_file(fs, File.join(DEBIANIFCFGILE, "interfaces")) do |line|
case line
when /^\s*iface eth0 inet dhcp\s*(.*)$/ then attrs[:dhcp_enabled] = 1
when /^\s*iface eth0 inet static\s*(.*)$/ then attrs[:dhcp_enabled] = 0
when /^\s*address\s*(.*)$/ then attrs[:ipaddress] = $1
when /^\s*netmask\s*(.*)$/ then attrs[:subnet_mask] = $1
when /^\s*gateway\s*(.*)$/ then attrs[:default_gateway] = $1
when /^\s*network\s*(.*)$/ then attrs[:network] = $1
end
end
if attrs[:dhcp_enabled] == 1
read_file(fs, File.join(DEBIANDHCLIENTFILE, "dhclient.eth0.leases")) do |line|
case line
when /^\s*fixed-address\s*(.*)\;$/ then attrs[:ipaddress] = $1
when /^\s*option subnet-mask\s*(.*)\;$/ then attrs[:subnet_mask] = $1
when /^\s*option routers\s*(.*)\;$/ then attrs[:default_gateway] = $1
when /^\s*option domain-name-servers\s*(.*)\;$/ then attrs[:dns_server] = $1
when /^\s*option dhcp-server-identifier\s*(.*)\;$/ then attrs[:dhcp_server] = $1
when /^\s*option domain-name\s*"*(.*)"\;$/ then attrs[:domain] = $1
when /^\s*expire\s*[0-9]?\s*(.*)\;$/ then attrs[:lease_expires] = $1
when /^\s*renew\s*[0-9]?\s*(.*)\;$/ then attrs[:lease_obtained] = $1
end
end
end
fix_attr_values(attrs)
@networks << attrs
end
def networking_redhat(fs, attrs)
read_file(fs, File.join(IFCFGFILE, "ifcfg-eth0")) do |line|
case line
when /^\s*BOOTPROTO=dhcp\s*(.*)$/ then attrs[:dhcp_enabled] = 1
when /^\s*BOOTPROTO=static\s*(.*)$/ then attrs[:dhcp_enabled] = 0
when /^\s*DEVICE\s*=\s*(.*)$/ then attrs[:device] = $1
when /^\s*HWADDR\s*=\s*(.*)$/ then attrs[:hwaddr] = $1
# static setting will have these entries
when /^\s*IPADDR\s*=\s*(.*)$/ then attrs[:ipaddress] = $1
when /^\s*NETMASK\s*=\s*(.*)$/ then attrs[:subnet_mask] = $1
# static setting might have these entries
when /^\s*BROADCAST\s*=\s*(.*)$/ then attrs[:broadcast] = $1
when /^\s*NETWORK\s*=\s*(.*)$/ then attrs[:network] = $1
end
end
if attrs[:dhcp_enabled] == 1
read_file(fs, File.join(DHCLIENTFILE, "dhclient-eth0.leases")) do |line|
case line
when /^\s*fixed-address\s*(.*)\;$/ then attrs[:ipaddress] = $1
when /^\s*option subnet-mask\s*(.*)\;$/ then attrs[:subnet_mask] = $1
when /^\s*option routers\s*(.*)\;$/ then attrs[:default_gateway] = $1
when /^\s*option domain-name-servers\s*(.*)\;$/ then attrs[:dns_server] = $1
when /^\s*option dhcp-server-identifier\s*(.*)\;$/ then attrs[:dhcp_server] = $1
when /^\s*option domain-name\s*"*(.*)"\;$/ then attrs[:domain] = $1
when /^\s*expire\s*[0-9]?\s*(.*)\;$/ then attrs[:lease_expires] = $1
when /^\s*renew\s*[0-9]?\s*(.*)\;$/ then attrs[:lease_obtained] = $1
end
end
end
fix_attr_values(attrs)
@networks << attrs
end
def networking_hercules(fs, attrs)
read_file(fs, File.join(DEBIANIFCFGILE, "interfaces")) do |line|
case line
when /^\s*iface eth0 inet dhcp\s*(.*)$/ then attrs[:dhcp_enabled] = 1
when /^\s*iface eth0 inet static\s*(.*)$/ then attrs[:dhcp_enabled] = 0
end
end
fix_attr_values(attrs)
@networks << attrs
end
def toXml(doc = nil)
doc = MiqXml.createDoc(nil) unless doc
doc.add_element(:os, @os)
networksToXml(doc)
doc
end
def networksToXml(doc = nil)
doc = MiqXml.createDoc(nil) unless doc
unless @networks.empty?
node = doc.add_element(:networks)
@networks.each do |n|
[:hwaddr, :network, :device, :broadcast].each { |key| n.delete(key) }
node.add_element(:network, n)
end
end
doc
end
def read_file(fs, filename)
if fs.fileExists?(filename)
file_content = ""
fs.fileOpen(filename) { |fo| file_content = fo.read }
unless file_content.nil?
file_content.each_line { |line| yield(line.chomp) }
end
end
end
def fix_attr_values(attrs)
# Clean the lease times and check they are in a reasonable range
[:lease_obtained, :lease_expires].each do |t|
if attrs[t] && attrs[t].to_i >= 0 && attrs[t].to_i < 0x80000000
attrs[t] = Time.parse(attrs[t]).utc.iso8601
else
attrs.delete(t)
end
end
attrs[:dns_server].gsub!(/(,)/) { (' ') } unless attrs[:dns_server].nil?
end
end # class OSInfo
end # module MiqLinux
| 36.739496 | 148 | 0.547347 |
e80b8f2e718612c382ea69cb6b6f6416e8e2cb0a | 218 | class Calculator
attr_reader :name
def initialize(name)
@name = name
end
def add(one, two)
one + two
end
def subtract(one, two)
one - two
end
def divide(one, two)
one / two
end
end
| 9.478261 | 24 | 0.605505 |
7a89c1dba9417e4afcc7f20fa11e32127f8ace57 | 1,502 | require_relative 'boot'
require 'active_record/railtie'
require 'action_controller/railtie'
require 'action_view/railtie'
require 'rails/test_unit/railtie'
require 'sprockets/railtie'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module JobConstructor
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
if ::Configuration.load_external_config?
config.paths["config/initializers"] << ::Configuration.custom_initializers_root.to_s
config.paths["app/views"].unshift ::Configuration.custom_views_root.to_s
end
end
end
| 39.526316 | 99 | 0.746338 |
7a54dc5755389fe851be5b0174b2c48437fde91a | 3,099 | # frozen_string_literal: true
# Copyright (c) 2017-present, BigCommerce Pty. Ltd. All rights reserved
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
require 'spec_helper'
describe Gruf::Response do
let(:internal_execution_time) { rand(1.00..500.00) }
let(:trailing_metadata) { { 'timer' => internal_execution_time } }
let(:operation) { build_operation(trailing_metadata: trailing_metadata, execution_time: execution_time) }
let(:execution_time) { nil }
let(:message) { Rpc::GetThingResponse.new }
let(:response) { described_class.new(operation: operation, message: message, execution_time: execution_time) }
describe '.initialize' do
subject { response }
it 'sets up the appropriate values' do
expect(subject).to be_a(described_class)
expect(subject.operation).to eq operation
expect(subject.message).to eq message
expect(subject.metadata).to eq operation.metadata
expect(subject.trailing_metadata).to eq operation.trailing_metadata
expect(subject.deadline).to eq operation.deadline
expect(subject.cancelled).to eq operation.cancelled?
end
context 'with no specified execution time' do
it 'sets the execution time to 0.0' do
expect(subject.execution_time).to eq 0.0
end
end
context 'with a specified execution time' do
let(:execution_time) { rand(1.00..200.00) }
it 'sets it to the passed value' do
expect(subject.execution_time).to eq execution_time
end
end
end
describe '#message' do
subject { response.message }
it 'returns the operation execution result' do
expect(subject).to eq message
end
end
describe '#internal_execution_time' do
subject { response.internal_execution_time }
context 'when the time is passed through the trailing metadata' do
it 'returns that time' do
expect(subject).to eq internal_execution_time
end
end
context 'when no time is passed' do
let(:trailing_metadata) { {} }
it 'returns 0.0' do
expect(subject).to eq 0.0
end
end
end
end
| 37.792683 | 120 | 0.727654 |
210556cac08967210692b2ce4bd1116c1410fff0 | 293 | Delayed::Worker.destroy_failed_jobs = false
Delayed::Worker.sleep_delay = 10
Delayed::Worker.max_attempts = 2
Delayed::Worker.max_run_time = 45.minutes
Delayed::Worker.default_queue_name = 'default'
Delayed::Worker.delay_jobs = !Rails.env.test?
Delayed::Worker.raise_signal_exceptions = :term
| 36.625 | 47 | 0.805461 |
617f9dca6ec0428c128cc0ef5ecf462ecff2373c | 16,391 | require 'mono_logger'
require 'redis/namespace'
require 'forwardable'
require 'resque/version'
require 'resque/errors'
require 'resque/failure'
require 'resque/failure/base'
require 'resque/helpers'
require 'resque/stat'
require 'resque/logging'
require 'resque/log_formatters/quiet_formatter'
require 'resque/log_formatters/verbose_formatter'
require 'resque/log_formatters/very_verbose_formatter'
require 'resque/job'
require 'resque/worker'
require 'resque/plugin'
require 'resque/data_store'
require 'resque/thread_signal'
require 'resque/vendor/utf8_util'
module Resque
include Helpers
extend self
# Given a Ruby object, returns a string suitable for storage in a
# queue.
def encode(object)
if MultiJson.respond_to?(:dump) && MultiJson.respond_to?(:load)
MultiJson.dump object
else
MultiJson.encode object
end
end
# Given a string, returns a Ruby object.
def decode(object)
return unless object
begin
if MultiJson.respond_to?(:dump) && MultiJson.respond_to?(:load)
MultiJson.load object
else
MultiJson.decode object
end
rescue ::MultiJson::DecodeError => e
raise Helpers::DecodeException, e.message, e.backtrace
end
end
# Given a word with dashes, returns a camel cased version of it.
#
# classify('job-name') # => 'JobName'
def classify(dashed_word)
dashed_word.split('-').map(&:capitalize).join
end
# Tries to find a constant with the name specified in the argument string:
#
# constantize("Module") # => Module
# constantize("Test::Unit") # => Test::Unit
#
# The name is assumed to be the one of a top-level constant, no matter
# whether it starts with "::" or not. No lexical context is taken into
# account:
#
# C = 'outside'
# module M
# C = 'inside'
# C # => 'inside'
# constantize("C") # => 'outside', same as ::C
# end
#
# NameError is raised when the constant is unknown.
def constantize(camel_cased_word)
camel_cased_word = camel_cased_word.to_s
if camel_cased_word.include?('-')
camel_cased_word = classify(camel_cased_word)
end
names = camel_cased_word.split('::')
names.shift if names.empty? || names.first.empty?
constant = Object
names.each do |name|
args = Module.method(:const_get).arity != 1 ? [false] : []
if constant.const_defined?(name, *args)
constant = constant.const_get(name)
else
constant = constant.const_missing(name)
end
end
constant
end
extend ::Forwardable
# Accepts:
# 1. A 'hostname:port' String
# 2. A 'hostname:port:db' String (to select the Redis db)
# 3. A 'hostname:port/namespace' String (to set the Redis namespace)
# 4. A Redis URL String 'redis://host:port'
# 5. An instance of `Redis`, `Redis::Client`, `Redis::DistRedis`,
# or `Redis::Namespace`.
# 6. An Hash of a redis connection {:host => 'localhost', :port => 6379, :db => 0}
def redis=(server)
case server
when String
if server =~ /redis\:\/\//
redis = Redis.connect(:url => server, :thread_safe => true)
else
server, namespace = server.split('/', 2)
host, port, db = server.split(':')
redis = Redis.new(:host => host, :port => port,
:thread_safe => true, :db => db)
end
namespace ||= :resque
@data_store = Resque::DataStore.new(Redis::Namespace.new(namespace, :redis => redis))
when Redis::Namespace
@data_store = Resque::DataStore.new(server)
when Resque::DataStore
@data_store = server
when Hash
@data_store = Resque::DataStore.new(Redis::Namespace.new(:resque, :redis => Redis.new(server)))
else
@data_store = Resque::DataStore.new(Redis::Namespace.new(:resque, :redis => server))
end
end
# Returns the current Redis connection. If none has been created, will
# create a new one.
def redis
return @data_store if @data_store
self.redis = Redis.respond_to?(:connect) ? Redis.connect : "localhost:6379"
self.redis
end
alias :data_store :redis
def redis_id
data_store.identifier
end
# Set or retrieve the current logger object
attr_accessor :logger
DEFAULT_HEARTBEAT_INTERVAL = 60
DEFAULT_PRUNE_INTERVAL = DEFAULT_HEARTBEAT_INTERVAL * 5
attr_writer :heartbeat_interval
def heartbeat_interval
@heartbeat_interval || DEFAULT_HEARTBEAT_INTERVAL
end
attr_writer :prune_interval
def prune_interval
@prune_interval || DEFAULT_PRUNE_INTERVAL
end
attr_writer :enqueue_front
def enqueue_front
return @enqueue_front unless @enqueue_front.nil?
@enqueue_front = false
end
# The `before_first_fork` hook will be run in the **parent** process
# only once, before forking to run the first job. Be careful- any
# changes you make will be permanent for the lifespan of the
# worker.
#
# Call with a block to register a hook.
# Call with no arguments to return all registered hooks.
def before_first_fork(&block)
block ? register_hook(:before_first_fork, block) : hooks(:before_first_fork)
end
# Register a before_first_fork proc.
def before_first_fork=(block)
register_hook(:before_first_fork, block)
end
# The `before_fork` hook will be run in the **parent** process
# before every job, so be careful- any changes you make will be
# permanent for the lifespan of the worker.
#
# Call with a block to register a hook.
# Call with no arguments to return all registered hooks.
def before_fork(&block)
block ? register_hook(:before_fork, block) : hooks(:before_fork)
end
# Register a before_fork proc.
def before_fork=(block)
register_hook(:before_fork, block)
end
# The `after_fork` hook will be run in the child process and is passed
# the current job. Any changes you make, therefore, will only live as
# long as the job currently being processed.
#
# Call with a block to register a hook.
# Call with no arguments to return all registered hooks.
def after_fork(&block)
block ? register_hook(:after_fork, block) : hooks(:after_fork)
end
# Register an after_fork proc.
def after_fork=(block)
register_hook(:after_fork, block)
end
# The `before_pause` hook will be run in the parent process before the
# worker has paused processing (via #pause_processing or SIGUSR2).
def before_pause(&block)
block ? register_hook(:before_pause, block) : hooks(:before_pause)
end
# Register a before_pause proc.
def before_pause=(block)
register_hook(:before_pause, block)
end
# The `after_pause` hook will be run in the parent process after the
# worker has paused (via SIGCONT).
def after_pause(&block)
block ? register_hook(:after_pause, block) : hooks(:after_pause)
end
# Register an after_pause proc.
def after_pause=(block)
register_hook(:after_pause, block)
end
def to_s
"Resque Client connected to #{redis_id}"
end
attr_accessor :inline
# If 'inline' is true Resque will call #perform method inline
# without queuing it into Redis and without any Resque callbacks.
# The 'inline' is false Resque jobs will be put in queue regularly.
alias :inline? :inline
#
# queue manipulation
#
# Pushes a job onto a queue. Queue name should be a string and the
# item should be any JSON-able Ruby object.
#
# Resque works generally expect the `item` to be a hash with the following
# keys:
#
# class - The String name of the job to run.
# args - An Array of arguments to pass the job. Usually passed
# via `class.to_class.perform(*args)`.
#
# Example
#
# Resque.push('archive', :class => 'Archive', :args => [ 35, 'tar' ])
#
# Returns nothing
def push(queue, item)
data_store.push_to_queue(queue,encode(item))
end
# Pops a job off a queue. Queue name should be a string.
#
# Returns a Ruby object.
def pop(queue)
Rails.logger.info("mrj_chaos: Resque#pop: Seeing if there is a job to pop from #{queue} queue") if queue == "outbound_mail"
decode(data_store.pop_from_queue(queue))
end
# Returns an integer representing the size of a queue.
# Queue name should be a string.
def size(queue)
data_store.queue_size(queue)
end
# Returns an array of items currently queued. Queue name should be
# a string.
#
# start and count should be integer and can be used for pagination.
# start is the item to begin, count is how many items to return.
#
# To get the 3rd page of a 30 item, paginatied list one would use:
# Resque.peek('my_list', 59, 30)
def peek(queue, start = 0, count = 1)
results = data_store.peek_in_queue(queue,start,count)
if count == 1
decode(results)
else
results.map { |result| decode(result) }
end
end
# Does the dirty work of fetching a range of items from a Redis list
# and converting them into Ruby objects.
def list_range(key, start = 0, count = 1)
results = data_store.list_range(key, start, count)
if count == 1
decode(results)
else
results.map { |result| decode(result) }
end
end
# Returns an array of all known Resque queues as strings.
def queues
data_store.queue_names
end
# Given a queue name, completely deletes the queue.
def remove_queue(queue)
data_store.remove_queue(queue)
end
# Used internally to keep track of which queues we've created.
# Don't call this directly.
def watch_queue(queue)
data_store.watch_queue(queue)
end
#
# job shortcuts
#
# This method can be used to conveniently add a job to a queue.
# It assumes the class you're passing it is a real Ruby class (not
# a string or reference) which either:
#
# a) has a @queue ivar set
# b) responds to `queue`
#
# If either of those conditions are met, it will use the value obtained
# from performing one of the above operations to determine the queue.
#
# If no queue can be inferred this method will raise a `Resque::NoQueueError`
#
# Returns true if the job was queued, nil if the job was rejected by a
# before_enqueue hook.
#
# This method is considered part of the `stable` API.
def enqueue(klass, *args)
enqueue_to(queue_from_class(klass), klass, *args)
end
# Just like `enqueue` but allows you to specify the queue you want to
# use. Runs hooks.
#
# `queue` should be the String name of the queue you're targeting.
#
# Returns true if the job was queued, nil if the job was rejected by a
# before_enqueue hook.
#
# This method is considered part of the `stable` API.
def enqueue_to(queue, klass, *args)
# Perform before_enqueue hooks. Don't perform enqueue if any hook returns false
before_hooks = Plugin.before_enqueue_hooks(klass).collect do |hook|
klass.send(hook, *args)
end
return nil if before_hooks.any? { |result| result == false }
Job.create(queue, klass, *args)
Plugin.after_enqueue_hooks(klass).each do |hook|
klass.send(hook, *args)
end
return true
end
# This method can be used to conveniently remove a job from a queue.
# It assumes the class you're passing it is a real Ruby class (not
# a string or reference) which either:
#
# a) has a @queue ivar set
# b) responds to `queue`
#
# If either of those conditions are met, it will use the value obtained
# from performing one of the above operations to determine the queue.
#
# If no queue can be inferred this method will raise a `Resque::NoQueueError`
#
# If no args are given, this method will dequeue *all* jobs matching
# the provided class. See `Resque::Job.destroy` for more
# information.
#
# Returns the number of jobs destroyed.
#
# Example:
#
# # Removes all jobs of class `UpdateNetworkGraph`
# Resque.dequeue(GitHub::Jobs::UpdateNetworkGraph)
#
# # Removes all jobs of class `UpdateNetworkGraph` with matching args.
# Resque.dequeue(GitHub::Jobs::UpdateNetworkGraph, 'repo:135325')
#
# This method is considered part of the `stable` API.
def dequeue(klass, *args)
# Perform before_dequeue hooks. Don't perform dequeue if any hook returns false
before_hooks = Plugin.before_dequeue_hooks(klass).collect do |hook|
klass.send(hook, *args)
end
return if before_hooks.any? { |result| result == false }
destroyed = Job.destroy(queue_from_class(klass), klass, *args)
Plugin.after_dequeue_hooks(klass).each do |hook|
klass.send(hook, *args)
end
destroyed
end
# Given a class, try to extrapolate an appropriate queue based on a
# class instance variable or `queue` method.
def queue_from_class(klass)
klass.instance_variable_get(:@queue) ||
(klass.respond_to?(:queue) and klass.queue)
end
# This method will return a `Resque::Job` object or a non-true value
# depending on whether a job can be obtained. You should pass it the
# precise name of a queue: case matters.
#
# This method is considered part of the `stable` API.
def reserve(queue)
Job.reserve(queue)
end
# Validates if the given klass could be a valid Resque job
#
# If no queue can be inferred this method will raise a `Resque::NoQueueError`
#
# If given klass is nil this method will raise a `Resque::NoClassError`
def validate(klass, queue = nil)
queue ||= queue_from_class(klass)
if !queue
raise NoQueueError.new("Jobs must be placed onto a queue. No queue could be inferred for class #{klass}")
end
if klass.to_s.empty?
raise NoClassError.new("Jobs must be given a class.")
end
end
#
# worker shortcuts
#
# A shortcut to Worker.all
def workers
Worker.all
end
# A shortcut to Worker.working
def working
Worker.working
end
# A shortcut to unregister_worker
# useful for command line tool
def remove_worker(worker_id)
worker = Resque::Worker.find(worker_id)
worker.unregister_worker
end
#
# stats
#
# Returns a hash, similar to redis-rb's #info, of interesting stats.
def info
return {
:pending => queue_sizes.inject(0) { |sum, (queue_name, queue_size)| sum + queue_size },
:processed => Stat[:processed],
:queues => queues.size,
:workers => workers.size.to_i,
:working => working.size,
:failed => data_store.num_failed,
:servers => [redis_id],
:environment => ENV['RAILS_ENV'] || ENV['RACK_ENV'] || 'development'
}
end
# Returns an array of all known Resque keys in Redis. Redis' KEYS operation
# is O(N) for the keyspace, so be careful - this can be slow for big databases.
def keys
data_store.all_resque_keys
end
# Returns a hash, mapping queue names to queue sizes
def queue_sizes
queue_names = queues
sizes = redis.pipelined do
queue_names.each do |name|
redis.llen("queue:#{name}")
end
end
Hash[queue_names.zip(sizes)]
end
# Returns a hash, mapping queue names to (up to `sample_size`) samples of jobs in that queue
def sample_queues(sample_size = 1000)
queue_names = queues
samples = redis.pipelined do
queue_names.each do |name|
key = "queue:#{name}"
redis.llen(key)
redis.lrange(key, 0, sample_size - 1)
end
end
hash = {}
queue_names.zip(samples.each_slice(2).to_a) do |queue_name, (queue_size, serialized_samples)|
samples = serialized_samples.map do |serialized_sample|
Job.decode(serialized_sample)
end
hash[queue_name] = {
:size => queue_size,
:samples => samples
}
end
hash
end
private
# Register a new proc as a hook. If the block is nil this is the
# equivalent of removing all hooks of the given name.
#
# `name` is the hook that the block should be registered with.
def register_hook(name, block)
return clear_hooks(name) if block.nil?
@hooks ||= {}
@hooks[name] ||= []
block = Array(block)
@hooks[name].concat(block)
end
# Clear all hooks given a hook name.
def clear_hooks(name)
@hooks && @hooks[name] = []
end
# Retrieve all hooks
def hooks
@hooks || {}
end
# Retrieve all hooks of a given name.
def hooks(name)
(@hooks && @hooks[name]) || []
end
end
# Log to STDOUT by default
Resque.logger = MonoLogger.new(STDOUT)
Resque.logger.formatter = Resque::QuietFormatter.new
| 28.260345 | 127 | 0.679275 |
62d72dead178cb2975e32ac739347c125e39fdff | 1,298 | class Libmp3splt < Formula
desc "Utility library to split mp3, ogg, and FLAC files"
homepage "https://mp3splt.sourceforge.io"
url "https://downloads.sourceforge.net/project/mp3splt/libmp3splt/0.9.2/libmp3splt-0.9.2.tar.gz"
sha256 "30eed64fce58cb379b7cc6a0d8e545579cb99d0f0f31eb00b9acc8aaa1b035dc"
bottle do
sha256 "08c048a165564eab43d0ec34f837309eec4bc5fd9f63ef80177c1d2da72c1d47" => :high_sierra
sha256 "e513672ee4682c1f722e710d4446fc2721325875acb65ccaaee0e5de113cb82b" => :sierra
sha256 "587226a840b162aeef70cc8022bdbcd61218e1be6dd1b98418774f3f48405072" => :el_capitan
sha256 "47d3aaeee6d237273e8457666cd2717e1264742ae776d541c40a203e1b82003f" => :yosemite
sha256 "0bac13f95cb16925fe28cd1d662bec10a66c93bf9b27c2c9533ab38b7a1f38a2" => :mavericks
sha256 "a6100bee5fe14afed4702b474360078b75bddaa0328290b2fcf902c3f808c78c" => :mountain_lion
end
depends_on "libtool"
depends_on "pkg-config" => :build
depends_on "gettext"
depends_on "pcre"
depends_on "libid3tag"
depends_on "mad"
depends_on "libvorbis"
depends_on "flac"
depends_on "libogg"
def install
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make", "install"
end
end
| 39.333333 | 98 | 0.756549 |
bba48a7be086f092c32e717b9a3a1974890d62a8 | 1,905 | # frozen_string_literal: true
require "cli/parser"
module Homebrew
module_function
def mirror_args
Homebrew::CLI::Parser.new do
usage_banner <<~EOS
`mirror` <formula>
Reupload the stable URL of a formula to Bintray for use as a mirror.
EOS
switch :verbose
switch :debug
hide_from_man_page!
min_named :formula
end
end
def mirror
mirror_args.parse
bintray_user = Homebrew::EnvConfig.bintray_user
bintray_key = Homebrew::EnvConfig.bintray_key
raise "Missing HOMEBREW_BINTRAY_USER or HOMEBREW_BINTRAY_KEY variables!" if !bintray_user || !bintray_key
args.formulae.each do |f|
bintray_package = Utils::Bottles::Bintray.package f.name
bintray_repo_url = "https://api.bintray.com/packages/homebrew/mirror"
package_url = "#{bintray_repo_url}/#{bintray_package}"
unless system curl_executable, "--silent", "--fail", "--output", "/dev/null", package_url
package_blob = <<~JSON
{"name": "#{bintray_package}",
"public_download_numbers": true,
"public_stats": true}
JSON
curl "--silent", "--fail", "--user", "#{bintray_user}:#{bintray_key}",
"--header", "Content-Type: application/json",
"--data", package_blob, bintray_repo_url
puts
end
downloader = f.downloader
downloader.fetch
filename = downloader.basename
destination_url = "https://dl.bintray.com/homebrew/mirror/#{filename}"
ohai "Uploading to #{destination_url}"
content_url =
"https://api.bintray.com/content/homebrew/mirror/#{bintray_package}/#{f.pkg_version}/#{filename}?publish=1"
curl "--silent", "--fail", "--user", "#{bintray_user}:#{bintray_key}",
"--upload-file", downloader.cached_location, content_url
puts
ohai "Mirrored #{filename}!"
end
end
end
| 29.765625 | 115 | 0.64357 |
28bc6a1afc102812b313cc466fe7acfe33780e17 | 814 | # Use Action Cable channels (remember to import "@rails/actionable" in your application.js)
# pin "@rails/actioncable", to: "actioncable.esm.js"
# pin_all_from "app/javascript/channels", under: "channels"
# Use direct uploads for Active Storage (remember to import "@rails/activestorage" in your application.js)
# pin "@rails/activestorage", to: "activestorage.esm.js"
# Use node modules from a JavaScript CDN by running ./bin/importmap
pin "application"
pin "@hotwired/stimulus", to: "stimulus.js"
pin "@hotwired/stimulus-importmap-autoloader", to: "stimulus-importmap-autoloader.js"
pin_all_from "app/javascript/controllers", under: "controllers"
pin "@hotwired/turbo-rails", to: "turbo.js"
pin "@glidejs/glide", to: "glide.esm.js"
pin "lazyload", to: "https://ga.jspm.io/npm:[email protected]/lazyload.js"
| 47.882353 | 106 | 0.749386 |
08c00bbf37a029abdd3a5665458561a2fcb440f4 | 1,252 | # Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/dlp_v2/service.rb'
require 'google/apis/dlp_v2/classes.rb'
require 'google/apis/dlp_v2/representations.rb'
module Google
module Apis
# Cloud Data Loss Prevention (DLP) API
#
# Provides methods for detection, risk analysis, and de-identification of
# privacy-sensitive fragments in text, images, and Google Cloud Platform storage
# repositories.
#
# @see https://cloud.google.com/dlp/docs/
module DlpV2
VERSION = 'V2'
REVISION = '20180404'
# View and manage your data across Google Cloud Platform services
AUTH_CLOUD_PLATFORM = 'https://www.googleapis.com/auth/cloud-platform'
end
end
end
| 33.837838 | 84 | 0.731629 |
b9952c2a860dfb3919c053b5eaf66240d294f444 | 6,952 | require 'spec_helper'
if defined?(ActionController::Request)
describe ApiAuth::RequestDrivers::ActionControllerRequest do
let(:timestamp) { Time.now.utc.httpdate }
let(:request) do
ActionController::Request.new(
'AUTHORIZATION' => 'APIAuth 1044:12345',
'PATH_INFO' => '/resource.xml',
'QUERY_STRING' => 'foo=bar&bar=foo',
'REQUEST_METHOD' => 'PUT',
'CONTENT_MD5' => '1B2M2Y8AsgTpgAmY7PhCfg==',
'CONTENT_TYPE' => 'text/plain',
'CONTENT_LENGTH' => '11',
'HTTP_DATE' => timestamp,
'rack.input' => StringIO.new("hello\nworld")
)
end
subject(:driven_request) { ApiAuth::RequestDrivers::ActionControllerRequest.new(request) }
describe 'getting headers correctly' do
it 'gets the content_type' do
expect(driven_request.content_type).to eq('text/plain')
end
it 'gets the content_md5' do
expect(driven_request.content_md5).to eq('1B2M2Y8AsgTpgAmY7PhCfg==')
end
it 'gets the request_uri' do
expect(driven_request.request_uri).to eq('/resource.xml?foo=bar&bar=foo')
end
it 'gets the timestamp' do
expect(driven_request.timestamp).to eq(timestamp)
end
it 'gets the authorization_header' do
expect(driven_request.authorization_header).to eq('APIAuth 1044:12345')
end
describe '#calculated_md5' do
it 'calculates md5 from the body' do
expect(driven_request.calculated_md5).to eq('kZXQvrKoieG+Be1rsZVINw==')
end
it 'treats no body as empty string' do
request.env['rack.input'] = StringIO.new
request.env['CONTENT_LENGTH'] = 0
expect(driven_request.calculated_md5).to eq('1B2M2Y8AsgTpgAmY7PhCfg==')
end
end
describe 'http_method' do
context 'when put request' do
let(:request) do
ActionController::Request.new('REQUEST_METHOD' => 'PUT')
end
it 'returns upcased put' do
expect(driven_request.http_method).to eq('PUT')
end
end
context 'when get request' do
let(:request) do
ActionController::Request.new('REQUEST_METHOD' => 'GET')
end
it 'returns upcased get' do
expect(driven_request.http_method).to eq('GET')
end
end
end
end
describe 'setting headers correctly' do
let(:request) do
ActionController::Request.new(
'PATH_INFO' => '/resource.xml',
'QUERY_STRING' => 'foo=bar&bar=foo',
'REQUEST_METHOD' => 'PUT',
'CONTENT_TYPE' => 'text/plain',
'CONTENT_LENGTH' => '11',
'rack.input' => StringIO.new("hello\nworld")
)
end
describe '#populate_content_md5' do
context 'when getting' do
it "doesn't populate content-md5" do
request.env['REQUEST_METHOD'] = 'GET'
driven_request.populate_content_md5
expect(request.env['Content-MD5']).to be_nil
end
end
context 'when posting' do
it 'populates content-md5' do
request.env['REQUEST_METHOD'] = 'POST'
driven_request.populate_content_md5
expect(request.env['Content-MD5']).to eq('kZXQvrKoieG+Be1rsZVINw==')
end
it 'refreshes the cached headers' do
driven_request.populate_content_md5
expect(driven_request.content_md5).to eq('kZXQvrKoieG+Be1rsZVINw==')
end
end
context 'when putting' do
it 'populates content-md5' do
request.env['REQUEST_METHOD'] = 'PUT'
driven_request.populate_content_md5
expect(request.env['Content-MD5']).to eq('kZXQvrKoieG+Be1rsZVINw==')
end
it 'refreshes the cached headers' do
driven_request.populate_content_md5
expect(driven_request.content_md5).to eq('kZXQvrKoieG+Be1rsZVINw==')
end
end
context 'when deleting' do
it "doesn't populate content-md5" do
request.env['REQUEST_METHOD'] = 'DELETE'
driven_request.populate_content_md5
expect(request.env['Content-MD5']).to be_nil
end
end
end
describe '#set_date' do
before do
allow(Time).to receive_message_chain(:now, :utc, :httpdate).and_return(timestamp)
end
it 'sets the date header of the request' do
driven_request.set_date
expect(request.env['HTTP_DATE']).to eq(timestamp)
end
it 'refreshes the cached headers' do
driven_request.set_date
expect(driven_request.timestamp).to eq(timestamp)
end
end
describe '#set_auth_header' do
it 'sets the auth header' do
driven_request.set_auth_header('APIAuth 1044:54321')
expect(request.env['Authorization']).to eq('APIAuth 1044:54321')
end
end
end
describe 'md5_mismatch?' do
context 'when getting' do
before do
request.env['REQUEST_METHOD'] = 'GET'
end
it 'is false' do
expect(driven_request.md5_mismatch?).to be false
end
end
context 'when posting' do
before do
request.env['REQUEST_METHOD'] = 'POST'
end
context 'when calculated matches sent' do
before do
request.env['CONTENT_MD5'] = 'kZXQvrKoieG+Be1rsZVINw=='
end
it 'is false' do
expect(driven_request.md5_mismatch?).to be false
end
end
context "when calculated doesn't match sent" do
before do
request.env['CONTENT_MD5'] = '3'
end
it 'is true' do
expect(driven_request.md5_mismatch?).to be true
end
end
end
context 'when putting' do
before do
request.env['REQUEST_METHOD'] = 'PUT'
end
context 'when calculated matches sent' do
before do
request.env['CONTENT_MD5'] = 'kZXQvrKoieG+Be1rsZVINw=='
end
it 'is false' do
expect(driven_request.md5_mismatch?).to be false
end
end
context "when calculated doesn't match sent" do
before do
request.env['CONTENT_MD5'] = '3'
end
it 'is true' do
expect(driven_request.md5_mismatch?).to be true
end
end
end
context 'when deleting' do
before do
request.env['REQUEST_METHOD'] = 'DELETE'
end
it 'is false' do
expect(driven_request.md5_mismatch?).to be false
end
end
end
end
describe 'fetch_headers' do
it 'returns request headers' do
expect(driven_request.fetch_headers).to include('CONTENT-TYPE' => 'text/plain')
end
end
end
| 28.846473 | 94 | 0.584436 |
6a4f0268478cca3faf250d1c8fc17015f72ef920 | 6,309 | # frozen_string_literal: true
require 'test_helper'
class UserTest < ActiveSupport::TestCase
setup do
@mati = users(:mati)
@fede = users(:fede)
@juan = users(:juan)
@public = travels(:public)
@private = travels(:private)
@atlantis = travels(:atlantis)
@params = {
username: 'lionel',
email: '[email protected]',
name: 'Lionel',
lastname: 'Fuentes',
google_id: 'G0099'
}
end
test 'has_many authorizations' do
assert_equal :has_many, User.reflect_on_association(:authorizations).macro
end
test 'has_many comments' do
assert_equal :has_many, User.reflect_on_association(:comments).macro
end
test 'has_many favorites' do
assert_equal :has_many, User.reflect_on_association(:favorites).macro
end
test 'has_many travels' do
assert_equal :has_many, User.reflect_on_association(:travels).macro
end
test 'has_many notifications' do
assert_equal :has_many, User.reflect_on_association(:notifications).macro
end
test 'has_many followers' do
assert_equal :has_many, User.reflect_on_association(:followers).macro
end
test 'has_many followings' do
assert_equal :has_many, User.reflect_on_association(:followings).macro
end
test 'should create user' do
assert_difference('User.count') do
User.create!(@params)
end
assert User.exists?(email: @params.fetch(:email))
end
test 'should create user and set username if params dont include username' do
@params.delete(:username)
assert_difference('User.count') do
User.create!(@params)
end
assert User.exists?(email: @params.fetch(:email))
end
test 'should not create user with reserved username' do
@params[:username] = 'show'
assert_no_difference('User.count') do
assert_raise ActiveRecord::RecordInvalid do
User.create!(@params)
end
end
refute User.exists?(email: @params.fetch(:email))
end
test 'should not create user with invalid username' do
@params[:username] = 'li@nel'
assert_no_difference('User.count') do
assert_raise ActiveRecord::RecordInvalid do
User.create!(@params)
end
end
refute User.exists?(email: @params.fetch(:email))
end
test 'should not create user with duplicated username' do
@params[:username] = @mati.username
assert_no_difference('User.count') do
assert_raise ActiveRecord::RecordInvalid do
User.create!(@params)
end
end
refute User.exists?(email: @params.fetch(:email))
end
test 'should not create user without email' do
@params.delete(:email)
assert_no_difference('User.count') do
assert_raise ActiveRecord::RecordInvalid do
User.create!(@params)
end
end
refute User.exists?(name: @params.fetch(:name))
end
test 'should not create user with duplicated email' do
@params[:email] = @mati.email
assert_no_difference('User.count') do
assert_raise ActiveRecord::RecordInvalid do
User.create!(@params)
end
end
refute User.exists?(name: @params.fetch(:name))
end
test 'should not create user without name' do
@params.delete(:name)
assert_no_difference('User.count') do
assert_raise ActiveRecord::RecordInvalid do
User.create!(@params)
end
end
refute User.exists?(email: @params.fetch(:email))
end
test 'should not create user with name too short' do
@params[:name] = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'
assert_no_difference('User.count') do
assert_raise ActiveRecord::RecordInvalid do
User.create!(@params)
end
end
refute User.exists?(email: @params.fetch(:email))
end
test 'should not create user without lastname' do
@params.delete(:lastname)
assert_no_difference('User.count') do
assert_raise ActiveRecord::RecordInvalid do
User.create!(@params)
end
end
refute User.exists?(email: @params.fetch(:email))
end
test 'should not create user with lastname too long' do
@params[:lastname] = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'
assert_no_difference('User.count') do
assert_raise ActiveRecord::RecordInvalid do
User.create!(@params)
end
end
refute User.exists?(email: @params.fetch(:email))
end
test 'follow? should be true when user follow another' do
assert @juan.follow?(@mati)
end
test 'follow? should be false when user dont follow another' do
refute @mati.follow?(@juan)
end
test 'follow! should create following' do
refute @mati.follow?(@juan)
assert_difference('Following.count') do
@mati.follow!(@juan)
end
assert @mati.follow?(@juan)
end
test 'follow! should dont create following if user already follow to another' do
assert @juan.follow?(@mati)
assert_no_difference('Following.count') do
@juan.follow!(@mati)
end
assert @juan.follow?(@mati)
end
test 'follow! should dont create following if user follow itself' do
assert_no_difference('Following.count') do
assert_raise ActiveRecord::RecordInvalid do
@juan.follow!(@juan)
end
end
refute @juan.follow?(@juan)
end
test 'comment! should create comment if travel is public' do
assert_difference('Comment.count') do
@juan.comment!(@public, 'Es muy bueno')
end
assert @juan.comment?(@public)
end
test 'comment! should create comment if travel is private and has authorization' do
assert_difference('Comment.count') do
@juan.comment!(@private, 'Es muy bueno')
end
assert @juan.comment?(@private)
end
test 'comment! should not create comment if travel is private and has not authorization' do
assert_no_difference('Comment.count') do
assert_raise ActiveRecord::RecordInvalid do
@fede.comment!(@atlantis, 'Es muy bueno')
end
end
refute @fede.comment?(@atlantis)
end
test 'manageable? should be true if user is itself' do
assert @juan.manageable?(@juan)
end
test 'manageable? should be false if user is not itself' do
refute @juan.manageable?(@mati)
end
test 'posts should return user posts' do
assert @juan.posts
end
test 'home_posts should return user home posts' do
assert @juan.home_posts
end
end
| 24.453488 | 93 | 0.68331 |
38477aa11c51659e9d98ef5b2d3fa17d096298ef | 2,023 | # 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::Authorization::Mgmt::V2015_07_01_preview
module Models
#
# Role definition permissions.
#
class Permission
include MsRestAzure
# @return [Array<String>] Allowed actions.
attr_accessor :actions
# @return [Array<String>] Denied actions.
attr_accessor :not_actions
#
# Mapper for Permission class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'Permission',
type: {
name: 'Composite',
class_name: 'Permission',
model_properties: {
actions: {
client_side_validation: true,
required: false,
serialized_name: 'actions',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
},
not_actions: {
client_side_validation: true,
required: false,
serialized_name: 'notActions',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
}
}
}
}
end
end
end
end
| 27.337838 | 70 | 0.45823 |
fff878810e88ae91bd49a6c49c1f0fd22d4d6064 | 8,729 | require 'ansible_tower_client'
shared_examples_for "ansible configuration_script_source" do
let(:finished_task) { FactoryGirl.create(:miq_task, :state => "Finished") }
let(:manager) { FactoryGirl.create(:provider_ansible_tower, :with_authentication).managers.first }
let(:atc) { double("AnsibleTowerClient::Connection", :api => api) }
let(:api) { double("AnsibleTowerClient::Api", :projects => projects) }
let(:credential) { FactoryGirl.create(:ansible_scm_credential, :manager_ref => '1') }
context "create through API" do
let(:projects) { double("AnsibleTowerClient::Collection", :create! => project) }
let(:project) { AnsibleTowerClient::Project.new(nil, project_json) }
let(:css) { store_new_project(project, manager) }
let(:project_json) do
params.merge(
:id => 10,
"scm_type" => "git",
"scm_url" => "https://github.com/ansible/ansible-tower-samples"
).stringify_keys.to_json
end
let(:params) do
{
:description => "Description",
:name => "My Project",
:related => {}
}
end
let(:expected_notify) do
{
:type => :tower_op_success,
:options => {
:op_name => "#{described_class.name.demodulize} create_in_provider",
:op_arg => params.to_s,
:tower => "Tower(manager_id: #{manager.id})"
}
}
end
it ".create_in_provider to succeed and send notification" do
expect(AnsibleTowerClient::Connection).to receive(:new).and_return(atc)
store_new_project(project, manager)
expect(described_class).to receive(:refresh_in_provider).and_return(nil)
expect(EmsRefresh).to receive(:queue_refresh_task).with(manager).and_return([finished_task])
expect(ExtManagementSystem).to receive(:find).with(manager.id).and_return(manager)
expect(projects).to receive(:create!).with(params)
expect(Notification).to receive(:create).with(expected_notify)
expect(described_class.create_in_provider(manager.id, params)).to be_a(described_class)
end
it ".create_in_provider to fail(not found during refresh) and send notification" do
expect(AnsibleTowerClient::Connection).to receive(:new).and_return(atc)
expect(described_class).to receive(:refresh_in_provider).and_return(nil)
expect(EmsRefresh).to receive(:queue_refresh_task).and_return([finished_task])
expect(ExtManagementSystem).to receive(:find).with(manager.id).and_return(manager)
expected_notify[:type] = :tower_op_failure
expect(Notification).to receive(:create).with(expected_notify)
expect { described_class.create_in_provider(manager.id, params) }.to raise_error(ActiveRecord::RecordNotFound)
end
it ".create_in_provider with credential" do
params[:authentication_id] = credential.id
expect(AnsibleTowerClient::Connection).to receive(:new).and_return(atc)
store_new_project(project, manager)
expect(described_class).to receive(:refresh_in_provider).and_return(nil)
expect(EmsRefresh).to receive(:queue_refresh_task).with(manager).and_return([finished_task])
expect(ExtManagementSystem).to receive(:find).with(manager.id).and_return(manager)
expected_params = params.clone.merge(:credential => '1')
expected_params.delete(:authentication_id)
expect(projects).to receive(:create!).with(expected_params)
expected_notify[:options][:op_arg] = expected_params.to_s
expect(Notification).to receive(:create).with(expected_notify)
expect(described_class.create_in_provider(manager.id, params)).to be_a(described_class)
end
it ".create_in_provider_queue" do
EvmSpecHelper.local_miq_server
task_id = described_class.create_in_provider_queue(manager.id, params)
expect(MiqTask.find(task_id)).to have_attributes(:name => "Creating #{described_class.name} with name=#{params[:name]}")
expect(MiqQueue.first).to have_attributes(
:args => [manager.id, params],
:class_name => described_class.name,
:method_name => "create_in_provider",
:priority => MiqQueue::HIGH_PRIORITY,
:role => "ems_operations",
:zone => manager.my_zone
)
end
def store_new_project(project, manager)
described_class.create!(
:manager => manager,
:manager_ref => project.id.to_s,
:name => project.name,
)
end
end
context "Delete through API" do
let(:projects) { double("AnsibleTowerClient::Collection", :find => tower_project) }
let(:tower_project) { double("AnsibleTowerClient::Project", :destroy! => nil, :id => '1') }
let(:project) { described_class.create!(:manager => manager, :manager_ref => tower_project.id) }
let(:expected_notify) do
{
:type => :tower_op_success,
:options => {
:op_name => "#{described_class.name.demodulize} delete_in_provider",
:op_arg => {:manager_ref => tower_project.id}.to_s,
:tower => "Tower(manager_id: #{manager.id})"
}
}
end
it "#delete_in_provider to succeed and send notification" do
expect(AnsibleTowerClient::Connection).to receive(:new).and_return(atc)
expect(EmsRefresh).to receive(:queue_refresh_task).with(manager).and_return([finished_task])
expect(Notification).to receive(:create).with(expected_notify)
project.delete_in_provider
end
it "#delete_in_provider to fail (find the credential) and send notification" do
expect(AnsibleTowerClient::Connection).to receive(:new).and_return(atc)
allow(projects).to receive(:find).and_raise(AnsibleTowerClient::ClientError)
expected_notify[:type] = :tower_op_failure
expect(Notification).to receive(:create).with(expected_notify)
expect { project.delete_in_provider }.to raise_error(AnsibleTowerClient::ClientError)
end
it "#delete_in_provider_queue" do
task_id = project.delete_in_provider_queue
expect(MiqTask.find(task_id)).to have_attributes(:name => "Deleting #{described_class.name} with Tower internal reference=#{project.manager_ref}")
expect(MiqQueue.first).to have_attributes(
:instance_id => project.id,
:args => [],
:class_name => described_class.name,
:method_name => "delete_in_provider",
:priority => MiqQueue::HIGH_PRIORITY,
:role => "ems_operations",
:zone => manager.my_zone
)
end
end
context "Update through API" do
let(:projects) { double("AnsibleTowerClient::Collection", :find => tower_project) }
let(:tower_project) { double("AnsibleTowerClient::Project", :update_attributes! => {}, :id => 1) }
let(:project) { described_class.create!(:manager => manager, :manager_ref => tower_project.id) }
let(:expected_notify) do
{
:type => :tower_op_success,
:options => {
:op_name => "#{described_class.name.demodulize} update_in_provider",
:op_arg => {}.to_s,
:tower => "Tower(manager_id: #{manager.id})"
}
}
end
it "#update_in_provider to succeed and send notification" do
expect(AnsibleTowerClient::Connection).to receive(:new).and_return(atc)
expect(EmsRefresh).to receive(:queue_refresh_task).with(project).and_return([finished_task])
expect(Notification).to receive(:create).with(expected_notify)
expect(project.update_in_provider({})).to be_a(described_class)
end
it "#update_in_provider to fail (at update_attributes!) and send notification" do
expect(AnsibleTowerClient::Connection).to receive(:new).and_return(atc)
expect(tower_project).to receive(:update_attributes!).with({}).and_raise(AnsibleTowerClient::ClientError)
expected_notify[:type] = :tower_op_failure
expect(Notification).to receive(:create).with(expected_notify)
expect { project.update_in_provider({}) }.to raise_error(AnsibleTowerClient::ClientError)
end
it "#update_in_provider_queue" do
task_id = project.update_in_provider_queue({})
expect(MiqTask.find(task_id)).to have_attributes(:name => "Updating #{described_class.name} with Tower internal reference=#{project.manager_ref}")
expect(MiqQueue.first).to have_attributes(
:instance_id => project.id,
:args => [{:task_id => task_id}],
:class_name => described_class.name,
:method_name => "update_in_provider",
:priority => MiqQueue::HIGH_PRIORITY,
:role => "ems_operations",
:zone => manager.my_zone
)
end
end
end
| 45.701571 | 152 | 0.671784 |
e8087411df5a45420f1ab1a0fe770effa4320214 | 805 | require 'open-uri'
require 'base64'
class Prawn::Svg::UrlLoader
attr_accessor :enable_cache, :enable_web
attr_reader :url_cache
DATAURL_REGEXP = /(data:image\/(png|jpg);base64(;[a-z0-9]+)*,)/
URL_REGEXP = /^https?:\/\/|#{DATAURL_REGEXP}/
def initialize(opts = {})
@url_cache = {}
@enable_cache = opts.fetch(:enable_cache, false)
@enable_web = opts.fetch(:enable_web, true)
end
def valid?(url)
!!url.match(URL_REGEXP)
end
def load(url)
@url_cache[url] || begin
if m = url.match(DATAURL_REGEXP)
data = Base64.decode64(url[m[0].length .. -1])
elsif enable_web
data = open(url).read
else
raise "No handler available to retrieve URL #{url}"
end
@url_cache[url] = data if enable_cache
data
end
end
end
| 23 | 65 | 0.627329 |
abdb207a9f9b712e59c19e8bff61c5aa1618d849 | 1,829 | # frozen_string_literal: true
require 'cancan'
module Spree
module TestingSupport
module AuthorizationHelpers
module CustomAbility
def build_ability(&block)
block ||= proc{ |_u| can :manage, :all }
Class.new do
include CanCan::Ability
define_method(:initialize, block)
end
end
end
module Controller
include CustomAbility
def stub_authorization!(&block)
ability_class = build_ability(&block)
before do
allow(controller).to receive(:current_ability).and_return(ability_class.new(nil))
end
end
end
module Request
include CustomAbility
def stub_authorization!
ability = build_ability
after(:all) do
Spree::Ability.remove_ability(ability)
end
before(:all) do
Spree::Ability.register_ability(ability)
end
before do
allow(Spree.user_class).to receive(:find_by).
with(hash_including(:spree_api_key)).
and_return(Spree.user_class.new)
end
end
def custom_authorization!(&block)
ability = build_ability(&block)
after(:all) do
Spree::Ability.remove_ability(ability)
end
before(:all) do
Spree::Ability.register_ability(ability)
end
end
end
end
end
end
RSpec.configure do |config|
config.extend Spree::TestingSupport::AuthorizationHelpers::Controller, type: :controller
config.extend Spree::TestingSupport::AuthorizationHelpers::Request, type: :feature
config.extend Spree::TestingSupport::AuthorizationHelpers::Request, type: :request
end
| 26.507246 | 93 | 0.59158 |
1d0aaab6399c6117ffc7889e80c5d578d4d1bb36 | 5,325 | # Copyright (c) 2020-2021 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
module Glimmer
module SWT
# Proxy for org.eclipse.swt.graphics.Color
#
# Invoking `#swt_color` returns the SWT Color object wrapped by this proxy
#
# Follows the Proxy Design Pattern
class ColorProxy
SWT_COLOR_TRANSLATION = {
"widget_foreground" => [0, 0, 0],
"blue" => [0, 0, 255],
"widget_dark_shadow" => [0, 0, 0],
"title_foreground" => [0, 0, 0],
"yellow" => [255, 255, 0],
"widget_highlight_shadow" => [255, 255, 255],
"dark_cyan" => [0, 128, 128],
"list_foreground" => [0, 0, 0],
"dark_blue" => [0, 0, 128],
"dark_yellow" => [128, 128, 0],
"cyan" => [0, 255, 255],
"info_background" => [236, 235, 236],
"link_foreground" => [0, 104, 218],
"title_inactive_foreground" => [0, 0, 0],
"title_background_gradient" => [179, 215, 255],
"red" => [255, 0, 0],
"title_inactive_background_gradient" => [220, 220, 220],
"transparent" => [255, 255, 255],
"widget_light_shadow" => [232, 232, 232],
"dark_magenta" => [128, 0, 128],
"white" => [255, 255, 255],
"list_selection" => [179, 215, 255],
"gray" => [192, 192, 192],
"widget_border" => [0, 0, 0],
"widget_background" => [236, 236, 236],
"info_foreground" => [0, 0, 0],
"title_inactive_background" => [220, 220, 220],
"widget_disabled_foreground" => [220, 220, 220],
"list_background" => [255, 255, 255],
"magenta" => [255, 0, 255],
"title_background" => [0, 99, 225],
"text_disabled_background" => [255, 255, 255],
"black" => [0, 0, 0],
"dark_gray" => [128, 128, 128],
"list_selection_text" => [0, 0, 0],
"dark_red" => [128, 0, 0],
"widget_normal_shadow" => [159, 159, 159],
"dark_green" => [0, 128, 0],
"green" => [0, 255, 0]
}
attr_reader :args, :red, :green, :blue, :alpha
# Initializes a proxy for an SWT Color object
#
# Takes a standard color single argument, rgba 3 args, or rgba 4 args
#
# A standard color is a string/symbol representing one of the
# SWT.COLOR_*** constants like SWT.COLOR_RED, but in underscored string
# format (e.g :color_red).
# Glimmer can also accept standard color names without the color_ prefix,
# and it will automatically figure out the SWT.COLOR_*** constant
# (e.g. :red)
#
# rgb is 3 arguments representing Red, Green, Blue numeric values
#
# rgba is 4 arguments representing Red, Green, Blue, and Alpha numeric values
#
def initialize(*args)
@args = args
case @args.size
when 1
@alpha = nil
if @args.first.is_a?(String) || @args.first.is_a?(Symbol)
standard_color = @args.first.to_s.downcase.sub('COLOR_', '')
@red, @green, @blue = SWT_COLOR_TRANSLATION[standard_color]
else
@red, @green, @blue = [0, 0, 0]
end
when 3..4
@red, @green, @blue, @alpha = @args
end
end
def to_css
if alpha.nil?
"rgb(#{red}, #{green}, #{blue})"
else
"rgba(#{red}, #{green}, #{blue}, #{alpha_css})"
end
end
def alpha_css
alpha.to_f / 255
end
end
end
end
| 44.375 | 83 | 0.497465 |
ff8cf17b24ff5afb61b16d6bb18c69345b507c1a | 562 | # frozen_string_literal: true
require "bundler/setup"
Bundler.setup
require "simplecov"
SimpleCov.start
require "maremma"
require "rspec"
require "rack/test"
require "webmock/rspec"
require "vcr"
RSpec.configure do |config|
config.include WebMock::API
config.include Rack::Test::Methods
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
VCR.configure do |c|
c.cassette_library_dir = "spec/fixtures/vcr_cassettes"
c.hook_into :webmock
c.ignore_localhost = true
c.ignore_hosts "codeclimate.com"
c.configure_rspec_metadata!
end
| 18.733333 | 56 | 0.759786 |
38691dcb26fe2997044713495df0d1e816a6f572 | 1,573 | # Use a sha1 instead of a tag, as the author has not provided a tag for
# this release. In fact, the author no longer uses this software, so it
# is a candidate for removal if no new maintainer is found.
class Contacts < Formula
desc "Command-line tool to access macOS's Contacts (formerly 'Address Book')"
homepage "https://web.archive.org/web/20181108222900/gnufoo.org/contacts/contacts.html"
url "https://github.com/dhess/contacts/archive/4092a3c6615d7a22852a3bafc44e4aeeb698aa8f.tar.gz"
version "1.1a-3"
sha256 "e3dd7e592af0016b28e9215d8ac0fe1a94c360eca5bfbdafc2b0e5d76c60b871"
license "GPL-2.0"
bottle do
cellar :any_skip_relocation
sha256 "02f0086162efb3e8473f846252a6c4813e85a1bbf57a38e3420f20946eafa60f" => :catalina
sha256 "ad45d22cee04997d286b7e07f19328cd59dcb3a335a6a93e5ed24a8b995080f1" => :mojave
sha256 "27b7b256aa6f034b245c6cc1e6c7def038bbf183e73f94db942a220aa876ef0d" => :high_sierra
sha256 "21bf2ec23b9f096ed09acd44dbd7c2cc59891c01a821a6695e58d69c54647c0e" => :sierra
sha256 "7f6c6817310dacf83041d2017e8841b49e26df0d09039692576b6fe0fed52ecc" => :el_capitan
sha256 "9a9c89e40f9ccf4ec45cf63414eaf31266dfc9b71dc96d8c02f7ab2b38e8f346" => :mavericks
end
depends_on :xcode => :build if OS.mac?
depends_on :macos
def install
system "make", "SDKROOT=#{MacOS.sdk_path}"
bin.install "build/Deployment/contacts"
man1.install gzip("contacts.1")
end
test do
output = shell_output("#{bin}/contacts -h 2>&1", 2)
assert_match "displays contacts from the AddressBook database", output
end
end
| 43.694444 | 97 | 0.783853 |
395031df23319f23b6d8627a0de9639fd65432d1 | 197 | module ActivityStreams
class Object::Collection < Object
attr_optional :object_types
def validate_attributes!
super
validate_attribute! :object_types, Array
end
end
end | 19.7 | 46 | 0.730964 |
ac7d47f9ad110611f7e0008605c3ee7623e319b0 | 5,042 | # NOTE: These tests require RubyCocoa and should be run on a Mac.
# Because this provider is OS X-specific, the tests (and,
# subsequently, the provider itself, will only run on OS X).
require 'puppet'
require 'puppet/type/property_list_key'
require 'fileutils'
require 'tempfile'
RSpec.configure do |config|
config.mock_with :mocha
end
describe 'The rubycocoa provider for the property_list_key type' do
let(:test_dir) { Dir.mktmpdir }
let(:resource) do
Puppet::Type::Property_list_key.new(
{
:name => 'string_resource',
:path => File.join(test_dir, 'string.plist'),
:key => 'string',
:value => 'string value',
:value_type => 'string'
}
)
end
let(:provider) { Puppet::Type.type(:property_list_key).provider(:rubycocoa).new(resource) }
after :each do
FileUtils.rm_rf(test_dir)
end
it 'exists? should return false if the plist file does not exist' do
provider.exists?.should == false
end
it 'exists? should return true if the plist file exists' do
provider.create
provider.exists?.should == true
end
it 'should successfully destroy a resource' do
provider.create
provider.destroy
provider.exists?.should == false
end
it 'should write a string value if a string value_type is passed' do
provider.create
provider.value.first.class.should == String
end
it 'should write a string value' do
provider.create
provider.value.first.should == 'string value'
end
it 'should set a string value with value=' do
provider.create
provider.value = 'foobar'
provider.value.should == 'foobar'
end
it 'should write a boolean true value if a boolean value_type is passed' do
resource[:value] = true
resource[:value_type] = :boolean
provider.create
provider.value.class.should == TrueClass
end
it 'should set a boolean true value with value=' do
resource[:value] = false
resource[:value_type] = :boolean
provider.create
provider.value = true
provider.value.should == true
end
it 'should write a boolean false value if a boolean value_type is passed' do
resource[:value] = 'false'
resource[:value_type] = :boolean
provider.create
provider.value.class.should == FalseClass
end
it 'should set a boolean false value with value=' do
resource[:value] = true
resource[:value_type] = :boolean
provider.create
provider.value = false
provider.value.should == false
end
it 'should raise an error if an invalid boolean value is passed' do
resource[:value] = 'bad'
resource[:value_type] = :boolean
expect { provider.create }.to raise_error Puppet::Error, \
/Valid boolean values are 'true' or 'false', you specified 'bad'/
end
it 'should raise an error if an invalid boolean value is set' do
resource[:value] = true
resource[:value_type] = :boolean
provider.create
expect { provider.value = 'bad' }.to raise_error Puppet::Error, \
/Valid boolean values are 'true' or 'false', you specified 'bad'/
end
it 'should write an integer value if an integer value_type is passed' do
resource[:value] = '4'
resource[:value_type] = :integer
provider.create
provider.value.class.should == Fixnum
end
it 'should set an integer value' do
resource[:value] = '4'
resource[:value_type] = :integer
provider.create
provider.value.should == 4
end
it 'should set an integer value with value=' do
resource[:value] = '4'
resource[:value_type] = :integer
provider.create
provider.value = '8'
provider.value.should == 8
end
it 'should write an array value if an array value_type is passed' do
resource[:value] = ['array', 'of', 'values']
resource[:value_type] = :array
provider.create
provider.value.class.should == Array
end
it 'should set an array value' do
resource[:value] = ['array', 'of', 'values']
resource[:value_type] = :array
provider.create
provider.value.should == ['array', 'of', 'values']
end
it 'should set an array value with value=' do
resource[:value] = ['array', 'of', 'values']
resource[:value_type] = :array
provider.create
provider.value = ['new', 'array', 'of', 'values']
provider.value.should == ['new', 'array', 'of', 'values']
end
it 'should write a hash value if a hash value_type is passed' do
resource[:value] = { 'hash' => 'value' }
resource[:value_type] = :hash
provider.create
provider.value.class.should == Hash
end
it 'should set a hash value' do
resource[:value] = { 'hash' => 'value' }
resource[:value_type] = :hash
provider.create
provider.value.should == { 'hash' => 'value' }
end
it 'should set a hash value with value=' do
resource[:value] = { 'hash' => 'value' }
resource[:value_type] = :hash
provider.create
provider.value = { 'another' => 'hash_value' }
provider.value.should == { 'another' => 'hash_value' }
end
end
| 28.811429 | 93 | 0.659461 |
1c71c8c22a4125c3d92a2206792d202548151b9c | 712 | Pod::Spec.new do |s|
s.name = "MCSCommerceWeb"
s.version = "1.1.4"
s.summary = "Objective-C iOS wrapper for Mastercard's web SRC Initiator"
s.homepage = "https://github.com/Mastercard/MCSCommerceWeb"
s.license = "Apache License, Version 2.0"
s.author = { "Bret Deasy" => "[email protected]" }
s.platform = :ios, "11.0"
s.source = { :git => "https://github.com/Mastercard/MCSCommerceWeb.git", :tag => "1.1.4" }
s.source_files = "MCSCommerceWeb", "MCSCommerceWeb/**/*.{h,m}"
s.public_header_files = "MCSCommerceWeb/Public/**/*.h"
s.resources = "MCSCommerceWeb/Resources/**/*.{png,html,xcassets,xib}"
s.dependency 'SVGKit', '3.0.0beta3'
end
| 47.466667 | 98 | 0.622191 |
33719b7e24bd6a20b5a011dbf5b877fe281ff7ad | 337 | class GemCollector::UpdateRepository
def run(repository_id:, full_name:, html_url:, ssh_url:)
host = Addressable::URI.parse(html_url).host
repo = GemCollector::Repository.find_or_initialize_by(site: host, repository_id: repository_id)
repo.full_name = full_name
repo.ssh_url = ssh_url
repo.save!
repo
end
end
| 30.636364 | 99 | 0.74184 |
ab0bd85d8d59c4e68c41014cafe36e0d78a20322 | 321 | class PaymentMethod::Ebsin < PaymentMethod
preference :account_id, :string
preference :url, :string, :default => "https://secure.ebs.in/pg/ma/sale/pay/"
preference :secret_key, :string
preference :mode, :string
preference :currency_code, :string
def payment_profiles_supported?
false
end
end
| 22.928571 | 87 | 0.716511 |
035205f12d79c836dfeae487dbc748d93ecb7c56 | 86 | include Java
class A < java.AbstractClass2
def foo
#caret#
end
end
#result#
1 | 9.555556 | 29 | 0.686047 |
e89f9d61b08835865276a83b638a94cc3d612052 | 1,194 | require 'MustardClient/client'
module MustardClient
class EnvironmentsClient < Client
def find environment_id
command = {}
command[:method] = :get
command[:route] = @mustard_url + "/environments/#{environment_id}"
command[:headers] = {'User-Token' => @user_token}
execute(command)
end
def add environment_params
command = {}
command[:method] = :post
command[:route] = @mustard_url + "/environments"
command[:params] = {environment: environment_params}
command[:headers] = {'User-Token' => @user_token}
execute(command)
end
def delete environment_id
command = {}
command[:method] = :delete
command[:route] = @mustard_url + "/environments/#{environment_id}"
command[:headers] = {'User-Token' => @user_token}
execute(command)
end
def update environment_id, environment_params
command = {}
command[:method] = :put
command[:route] = @mustard_url + "/environments/#{environment_id}"
command[:headers] = {'User-Token' => @user_token}
command[:params] = {environment: environment_params}
execute(command)
end
end
end
| 22.528302 | 72 | 0.628978 |
d52349dabe32c4dc3c91c9ffce27f4d0e00f2ff0 | 849 | class GitSvnAbandon < Formula
desc "History-preserving svn-to-git migration"
homepage "https://github.com/nothingmuch/git-svn-abandon"
url "https://github.com/nothingmuch/git-svn-abandon/archive/0.0.1.tar.gz"
sha256 "65c11b5e575e6af4d21ef7624941c4581a5570748d50e38714bd33fee56e4485"
license "MIT"
head "https://github.com/nothingmuch/git-svn-abandon.git", branch: "master"
bottle do
sha256 cellar: :any_skip_relocation, all: "06ae7b10d6efedfb1ba1c781509f717f6b680c4a7408f15690f6800ee06594f3"
end
def install
bin.install Dir["git-svn-abandon-*"]
end
test do
system "git", "init"
system "git", "symbolic-ref", "HEAD", "refs/heads/trunk"
system "git", "commit", "--allow-empty", "-m", "foo"
system "git", "svn-abandon-fix-refs"
assert_equal "* master", shell_output("git branch -a").chomp
end
end
| 33.96 | 112 | 0.722026 |
1d8dd4e9c4b884d5e8617be19188633d7d689a14 | 603 | Pod::Spec.new do |s|
s.name = 'TOPropertyAccessor'
s.version = '1.1.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'An abstract class that enables hooking the properties of subclasses.'
s.homepage = 'https://github.com/TimOliver/TOPropertyAccessor'
s.author = 'Tim Oliver'
s.source = { :git => 'https://github.com/TimOliver/TOPropertyAccessor.git', :tag => s.version }
s.source_files = 'TOPropertyAccessor/**/*.{h,m}'
s.requires_arc = true
s.ios.deployment_target = '9.0'
s.osx.deployment_target = '10.9'
s.tvos.deployment_target = '9.0'
end
| 35.470588 | 99 | 0.6534 |
087719d248086d3514362b7bcc812a589295dd53 | 1,541 | namespace :associated_user do
desc "Testing populate change requests associated users into the database"
task :populate_users_dryrun => :environment do
populate(true)
end
desc "Populate change requests associated users into the database"
task :populate_users => :environment do
populate(false)
end
def populate(is_dryrun)
puts "This is a dryrun".colorize(:light_red) if is_dryrun
count_success = 0
count_fail = 0
ChangeRequest.all.each do |cr|
associated_user_ids = [cr.user.id]
associated_user_ids.concat(cr.approvals.collect(&:user_id))
associated_user_ids.concat(cr.implementers.collect(&:id))
associated_user_ids.concat(cr.testers.collect(&:id))
associated_user_ids.concat(cr.collaborators.collect(&:id))
associated_user_ids.uniq!
puts "Change Requests ##{cr.id} associated users: #{associated_user_ids}".colorize(:light_green)
if !is_dryrun
if cr.update_attributes(associated_user_ids: associated_user_ids)
puts "~~> Associated users assigned to CR##{cr.id}".colorize(:light_blue)
count_success += 1
else
puts "~~> Failed to assign associated users CR##{cr.id}".colorize(:light_red)
puts "~~> Error cause: #{cr.errors.messages}"
count_fail += 1
end
end
end
puts "\n\nRake result:".colorize(:light_blue)
puts "Succes : #{count_success} change requests".colorize(:light_green)
puts "Fail : #{count_fail} change requests".colorize(:light_red)
end
end
| 38.525 | 102 | 0.691759 |
abd795485581bbe5370608072177feddc26d4a11 | 1,944 | class Sngrep < Formula
desc "Command-line tool for displaying SIP calls message flows"
homepage "https://github.com/irontec/sngrep"
url "https://github.com/irontec/sngrep/archive/v1.4.9.tar.gz"
sha256 "3c6f28b5c795a5b1844a8997aa430aba72e083c8bd52939990900450c5f4c85a"
license "GPL-3.0-or-later"
bottle do
sha256 cellar: :any, arm64_monterey: "328666d36c468478d3c63ee9187b57dec4d8fd58a0554296c917f77062eb7a71"
sha256 cellar: :any, arm64_big_sur: "449af17f3cb8673ec2beb158ba5a48bfc620739bac89bce15eeaea4297c65972"
sha256 monterey: "caf2d4342c7cb6bacdbe8e7fb2187f263db2454e626df689090db07fb44cbd73"
sha256 big_sur: "d226ad4dbc036097beeefdb5d181954c3ed8eaeef9d236189598783d03a6a4c3"
sha256 catalina: "95e8048031ea84674d2147c224aae73c14616164c74234f25d3001e15b779a35"
sha256 mojave: "20e51aa586d1a16ad0ed97aacc941649b8872a78e36f3ec34dbdb8ea2a674216"
sha256 cellar: :any_skip_relocation, x86_64_linux: "0ce3e5f4cb6aded2538bef214778a5b4204b460421ec57f6314685e4a90085b9"
end
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "ncurses" if DevelopmentTools.clang_build_version >= 1000
depends_on "[email protected]"
uses_from_macos "libpcap"
uses_from_macos "ncurses"
def install
ENV.append_to_cflags "-I#{Formula["ncurses"].opt_include}/ncursesw" if OS.linux?
system "./bootstrap.sh"
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}",
"--with-openssl=#{Formula["[email protected]"].opt_prefix}"
system "make", "install"
end
test do
system bin/"sngrep", "-NI", test_fixtures("test.pcap")
end
end
| 46.285714 | 123 | 0.667181 |
335679e9ff5fbb9372ce038e17a66c2e6f758047 | 2,185 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Security::StoreScansWorker do
let_it_be(:sast_scan) { create(:security_scan, scan_type: :sast) }
let_it_be(:pipeline) { sast_scan.pipeline }
let_it_be(:sast_build) { pipeline.security_scans.sast.last&.build }
describe '#perform' do
subject(:run_worker) { described_class.new.perform(pipeline.id) }
before do
allow(Security::StoreScansService).to receive(:execute)
allow_next_found_instance_of(Ci::Pipeline) do |record|
allow(record).to receive(:can_store_security_reports?).and_return(can_store_security_reports)
end
end
context 'when security reports can not be stored for the pipeline' do
let(:can_store_security_reports) { false }
it 'does not call `Security::StoreScansService`' do
run_worker
expect(Security::StoreScansService).not_to have_received(:execute)
end
it_behaves_like 'does not record an onboarding progress action'
end
context 'when security reports can be stored for the pipeline' do
let(:can_store_security_reports) { true }
it 'calls `Security::StoreScansService`' do
run_worker
expect(Security::StoreScansService).to have_received(:execute)
end
scan_types_actions = {
"sast" => :security_scan_enabled,
"dependency_scanning" => :secure_dependency_scanning_run,
"container_scanning" => :secure_container_scanning_run,
"dast" => :secure_dast_run,
"secret_detection" => :secure_secret_detection_run,
"coverage_fuzzing" => :secure_coverage_fuzzing_run,
"api_fuzzing" => :secure_api_fuzzing_run,
"cluster_image_scanning" => :secure_cluster_image_scanning_run
}.freeze
scan_types_actions.each do |scan_type, action|
context "security #{scan_type}" do
let_it_be(:scan) { create(:security_scan, scan_type: scan_type) }
let_it_be(:pipeline) { scan.pipeline }
it_behaves_like 'records an onboarding progress action', [action] do
let(:namespace) { pipeline.project.namespace }
end
end
end
end
end
end
| 33.615385 | 101 | 0.691991 |
391b88a2ee7950dad06ac30947683be0cad011d9 | 581 | describe Eshop::ProductDetector do
describe '#find_product_class' do
it { expect(Eshop::ProductDetector.new('book','20').find_product_class).to be_an_instance_of(Eshop::Product::Book)}
it { expect(Eshop::ProductDetector.new('pill','19').find_product_class).to be_an_instance_of(Eshop::Product::Medicine)}
it { expect(Eshop::ProductDetector.new('chocolate','10').find_product_class).to be_an_instance_of(Eshop::Product::Food)}
it { expect(Eshop::ProductDetector.new('playstation','299').find_product_class).to be_an_instance_of(Eshop::Product::Product)}
end
end
| 64.555556 | 130 | 0.7642 |
4a5a940de40d17b907ac4e2f346d489e96b54e1c | 609 | # frozen_string_literal: true
RSpec.shared_examples 'a resource with orderable creators' do
before(:all) do
raise 'resource must be set with `let(:resource)`' unless defined? resource
end
it 'orders them by #position asc' do
creator_a, creator_b = resource.creators
creator_a.update!(display_name: 'A', position: 1)
creator_b.update!(display_name: 'B', position: 2)
resource.reload
expect(resource.creators.map(&:display_name)).to eq %w(A B)
creator_a.update!(position: 100)
resource.reload
expect(resource.creators.map(&:display_name)).to eq %w(B A)
end
end
| 26.478261 | 79 | 0.70936 |
e2758aceecfd1556239bf07cfec3157cc1a5277f | 260 | class AddChoreSessionFieldsToTarget < ActiveRecord::Migration[6.0][5.0]
def change
add_column :targets, :video_embed, :text
add_column :targets, :last_session_at, :datetime
add_index :targets, :chore
add_index :targets, :session_at
end
end
| 28.888889 | 71 | 0.742308 |
186e556d6afd9c317f4047bed2d981656193949d | 1,680 | #
# Be sure to run `pod lib lint qrframework_part_5.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'qrframework_part_5'
s.version = '0.1.0'
s.summary = 'A short description of qrframework_part_5.'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
TODO: Add long description of the pod here.
DESC
s.homepage = 'https://github.com/gilbertttsubay/qris-sdk-part-1.git'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'gilbertttsubay' => '[email protected]' }
s.source = { :git => 'https://github.com/gilbertttsubay/qris-sdk-part-1.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '13.0'
s.source_files = 'qrframework_part_5/Classes/**/*'
# s.resource_bundles = {
# 'qrframework_part_5' => ['qrframework_part_5/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
| 39.069767 | 114 | 0.651786 |
62670f011e36a2412fd6ff934c0ce6ea1bae30f4 | 10,477 | class HostAggregateController < ApplicationController
before_action :check_privileges
before_action :get_session_data
after_action :cleanup_action
after_action :set_session_data
include Mixins::GenericFormMixin
include Mixins::GenericListMixin
include Mixins::GenericSessionMixin
include Mixins::GenericShowMixin
include Mixins::MoreShowActions
include Mixins::EmsCommon
include Mixins::BreadcrumbsMixin
def self.display_methods
%w[instances hosts]
end
def host_aggregate_form_fields
assert_privileges("host_aggregate_edit")
host_aggregate = find_record_with_rbac(HostAggregate, params[:id])
render :json => {:name => host_aggregate.name,
:ems_id => host_aggregate.ems_id}
end
def new
assert_privileges("host_aggregate_new")
@host_aggregate = HostAggregate.new
@in_a_form = true
supported_types = HostAggregate.descendants.select { |klass| klass.supports?(:create) }.map(&:module_parent).map(&:name)
@ems_choices = Rbac::Filterer.filtered(
ManageIQ::Providers::CloudManager.where(:type => supported_types)
).pluck(:name, :id).to_h
drop_breadcrumb(
:name => _("Create New Host Aggregate"),
:url => "/host_aggregate/new"
)
end
def create
assert_privileges("host_aggregate_new")
@in_a_form = true
end
def edit
assert_privileges("host_aggregate_edit")
@host_aggregate = find_record_with_rbac(HostAggregate, params[:id])
@in_a_form = true
drop_breadcrumb(
:name => _("Edit Host Aggregate \"%{name}\"") % {:name => @host_aggregate.name},
:url => "/host_aggregate/edit/#{@host_aggregate.id}"
)
end
def update
assert_privileges("host_aggregate_edit")
@in_a_form = true
@host_aggregate = find_record_with_rbac(HostAggregate, params[:id])
end
def delete_host_aggregates
assert_privileges("host_aggregate_delete")
host_aggregates = checked_or_params
if host_aggregates.empty?
add_flash(_("No Host Aggregates were selected for deletion."), :error)
end
host_aggregates_to_delete = []
host_aggregates.each do |host_aggregate_id|
host_aggregate = HostAggregate.find(host_aggregate_id)
if host_aggregate.nil?
add_flash(_("Host Aggregate no longer exists."), :error)
elsif !host_aggregate.supports?(:delete)
add_flash(_("Delete aggregate not supported by Host Aggregate \"%{name}\"") % {:name => host_aggregate.name}, :error)
else
host_aggregates_to_delete.push(host_aggregate)
end
end
process_host_aggregates(host_aggregates_to_delete, "destroy") unless host_aggregates_to_delete.empty?
flash_to_session
# refresh the list
if @lastaction == "show" && @layout == "host_aggregate" # Textual Summary of Host Aggregate
@single_delete = true unless flash_errors?
redirect_to(previous_breadcrumb_url)
else # list of Host Aggregates
@refresh_partial = "layouts/gtl" if @lastaction == "show_list"
redirect_to(last_screen_url)
end
end
def add_host_select
assert_privileges("host_aggregate_add_host")
@host_aggregate = find_record_with_rbac(HostAggregate, params[:id])
@in_a_form = true
@host_choices = {}
ems_clusters = @host_aggregate.ext_management_system.provider.try(:infra_ems).try(:ems_clusters)
if ems_clusters.present?
ems_clusters.select(&:compute?).each do |ems_cluster|
(ems_cluster.hosts - @host_aggregate.hosts).each do |host|
@host_choices["#{host.name}: #{host.hostname}"] = host.id
end
end
end
if @host_choices.empty?
add_flash(_("No hosts available to add to Host Aggregate \"%{name}\"") % {
:name => @host_aggregate.name
}, :error)
session[:flash_msgs] = @flash_array
@in_a_form = false
redirect_to(last_screen_url)
else
drop_breadcrumb(
:name => _("Add Host to Host Aggregate \"%{name}\"") % {:name => @host_aggregate.name},
:url => "/host_aggregate/add_host/#{@host_aggregate.id}"
)
end
end
def add_host
assert_privileges("host_aggregate_add_host")
@host_aggregate = find_record_with_rbac(HostAggregate, params[:id])
case params[:button]
when "cancel"
flash_and_redirect(_("Add Host to Host Aggregate \"%{name}\" was cancelled by the user") % {
:name => @host_aggregate.name
})
when "addHost"
options = form_params(params)
host = find_record_with_rbac(Host, options[:host_id])
if @host_aggregate.supports?(:add_host)
task_id = @host_aggregate.add_host_queue(session[:userid], host)
unless task_id.kind_of?(Integer)
add_flash(_("Add Host to Host Aggregate \"%{name}\" failed: Task start failed") % {
:name => @host_aggregate.name,
}, :error)
end
if @flash_array
javascript_flash(:spinner_off => true)
else
initiate_wait_for_task(:task_id => task_id, :action => "add_host_finished")
end
else
@in_a_form = true
add_flash(_("Add Host not supported by Host Aggregate \"%{name}\"") % {
:name => @host_aggregate.name
}, :error)
@breadcrumbs&.pop
javascript_flash
end
end
end
def add_host_finished
task_id = session[:async][:params][:task_id]
host_aggregate_name = session[:async][:params][:name]
host_id = session[:async][:params][:host_id]
task = MiqTask.find(task_id)
host = Host.find(host_id)
if MiqTask.status_ok?(task.status)
flash_and_redirect(_("Host \"%{hostname}\" added to Host Aggregate \"%{name}\"") % {
:hostname => host.name,
:name => host_aggregate_name
})
else
flash_and_redirect(_("Unable to update Host Aggregate \"%{name}\": %{details}") % {
:name => host_aggregate_name,
:details => task.message
}, :error)
end
end
def remove_host_select
assert_privileges("host_aggregate_remove_host")
@host_aggregate = find_record_with_rbac(HostAggregate, params[:id])
@in_a_form = true
@host_choices = {}
@host_aggregate.hosts.each do |host|
@host_choices["#{host.name}: #{host.hostname}"] = host.id
end
if @host_choices.empty?
add_flash(_("No hosts to remove from Host Aggregate \"%{name}\"") % {
:name => @host_aggregate.name
}, :error)
session[:flash_msgs] = @flash_array
@in_a_form = false
redirect_to(last_screen_url)
else
drop_breadcrumb(
:name => _("Remove Host from Host Aggregate \"%{name}\"") % {:name => @host_aggregate.name},
:url => "/host_aggregate/remove_host/#{@host_aggregate.id}"
)
end
end
def remove_host
assert_privileges("host_aggregate_remove_host")
@host_aggregate = find_record_with_rbac(HostAggregate, params[:id])
case params[:button]
when "cancel"
flash_and_redirect(_("Remove Host from Host Aggregate \"%{name}\" was cancelled by the user") % {
:name => @host_aggregate.name
})
when "removeHost"
options = form_params(params)
host = find_record_with_rbac(Host, options[:host_id])
if @host_aggregate.supports?(:remove_host)
task_id = @host_aggregate.remove_host_queue(session[:userid], host)
unless task_id.kind_of?(Integer)
add_flash(_("Remove Host to Host Aggregate \"%{name}\" failed: Task start failed") % {
:name => @host_aggregate.name,
}, :error)
end
if @flash_array
javascript_flash(:spinner_off => true)
else
initiate_wait_for_task(:task_id => task_id, :action => "remove_host_finished")
end
else
@in_a_form = true
add_flash(_("Remove Host not supported by Host Aggregate \"%{name}\"") % {
:name => @host_aggregate.name
}, :error)
@breadcrumbs&.pop
javascript_flash
end
end
end
def remove_host_finished
task_id = session[:async][:params][:task_id]
host_aggregate_name = session[:async][:params][:name]
host_id = session[:async][:params][:host_id]
task = MiqTask.find(task_id)
host = Host.find(host_id)
if MiqTask.status_ok?(task.status)
flash_and_redirect(_("Host \"%{hostname}\" removed from Host Aggregate \"%{name}\"") % {
:hostname => host.name,
:name => host_aggregate_name
})
else
flash_and_redirect(_("Unable to update Host Aggregate \"%{name}\": %{details}") % {
:name => host_aggregate_name,
:details => task.message
}, :error)
end
end
def download_data
assert_privileges('host_aggregate_show_list')
super
end
def download_summary_pdf
assert_privileges('host_aggregate_show')
super
end
private
def textual_group_list
[%i[relationships], %i[tags]]
end
helper_method :textual_group_list
def form_params(in_params)
options = {}
%i[name availability_zone ems_id host_id metadata].each do |param|
options[param] = in_params[param] if in_params[param]
end
options
end
# dispatches tasks to multiple host aggregates
def process_host_aggregates(host_aggregates, task)
return if host_aggregates.empty?
return unless task == "destroy"
host_aggregates.each do |host_aggregate|
audit = {
:event => "host_aggregate_record_delete_initiateed",
:message => "[#{host_aggregate.name}] Record delete initiated",
:target_id => host_aggregate.id,
:target_class => "HostAggregate",
:userid => session[:userid]
}
AuditEvent.success(audit)
host_aggregate.delete_aggregate_queue(session[:userid])
end
add_flash(n_("Delete initiated for %{number} Host Aggregate.",
"Delete initiated for %{number} Host Aggregates.",
host_aggregates.length) % {:number => host_aggregates.length})
end
def breadcrumbs_options
{
:breadcrumbs => [
{:title => _("Compute")},
{:title => _("Clouds")},
{:title => _("Host Aggregates"), :url => controller_url},
],
:record_info => @host_aggregate,
}.compact
end
menu_section :clo
feature_for_actions "#{controller_name}_show_list", *ADV_SEARCH_ACTIONS
feature_for_actions "#{controller_name}_timeline", :tl_chooser
feature_for_actions "#{controller_name}_perf", :perf_top_chart
end
| 31.748485 | 125 | 0.656008 |
ab2197e9689a9fa07d24bcf578986b72a1a8c1c9 | 531 | require 'fog'
bucket_name = ARGV[0]
host = ARGV[1]
admin_access_key = ARGV[2]
admin_secret_key = ARGV[3]
client = Fog::Storage.new(
provider: 'AWS',
path_style: true,
host: host,
port: 8080,
scheme: 'http',
aws_access_key_id: admin_access_key,
aws_secret_access_key: admin_secret_key)
puts "Fog client: #{client.inspect}"
begin
puts "Bucket name: #{bucket_name}"
client.directories.create(key: bucket_name)
puts "Created bucket #{bucket_name}"
rescue => e
puts "Error creating bucket: #{e.message}"
end
| 18.964286 | 45 | 0.713748 |
1d47171cb310b9e03f61823d12d000986b7a4295 | 5,376 | =begin
#DocuSign Admin API
#An API for an organization administrator to manage organizations, accounts and users
OpenAPI spec version: v2.1
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
=end
require 'date'
module DocuSign_Admin
class PermissionProfileResponse
attr_accessor :id
attr_accessor :name
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'id' => :'id',
:'name' => :'name'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'id' => :'Integer',
:'name' => :'String'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
if attributes.has_key?(:'id')
self.id = attributes[:'id']
end
if attributes.has_key?(:'name')
self.name = attributes[:'name']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
id == o.id &&
name == o.name
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[id, name].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
temp_model = DocuSign_Admin.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 27.854922 | 107 | 0.610491 |
1da89883fe240bea6d855156785ef40ab5a902ce | 315 | module Api
module V2
class GeographicalAreasController < ApiController
def index
render json: CachedGeographicalAreaService.new(actual_date).call
end
def countries
render json: CachedGeographicalAreaService.new(actual_date, countries: true).call
end
end
end
end
| 22.5 | 89 | 0.711111 |
87c9eb9504be28a92264a4a247ee33c350b42ad5 | 3,682 | #
# Copyright 2017, Schuberg Philis B.V.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# author: Kristian Vlaardingerbroek
title '3.3 IPv6'
control 'cis-dil-benchmark-3.3.1' do
title 'Ensure IPv6 router advertisements are not accepted'
desc "This setting disables the system's ability to accept IPv6 router advertisements.\n\nRationale: It is recommended that systems not accept router advertisements as they could be tricked into routing traffic to compromised machines. Setting hard routes within the system (usually a single default route to a trusted router) protects the system from bad routes."
impact 0.0
tag cis: 'distribution-independent-linux:3.3.1'
tag level: 1
only_if do
ipv6_enabled = true
%w(/boot/grub/grub.conf /boot/grub/grub.cfg /boot/grub/menu.lst /boot/boot/grub/grub.conf /boot/boot/grub/grub.cfg /boot/boot/grub/menu.lst).each do |f|
grub_file = file(f)
if !grub_file.content.nil? && grub_file.content.match(/ipv6\.disable=1/)
ipv6_enabled = false
break
end
end
ipv6_enabled
end
%w(net.ipv6.conf.all.accept_ra net.ipv6.conf.default.accept_ra).each do |kp|
describe kernel_parameter(kp) do
its(:value) { should_not be_nil }
its(:value) { should eq 0 }
end
end
end
control 'cis-dil-benchmark-3.3.2' do
title 'Ensure IPv6 redirects are not accepted'
desc "This setting prevents the system from accepting ICMP redirects. ICMP redirects tell the system about alternate routes for sending traffic.\n\nRationale: It is recommended that systems not accept ICMP redirects as they could be tricked into routing traffic to compromised machines. Setting hard routes within the system (usually a single default route to a trusted router) protects the system from bad routes."
impact 0.0
tag cis: 'distribution-independent-linux:3.3.2'
tag level: 1
only_if do
ipv6_enabled = true
%w(/boot/grub/grub.conf /boot/grub/grub.cfg /boot/grub/menu.lst /boot/boot/grub/grub.conf /boot/boot/grub/grub.cfg /boot/boot/grub/menu.lst).each do |f|
grub_file = file(f)
if !grub_file.content.nil? && grub_file.content.match(/ipv6\.disable=1/)
ipv6_enabled = false
break
end
end
ipv6_enabled
end
%w(net.ipv6.conf.all.accept_redirects net.ipv6.conf.default.accept_redirects).each do |kp|
describe kernel_parameter(kp) do
its(:value) { should_not be_nil }
its(:value) { should eq 0 }
end
end
end
#We want to be able to use IPv6
#control 'cis-dil-benchmark-3.3.3' do
# title 'Ensure IPv6 is disabled'
# desc "Although IPv6 has many advantages over IPv4, few organizations have implemented IPv6.\n\nRationale: If IPv6 is not to be used, it is recommended that it be disabled to reduce the attack surface of the system."
# impact 0.0
# tag cis: 'distribution-independent-linux:3.3.3'
# tag level: 1
# describe.one do
# %w(/boot/grub/grub.conf /boot/grub/grub.cfg /boot/grub/menu.lst /boot/boot/grub/grub.conf /boot/boot/grub/grub.cfg /boot/boot/grub/menu.lst).each do |f|
# describe file(f) do
# its(:content) { should match(/ipv6\.disable=1/) }
# end
# end
# end
#end
| 37.958763 | 418 | 0.719446 |
4abeedcca51c17b50c8fc62c9a6559e05a57aa75 | 915 | require 'rails_helper'
require 'helpers/login_helper'
describe "the delete a project process" do
it "allows admins to delete projects" do
category = FactoryGirl.create(:category)
login_admin
visit category_path(category)
click_on 'Add a project'
fill_in 'Name', :with => 'Basic Website'
fill_in 'Description', :with => 'Creating basic web pages.'
fill_in 'Github', :with => 'test'
click_on 'Create Project'
click_on 'Delete Project'
expect(page).to have_content 'no projects yet'
end
# it "does not allow users to delete projects" do
# category = FactoryGirl.create(:category)
# project = Project.create({name: 'alskjfdads', description: 'alksjdfl', id: 2584, category_id: category.id })
# login_user
# visit category_project_path(category.id, project.id)
# click_on 'Delete Project'
# expect(page).to have_content 'Access Denied'
# end
end
| 33.888889 | 114 | 0.700546 |
113fc2153f1668345fdffbbb6377550f9c6dde8a | 239 | class CreateEmployees < ActiveRecord::Migration[5.2]
def change
create_table :employees do |t|
t.string :name
t.string :position
t.string :address
t.integer :phone_number
t.timestamps
end
end
end
| 18.384615 | 52 | 0.65272 |
08706821e0fd37b4719d35973b92fdf8434f3469 | 1,328 | # -*- coding: utf-8 -*-
# Copyright (C) 2010, 2011 Rocky Bernstein <[email protected]>
require 'rubygems'; require 'require_relative'
require_relative 'up'
# Debugger "down" command. Is the same as the "up" command with the
# direction (set by DIRECTION) reversed.
class Trepan::Command::DownCommand < Trepan::Command::UpCommand
Trepan::Util.suppress_warnings {
old_verbose = $VERBOSE
$VERBOSE = nil
HELP = <<-HELP
#{NAME} [count]
Move the current frame down in the stack trace (to a newer frame). 0
is the most recent frame. If no count is given, move down 1.
See also 'up' and 'frame'.
HELP
ALIASES = %w(d)
NAME = File.basename(__FILE__, '.rb')
SHORT_HELP = 'Move frame in the direction of the caller of the last-selected frame'
}
def initialize(proc)
super
@direction = -1 # +1 for up.
end
end
if __FILE__ == $0
# Demo it.
require_relative '../mock'
dbgr, cmd = MockDebugger::setup
# def sep ; puts '=' * 40 end
# cmd.run [cmd.name]
# %w(-1 0 1 -2).each do |count|
# puts "#{cmd.name} #{count}"
# cmd.run([cmd.name, count])
# sep
# end
# def foo(cmd, cmd.name)
# puts "#{cmd.name}"
# cmd.run([cmd.name])
# sep
# puts "#{cmd.name} -1"
# cmd.run([cmd.name, '-1'])
# end
# foo(cmd, cmd.name)
end
| 24.145455 | 90 | 0.613705 |
013fcd74246928a477b540529c303c26cb6e1747 | 3,616 | module CliTasks
class Viewer
attr_accessor :files
attr_accessor :notes
def initialize(*args)
@files = args
if args.any?
Runner.run! args
else
Runner.run! world.task_path
end
end
def self.tag_groups(*args)
new(*args).tag_groups
end
def self.story(s)
story(s)
end
def self.screen(*args)
new(*args).screen
end
def self.print(*args)
viewer = new(*args)
# ap args: args, files: viewer.files, stories: viewer.stories
viewer.print
end
def print
puts screen
end
def tag_groups
stories.flat_map do |story|
story.tagged_notes
end.group_by do |story|
story.tag
end.sort_by{|k,v| k }.flat_map do |group,grouped_stories|
lines = [
]
lines += grouped_stories.sort_by do |gs|
gs.name[/[a-z]/i].downcase
end.map do |s|
story(s)
end
[
'',
format(" | TAG: | %s (%d)\n", group, grouped_stories.count),
lines, #.join(separator),
'',
] #.join(outer_separator)
end
end
def screen
lines = [header]
lines += stories.reverse.map{|s|
story(s)
}
lines.join(separator)
end
def header
sprintf(" %-80s | %-s\n", :name, :tags)
end
def self.wrap_in_column(str='',width=10)
str.to_s.scan(/\S.{0,#{width - 1}}(?!\S)/)
end
def wrap_in_column(str='',width=10)
self.class.wrap_in_column(str, width)
end
def self.total_lines(*cols)
[cols].flatten(1).map(&:length).max
end
def total_lines(*cols)
self.class.total_lines(*cols)
end
def self.separator
sprintf(" %-82s-+-%-s\n", ?-*82, ?-*29)
end
def separator
@separator ||= self.class.separator
end
def self.outer_separator
sprintf(" %-111s===\n", ?=*111)
end
def outer_separator
self.class.outer_separator
end
def simple_story(s)
self.class.simple_story(s)
end
def self.simple_story(s)
# make a method for each of the _col methods
#status_col = wrap_in_column(s.status, 10)
#id_col = wrap_in_column(s.id, 20)
#points_col = wrap_in_column(?* * s.points.to_i, 6)
name_width = (ENV['COLUMNS'] || 100).to_i - (13 + 1 + 1 + 1) # with of id plus spaces between columns
format(" %-13s %-#{name_width}s \n", s.id, s.name.slice(0,name_width))
end
def story(s)
return simple_story(s)
self.class.story(s)
end
def self.story(s)
return simple_story(s)
# make a method for each of the _col methods
#status_col = wrap_in_column(s.status, 10)
#id_col = wrap_in_column(s.id, 20)
#points_col = wrap_in_column(?* * s.points.to_i, 6)
name_col = wrap_in_column(s.name, 72)
name_col << ''
tags_col = wrap_in_column(s.tags.sort * "\n", 30)
name_labels = ['Name:']
#total = total_lines(status_col, id_col, points_col, name_col, tags_col)
#total = total_lines(id_col, name_col, tags_col)
total = total_lines(name_col, tags_col)
lines = Array.new(total).map{ " | %5s | %-72s | %-s\n" }
data = lines.zip(name_labels, name_col, tags_col)
# data.push([" ------ + %-72s +\n", ?- * 72])
data.push([" | File: | %-72s |\n", s.file])
data.map{|r| sprintf(*r) }.join
# data += separator
# data += format(" File: %s\n", s.file)
end
def stories
@stories ||= world.stories
end
def world
CliTasks.world
end
end
end
| 23.031847 | 108 | 0.562777 |
0136d1a4a7fdbb83f2fd705b49d39f26d1fca34a | 600 | cask 'mattr-slate' do
version '1.2.0'
sha256 'd409ccda9ed09f5647175f8834650e141a7375ced9665bf6af237525665d4966'
url "https://github.com/mattr-/slate/releases/download/v#{version}/Slate.zip"
appcast 'https://github.com/mattr-/slate/releases.atom',
checkpoint: '12a305e83d56fb2eab4c1341df73ea1faf5591838dc0ec636d7e06d72200bdb0'
name 'Slate'
homepage 'https://github.com/mattr-/slate'
license :gpl
app 'Slate.app'
zap delete: [
'~/.slate',
'~/.slate.js',
'~/Library/Application Support/com.slate.Slate',
]
end
| 30 | 88 | 0.66 |
61191a4115fbf2cfc1508a2d1709d968488fcf49 | 110 | class Capybara::Node::Base
def find_custom(finder, locator)
base.find_custom(finder, locator)
end
end
| 18.333333 | 37 | 0.745455 |
ff75e87d3d9e46e646a5e9642024d42219dca9eb | 4,171 | require 'delayed/server'
Rails.application.routes.draw do
# api
# service
# rails/active_storage
# assets
root 'application#index'
get 'oauth/admin', to: 'oauth#admin_token' if Rails.env.development?
scope '/rails' do
devise_for :users
mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
mount Delayed::Server.new => '/jobs'
# mount Logster::Web => "/logs", constraints: Constraints::CanCan.new(:manage, :logs)
#
get 'twitch/authorize', to: 'twitch_oauth#authorize'
get 'twitch/callback', to: 'twitch_oauth#callback', as: 'twitch_oauth_callback'
end
namespace :api do
namespace :v1 do
resources :seasons
resources :teams do
member do
get 'details'
end
end
get 'teams/details/:id', to: 'teams#details'
resources :users do
collection do
get 'search'
end
end
resources :events do
collection do
get 'approve_access/:token', action: 'approve_access', as: 'approve_access'
end
member do
# Basic views
get 'matches', action: 'view_matches'
get 'rankings', action: 'view_rankings'
get 'awards', action: 'view_awards'
get 'alliances', action: 'view_alliances'
get 'teams', action: 'view_teams'
get 'download_scoring_system_url'
get 'download_scoring_system', as: 'download_scoring_system'
post 'import_results'
post 'reset'
post 'state', action: 'post_state'
post 'rankings', action: 'post_rankings'
post 'awards', action: 'post_awards'
post 'teams', action: 'post_teams'
post 'alliances', action: 'post_alliances'
post 'matches', action: 'post_matches'
post 'matches/:mid', action: 'post_match'
post 'twitch'
delete 'twitch', action: 'remove_twitch'
post 'add_owner'
post 'remove_owner'
post 'request_access'
end
end
get 'events/matches/:id', to: 'events#view_matches'
get 'events/rankings/:id', to: 'events#view_rankings'
get 'events/awards/:id', to: 'events#view_awards'
get 'events/teams/:id', to: 'events#view_teams'
get 'events/download_scoring_system_url/:id', to: 'events#download_scoring_system_url'
get 'events/download_scoring_system/:id', to: 'events#download_scoring_system'
resources :leagues do
member do
get 'details'
end
end
get 'leagues/details/:id', to: 'leagues#details'
resources :divisions
post 'events/import_results/:id', to: 'events#import_results'
get 'rankings/league', to: 'league_rankings#index'
get 'rankings/league/:id', to: 'league_rankings#league_data'
get 'rankings/division/:id', to: 'league_rankings#division_data'
get 'matches/details/:id', to: 'matches#details'
get 'matches/:id/details', to: 'matches#details'
mount_devise_token_auth_for 'User', at: 'auth', controllers: {
confirmations: 'auth/confirmations'
}, skip: [:invitations]
devise_for :users, path: 'auth', only: [:invitations],
controllers: { invitations: 'auth/invitations' }
# Upload routes
post 'events/reset/:id', to: 'events#reset'
post 'events/state/:id', to: 'events#post_state'
post 'events/rankings/:id', to: 'events#post_rankings'
post 'events/awards/:id', to: 'events#post_awards'
post 'events/teams/:id', to: 'events#post_teams'
post 'events/alliances/:id', to: 'events#post_alliances'
post 'events/matches/:id', to: 'events#post_matches'
post 'events/matches/:id/:mid', to: 'events#post_match'
post 'events/twitch/:id', to: 'events#twitch'
delete 'events/twitch/:id', to: 'events#remove_twitch'
post 'events/add_owner/:id', to: 'events#add_owner'
post 'events/remove_owner/:id', to: 'events#remove_owner'
post 'events/requestAccess/:id', to: 'events#request_access'
get 'events/approveAccess/:token', to: 'events#approve_access'
end
end
health_check_routes
end
| 33.637097 | 92 | 0.626708 |
7957db8fd790974de325110e88d563aa690e7604 | 809 | # frozen_string_literal: true
xml.instruct! :xml, version: '1.0'
xml.OpenSearchDescription(xmlns: 'http://a9.com/-/spec/opensearch/1.1/') {
xml.ShortName application_name
xml.Description "#{application_name} Search"
xml.Image "#{asset_url('favicon.ico')}", height: 16, width: 16, type: 'image/x-icon'
xml.Contact
xml.Url type: 'text/html', method: 'get', template: "#{url_for controller: 'catalog', only_path: false}?q={searchTerms}&page={startPage?}"
xml.Url type: 'application/rss+xml', method: 'get', template: "#{url_for controller: 'catalog', only_path: false}.rss?q={searchTerms}&page={startPage?}"
xml.Url type: 'application/x-suggestions+json', method: 'get', template: "#{url_for controller: 'catalog',action: 'opensearch', format: 'json', only_path: false}?q={searchTerms}"
}
| 62.230769 | 180 | 0.71199 |
280584041fd64763ab503840bbcd43af72f002f5 | 6,228 | =begin
#OpenAPI Petstore
#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.0.0-beta3
=end
require 'date'
require 'time'
module Petstore
class DogAllOf
attr_accessor :breed
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'breed' => :'breed'
}
end
# Attribute type mapping.
def self.openapi_types
{
:'breed' => :'String'
}
end
# List of attributes with nullable: true
def self.openapi_nullable
Set.new([
])
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::DogAllOf` initialize method"
end
# check to see if the attribute exists and convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h|
if (!self.class.attribute_map.key?(k.to_sym))
fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::DogAllOf`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
end
h[k.to_sym] = v
}
if attributes.key?(:'breed')
self.breed = attributes[:'breed']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
breed == o.breed
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
def hash
[breed].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def self.build_from_hash(attributes)
new.build_from_hash(attributes)
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.openapi_types.each_pair do |key, type|
if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key)
self.send("#{key}=", nil)
elsif type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :Time
Time.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :Boolean
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
Petstore.const_get(type).build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
if value.nil?
is_nullable = self.class.openapi_nullable.include?(attr)
next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
end
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 29.516588 | 196 | 0.620745 |
6ac2dfd88a6242dc302b8923ef01227051029061 | 1,720 | # Windows console color support
# Copyright 2011 Michael 'mihi' Schierl
# Licensed under MSF license
class WindowsConsoleColorSupport
STD_OUTPUT_HANDLE = -11
COLORS = [0, 4, 2, 6, 1, 5, 3, 7]
def initialize(origstream)
@origstream = origstream
# initialize API
@GetStdHandle = Win32API.new("kernel32","GetStdHandle",['L'],'L')
@GetConsoleScreenBufferInfo = Win32API.new("kernel32","GetConsoleScreenBufferInfo",['L','P'],'L')
@SetConsoleTextAttribute = Win32API.new("kernel32","SetConsoleTextAttribute",['L','l'],'L')
@hConsoleHandle = @GetStdHandle.Call(STD_OUTPUT_HANDLE)
end
def write(msg)
rest = msg
while (rest =~ Regexp.new("([^\e]*)\e\\[([0-9;]+)m"))
@origstream.write($1)
rest = $' # save it now since setcolor may clobber it
$2.split(";").each do |color|
setcolor(color.to_i)
end
end
@origstream.write(rest)
end
def flush
@origstream.flush
end
def setcolor(color)
csbi = 0.chr * 24
@GetConsoleScreenBufferInfo.Call(@hConsoleHandle,csbi)
wAttr = csbi[8,2].unpack('v').first
case color
when 0 # reset
wAttr = 0x07
when 1 # bold
wAttr |= 0x08
when 2 # unbold
wAttr &= ~0x08
when 7 # reverse
wAttr = ((wAttr & 0x0f) << 4) | ((wAttr & 0xf0) >> 4)
when 8 # conceal
wAttr &= ~0x0f
when 30 .. 37 # foreground colors
wAttr = (wAttr & ~0x07) | COLORS[color - 30]
when 40 .. 47 # background colors
wAttr = (wAttr & ~0x70) | (COLORS[color - 40] << 4)
end
@SetConsoleTextAttribute.Call(@hConsoleHandle, wAttr)
end
end
| 28.196721 | 102 | 0.580814 |
62986af4cd65f74a9f4ba92e4ae72d82b6da472a | 18,624 | require 'spec_helper'
describe TranslationIO::FlatHash do
describe '#to_flat_hash' do
it 'returns a flat hash' do
hash = {
'en' => {
'hello' => 'Hello world',
'main' => {
'menu' => {
'stuff' => 'This is stuff'
}
},
'bye' => 'Good bye world',
'bidules' => [
'bidule 1',
'bidule 2'
],
'buzzwords' => [
['Adaptive', 'Advanced' ],
['24 hour', '4th generation']
],
'age' => 42,
:address => 'Cour du Curé',
'names' => [
{ 'first' => 'Aurélien', 'last' => 'Malisart' },
{ 'first' => 'Michaël', 'last' => 'Hoste' }
]
}
}
flat_hash = subject.to_flat_hash(hash)
flat_hash.should == {
'en.hello' => 'Hello world' ,
'en.main.menu.stuff' => 'This is stuff' ,
'en.bye' => 'Good bye world',
'en.bidules[0]' => 'bidule 1',
'en.bidules[1]' => 'bidule 2',
'en.buzzwords[0][0]' => 'Adaptive',
'en.buzzwords[0][1]' => 'Advanced',
'en.buzzwords[1][0]' => '24 hour',
'en.buzzwords[1][1]' => '4th generation',
'en.age' => 42,
'en.address' => 'Cour du Curé',
'en.names[0].first' => 'Aurélien',
'en.names[0].last' => 'Malisart',
'en.names[1].first' => 'Michaël',
'en.names[1].last' => 'Hoste'
}
end
it 'returns a flat hash with nil values' do
hash = {
"en" => {
"date" => {
"formats" => {
"default" => "%Y-%m-%d",
"long" => "%B %d, %Y",
"short" =>"%b %d"
},
"abbr_day_names" => [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ],
"abbr_month_names" => [ nil, "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ],
"day_names" => [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]
},
"number" => {
"format" => {
"strip_insignificant_zeros" => false
}
}
}
}
flat_hash = subject.to_flat_hash(hash)
flat_hash.should == {
"en.date.formats.default" => "%Y-%m-%d",
"en.date.formats.long" => "%B %d, %Y",
"en.date.formats.short" => "%b %d",
"en.date.abbr_day_names[0]" => "Sun",
"en.date.abbr_day_names[1]" => "Mon",
"en.date.abbr_day_names[2]" => "Tue",
"en.date.abbr_day_names[3]" => "Wed",
"en.date.abbr_day_names[4]" => "Thu",
"en.date.abbr_day_names[5]" => "Fri",
"en.date.abbr_day_names[6]" => "Sat",
"en.date.abbr_month_names[0]" => nil,
"en.date.abbr_month_names[1]" => "Jan",
"en.date.abbr_month_names[2]" => "Feb",
"en.date.abbr_month_names[3]" => "Mar",
"en.date.abbr_month_names[4]" => "Apr",
"en.date.abbr_month_names[5]" => "May",
"en.date.abbr_month_names[6]" => "Jun",
"en.date.abbr_month_names[7]" => "Jul",
"en.date.abbr_month_names[8]" => "Aug",
"en.date.abbr_month_names[9]" => "Sep",
"en.date.abbr_month_names[10]" => "Oct",
"en.date.abbr_month_names[11]" => "Nov",
"en.date.abbr_month_names[12]" => "Dec",
"en.date.day_names[0]" => "Sunday",
"en.date.day_names[1]" => "Monday",
"en.date.day_names[2]" => "Tuesday",
"en.date.day_names[3]" => "Wednesday",
"en.date.day_names[4]" => "Thursday",
"en.date.day_names[5]" => "Friday",
"en.date.day_names[6]" => "Saturday",
"en.number.format.strip_insignificant_zeros" => false
}
subject.to_hash(flat_hash).should == hash
end
it 'returns another flat hash with nil values at root' do
hash = {
"ja" => nil
}
flat_hash = subject.to_flat_hash(hash)
flat_hash.should == {
"ja" => nil
}
subject.to_hash(flat_hash).should == hash
end
it 'returns another flat hash with nil values at sublevel' do
hash = {
"nl" => {
"hello" => nil
}
}
flat_hash = subject.to_flat_hash(hash)
flat_hash.should == {
"nl.hello" => nil
}
subject.to_hash(flat_hash).should == hash
end
it 'returns another flat hash with nil values in arrays' do
hash = {
"nl" => {
"date" => {
"abbr_day_names" => [ "zon", "maa", "din", "woe", "don", "vri", "zat" ],
"abbr_month_names" => [ nil, "jan", "feb", "mar", "apr", "mei", "jun", "jul", "aug", "sep", "okt", "nov", "dec" ],
"day_names" => [ "zondag", "maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag" ],
"formats" => {
"default" => "%d/%m/%Y",
"long" => "%e %B %Y",
"short" => "%e %b"
}
}
}
}
flat_hash = subject.to_flat_hash(hash)
flat_hash.should == {
"nl.date.abbr_day_names[0]" => "zon",
"nl.date.abbr_day_names[1]" => "maa",
"nl.date.abbr_day_names[2]" => "din",
"nl.date.abbr_day_names[3]" => "woe",
"nl.date.abbr_day_names[4]" => "don",
"nl.date.abbr_day_names[5]" => "vri",
"nl.date.abbr_day_names[6]" => "zat",
"nl.date.abbr_month_names[0]" => nil,
"nl.date.abbr_month_names[1]" => "jan",
"nl.date.abbr_month_names[2]" => "feb",
"nl.date.abbr_month_names[3]" => "mar",
"nl.date.abbr_month_names[4]" => "apr",
"nl.date.abbr_month_names[5]" => "mei",
"nl.date.abbr_month_names[6]" => "jun",
"nl.date.abbr_month_names[7]" => "jul",
"nl.date.abbr_month_names[8]" => "aug",
"nl.date.abbr_month_names[9]" => "sep",
"nl.date.abbr_month_names[10]" => "okt",
"nl.date.abbr_month_names[11]" => "nov",
"nl.date.abbr_month_names[12]" => "dec",
"nl.date.day_names[0]" => "zondag",
"nl.date.day_names[1]" => "maandag",
"nl.date.day_names[2]" => "dinsdag",
"nl.date.day_names[3]" => "woensdag",
"nl.date.day_names[4]" => "donderdag",
"nl.date.day_names[5]" => "vrijdag",
"nl.date.day_names[6]" => "zaterdag",
"nl.date.formats.default" => "%d/%m/%Y",
"nl.date.formats.long" => "%e %B %Y",
"nl.date.formats.short" => "%e %b"
}
subject.to_hash(flat_hash).should == hash
end
it 'return hash with jokers instead of square brackets' do
hash = {
'helpers' => {
'label' => {
'startup[attachments_attributes][new_attachments]' => {
'permissions' => 'Permissions'
},
'startup[startup_financing_information_attributes]' => {
'_transaction' => 'Transaction'
}
}
}
}
flat_hash = subject.to_flat_hash(hash)
flat_hash.should == {
'helpers.label.startup<@~<attachments_attributes>@~><@~<new_attachments>@~>.permissions' => 'Permissions',
'helpers.label.startup<@~<startup_financing_information_attributes>@~>._transaction' => 'Transaction'
}
subject.to_hash(flat_hash).should == {
'helpers' => {
'label' => {
'startup[attachments_attributes][new_attachments]' => {
'permissions' => 'Permissions'
},
'startup[startup_financing_information_attributes]' => {
'_transaction' => 'Transaction'
}
}
}
}
end
end
describe '#to_hash' do
it 'returns a simple hash' do
flat_hash = {
'en' => 'hello'
}
hash = subject.to_hash(flat_hash)
hash.should == { 'en' => 'hello' }
end
it 'returns a simple array' do
flat_hash = {
'en[0]' => 'hello'
}
hash = subject.to_hash(flat_hash)
hash.should == { 'en' => ['hello'] }
end
it 'returns a simple array with 2 elements' do
flat_hash = {
'en[0]' => 'hello',
'en[1]' => 'world'
}
hash = subject.to_hash(flat_hash)
hash.should == { 'en' => ['hello', 'world'] }
end
it 'returns a double array' do
flat_hash = {
'en[0][0]' => 'hello',
'en[0][1]' => 'world'
}
hash = subject.to_hash(flat_hash)
hash.should == { 'en' => [['hello', 'world']] }
end
it 'returns a double array with hash in it' do
flat_hash = {
'en[0][0].hello' => 'hello world',
'en[0][1].goodbye' => 'goodbye world',
'en[1][0].hello2' => 'hello lord',
'en[1][1].goodbye2' => 'goodbye lord'
}
hash = subject.to_hash(flat_hash)
hash.should == {
'en' => [
[
{ 'hello' => 'hello world' },
{ 'goodbye' => 'goodbye world' }
],
[
{ 'hello2' => 'hello lord' },
{ 'goodbye2' => 'goodbye lord' }
]
]
}
end
it 'return a hash with arrays at many places' do
flat_hash = {
'fr[0][0].bouh.salut[0]' => 'blabla',
'fr[0][0].bouh.salut[1]' => 'blibli',
'fr[1][0].salut' => 'hahah',
'fr[1][1].ha' => 'house'
}
hash = subject.to_hash(flat_hash)
hash.should == {
'fr' => [
[{
'bouh' => {
'salut' => [ 'blabla', 'blibli' ]
}
}],
[
{ 'salut' => 'hahah' },
{ 'ha' => 'house'}
]
]
}
end
it 'returns a hash' do
flat_hash = {
'en.hello' => 'Hello world' ,
'en.main.menu[0].stuff' => 'This is stuff' ,
'en.bye' => 'Good bye world',
'en.bidules[0]' => 'bidule 1',
'en.bidules[1]' => 'bidule 2',
'en.family[0][0]' => 'Ta mère',
'en.family[0][1]' => 'Ta soeur',
'en.family[1][0]' => 'Ton père',
'en.family[1][1]' => 'Ton frère'
}
hash = subject.to_hash(flat_hash)
hash.should == {
'en' => {
'hello' => 'Hello world',
'main' => {
'menu' => [
'stuff' => 'This is stuff'
]
},
'bye' => 'Good bye world',
'bidules' => [
'bidule 1',
'bidule 2'
],
'family' => [
['Ta mère', 'Ta soeur'],
['Ton père', 'Ton frère'],
]
}
}
end
end
it 'returns a hash with missing array values' do
flat_hash = {
"nl.date.abbr_month_names[1]" => "jan",
"nl.date.abbr_month_names[2]" => "feb",
"nl.date.abbr_month_names[3]" => "mar"
}
hash = subject.to_hash(flat_hash)
hash.should == {
'nl' => {
'date' => {
'abbr_month_names' => [nil, 'jan', 'feb', 'mar']
}
}
}
end
it 'returns a hash when inconsistencies in YAML (can be caused by YamlLocalizationFillService)' do
flat_hash = {
"en.date.order" => "%d.%m.%Y",
"en.date.order[0]" => :year,
"en.date.order[1]" => :month,
"en.date.order[2]" => :day,
}
hash = subject.to_hash(flat_hash)
hash.should == {
'en' => {
'date' => {
'order' => "%d.%m.%Y"
}
}
}
end
it 'returns a hash when inconsistencies in YAML (can be caused by YamlLocalizationFillService) - 2' do
flat_hash = {
"en.date.order[0]" => :year,
"en.date.order[1]" => :month,
"en.date.order[2]" => :day,
"en.date.order" => "%d.%m.%Y",
}
hash = subject.to_hash(flat_hash)
hash.should == {
'en' => {
'date' => {
'order' => "%d.%m.%Y"
}
}
}
end
it 'handles empty/nil keys' do
flat_hash = {
"" => "jan"
}
hash = subject.to_hash(flat_hash)
hash.should == {
nil => "jan"
}
end
it 'handles nil values' do
flat_hash = {
"key" => nil
}
hash = subject.to_hash(flat_hash)
hash.should == {
"key" => nil
}
end
it 'handles nil values with sublevel' do
flat_hash = {
"key.test" => nil
}
hash = subject.to_hash(flat_hash)
hash.should == {
"key" => {
"test" => nil
}
}
end
it 'handles joker square brackets in hash keys' do
flat_hash = {
'helpers.label.startup<@~<attachments_attributes>@~><@~<new_attachments>@~>.permissions' => 'Permissions',
'helpers.label.startup<@~<startup_financing_information_attributes>@~>._transaction' => 'Transaction'
}
hash = subject.to_hash(flat_hash)
hash.should == {
'helpers' => {
'label' => {
'startup[attachments_attributes][new_attachments]' => {
'permissions' => 'Permissions'
},
'startup[startup_financing_information_attributes]' => {
'_transaction' => 'Transaction'
}
}
}
}
end
it 'handles joker square brackets and normal brackets (arrays) in hash keys' do
flat_hash = {
'helpers[0].startup<@~<first_key>@~>[0]' => 'blabla1',
'helpers[0].startup<@~<first_key>@~>[1]' => 'blabla2',
'helpers[1].startup<@~<second_key>@~>[0]' => 'blibli1',
'helpers[1].startup<@~<second_key>@~>[1]' => 'blibli2',
'helpers[2].startup<@~<third_key>@~>.key' => 'bloblo',
}
hash = subject.to_hash(flat_hash)
hash.should == {
'helpers' => [
{ 'startup[first_key]' => [ 'blabla1', 'blabla2' ] },
{ 'startup[second_key]' => [ 'blibli1', 'blibli2' ] },
{ 'startup[third_key]' => {
'key' => 'bloblo'
}}
]
}
subject.to_flat_hash(hash).should == flat_hash
end
it 'handles inconsistant values in hashs' do
flat_hash = {
"errors.messages.too_long" => "est trop long (pas plus de %{count} caractères)",
"errors.messages.too_long.one" => "est trop long (pas plus d'un caractère)",
"errors.messages.too_long.other" => "est trop long (pas plus de %{count} caractères)"
}
hash = subject.to_hash(flat_hash)
hash.should == {
"errors" => {
"messages" => {
"too_long" => "est trop long (pas plus de %{count} caractères)"
}
}
}
end
it 'handles inconsistant values in hashs - 2' do
flat_hash = {
"menus[0].a" => "Menu A",
"menus.b" => "Menu B",
"menus.c" => "Menu C",
"menus[0].b" => "Menu B2",
"menus[1]" => "Menu D"
}
hash = subject.to_hash(flat_hash)
hash.should == {
"menus" => [{
"a" => "Menu A",
"b" => "Menu B2",
},
"Menu D"
]
}
end
it 'handles inconsistant values in hashs - 3' do
flat_hash = {
"menus.a" => "Menu A",
"menus.a.test" => "test"
}
hash = subject.to_hash(flat_hash)
hash.should == {
"menus" => {
"a" => "Menu A",
}
}
end
it 'handles inconsistant values in hashs - 4' do
flat_hash = {
"title.edit" => "Modifier",
"title.new" => "Nouveau",
"title" => ""
}
hash = subject.to_hash(flat_hash)
hash.should == {
"title" => "",
}
end
it 'handles inconsistant values in hashs - 5' do
flat_hash = {
"services.renting.description" => 'Renting is great!',
"services.renting.description.price.header" => 'What is the price?',
}
hash = subject.to_hash(flat_hash)
hash.should == {
'services' => {
'renting' => {
'description' => "Renting is great!"
}
}
}
end
it "handles inconsistant values in hash - 6" do
flat_hash = {
"services.renting.description" => 'Renting is great!',
"services.renting.description.price.header.test" => 'What is the price?',
}
hash = subject.to_hash(flat_hash)
hash.should == {
'services' => {
'renting' => {
'description' => "Renting is great!"
}
}
}
end
it "handles inconsistant values in hash - 7" do
flat_hash = {
"services.renting.description.price.header.test" => 'What is the price?',
"services.renting.description" => 'Renting is great!',
}
hash = subject.to_hash(flat_hash)
hash.should == {
'services' => {
'renting' => {
'description' => "Renting is great!"
}
}
}
end
it "can remove empty keys if specified" do
flat_hash = {
"services.blih" => nil,
"services.renting" => 'Renting is great!',
"services.blah" => '',
"services.array[0]" => 'first_item',
"services.array[1]" => '',
"services.array[2]" => nil,
"services.array[3]" => 'something',
"services.array[4].hello" => 'bonjour',
"services.array[4].bye" => nil
}
hash = subject.to_hash(flat_hash, true)
hash.should == {
'services' => {
'renting' => "Renting is great!",
'array' => [
'first_item',
'',
nil,
'something',
{ 'hello' => 'bonjour' }
]
}
}
# Same but without empty key removal!
hash = subject.to_hash(flat_hash, false)
hash.should == {
'services' => {
'blih' => nil,
'renting' => "Renting is great!",
'blah' => '',
'array' => [
'first_item',
'',
nil,
'something',
{ 'hello' => 'bonjour', 'bye' => nil }
]
}
}
end
end
| 27.388235 | 126 | 0.452695 |
e83cf5f4e8e81bdc20e175e19679fd91168c3c1f | 389 | Given /^I am logged in$/ do
@current_user = FactoryBot.create(:user)
login_as @current_user
end
Given /^a user named "(.*?)"$/ do |name|
FactoryBot.create(:user, name: name)
end
Given /^I am logged in as "(.*?)"$/ do |name|
login_as User.find_by(name: name)
end
Given /^I am logged in as approver$/ do
@current_user = FactoryBot.create(:approver)
login_as @current_user
end
| 21.611111 | 46 | 0.683805 |
18a6609b271f13c751d7e3b7c4b52fafa41c2308 | 573 | require "/home/pi/.gem/ruby/2.5.1/gems/redis-4.0.2/lib/redis"
def blink
[1,0,1,0,1,0,1,0,1,0].each do |n|
`echo #{n} | tee /sys/class/leds/led0/brightness`
sleep 0.5
end
end
Redis.new.subscribe("system") do |on|
on.subscribe do |channel, subscriptions|
puts "Subscribed to #{channel}"
end
on.message do |channel, message|
puts "Message received on #{channel}: #{message}"
if message == "start_laserbonnet"
blink
exit
end
end
on.unsubscribe do |channel, subscriptions|
puts "Unsubscribed from #{channel}"
end
end
| 20.464286 | 61 | 0.645724 |
bbb191a09b1fd2b2f78a7ac432c3b2bdc2c8564b | 62,322 | # Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'
module Google
module Apis
module AndroiddeviceprovisioningV1
# Android Device Provisioning Partner API
#
# Automates Android zero-touch enrollment for device resellers, customers, and
# EMMs.
#
# @example
# require 'google/apis/androiddeviceprovisioning_v1'
#
# Androiddeviceprovisioning = Google::Apis::AndroiddeviceprovisioningV1 # Alias the module
# service = Androiddeviceprovisioning::AndroidProvisioningPartnerService.new
#
# @see https://developers.google.com/zero-touch/
class AndroidProvisioningPartnerService < Google::Apis::Core::BaseService
# @return [String]
# API key. Your API key identifies your project and provides you with API access,
# quota, and reports. Required unless you provide an OAuth 2.0 token.
attr_accessor :key
# @return [String]
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
attr_accessor :quota_user
def initialize
super('https://androiddeviceprovisioning.googleapis.com/', '')
@batch_path = 'batch'
end
# Lists the user's customer accounts.
# @param [Fixnum] page_size
# The maximum number of customers to show in a page of results.
# A number between 1 and 100 (inclusive).
# @param [String] page_token
# A token specifying which result page to return.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::CustomerListCustomersResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::CustomerListCustomersResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_customers(page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/customers', options)
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::CustomerListCustomersResponse::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::CustomerListCustomersResponse
command.query['pageSize'] = page_size unless page_size.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Creates a new configuration. Once created, a customer can apply the
# configuration to devices.
# @param [String] parent
# Required. The customer that manages the configuration. An API resource name
# in the format `customers/[CUSTOMER_ID]`.
# @param [Google::Apis::AndroiddeviceprovisioningV1::Configuration] configuration_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::Configuration] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::Configuration]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def create_customer_configuration(parent, configuration_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/{+parent}/configurations', options)
command.request_representation = Google::Apis::AndroiddeviceprovisioningV1::Configuration::Representation
command.request_object = configuration_object
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::Configuration::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::Configuration
command.params['parent'] = parent unless parent.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Deletes an unused configuration. The API call fails if the customer has
# devices with the configuration applied.
# @param [String] name
# Required. The configuration to delete. An API resource name in the format
# `customers/[CUSTOMER_ID]/configurations/[CONFIGURATION_ID]`. If the
# configuration is applied to any devices, the API call fails.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::Empty] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::Empty]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def delete_customer_configuration(name, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:delete, 'v1/{+name}', options)
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::Empty::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::Empty
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Gets the details of a configuration.
# @param [String] name
# Required. The configuration to get. An API resource name in the format
# `customers/[CUSTOMER_ID]/configurations/[CONFIGURATION_ID]`.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::Configuration] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::Configuration]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_customer_configuration(name, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/{+name}', options)
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::Configuration::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::Configuration
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists a customer's configurations.
# @param [String] parent
# Required. The customer that manages the listed configurations. An API
# resource name in the format `customers/[CUSTOMER_ID]`.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::CustomerListConfigurationsResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::CustomerListConfigurationsResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_customer_configurations(parent, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/{+parent}/configurations', options)
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::CustomerListConfigurationsResponse::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::CustomerListConfigurationsResponse
command.params['parent'] = parent unless parent.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Updates a configuration's field values.
# @param [String] name
# Output only. The API resource name in the format
# `customers/[CUSTOMER_ID]/configurations/[CONFIGURATION_ID]`. Assigned by
# the server.
# @param [Google::Apis::AndroiddeviceprovisioningV1::Configuration] configuration_object
# @param [String] update_mask
# Required. The field mask applied to the target `Configuration` before
# updating the fields. To learn more about using field masks, read
# [FieldMask](/protocol-buffers/docs/reference/google.protobuf#fieldmask) in
# the Protocol Buffers documentation.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::Configuration] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::Configuration]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def patch_customer_configuration(name, configuration_object = nil, update_mask: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:patch, 'v1/{+name}', options)
command.request_representation = Google::Apis::AndroiddeviceprovisioningV1::Configuration::Representation
command.request_object = configuration_object
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::Configuration::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::Configuration
command.params['name'] = name unless name.nil?
command.query['updateMask'] = update_mask unless update_mask.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Applies a Configuration to the device to register the device for zero-touch
# enrollment. After applying a configuration to a device, the device
# automatically provisions itself on first boot, or next factory reset.
# @param [String] parent
# Required. The customer managing the device. An API resource name in the
# format `customers/[CUSTOMER_ID]`.
# @param [Google::Apis::AndroiddeviceprovisioningV1::CustomerApplyConfigurationRequest] customer_apply_configuration_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::Empty] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::Empty]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def apply_customer_device_configuration(parent, customer_apply_configuration_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/{+parent}/devices:applyConfiguration', options)
command.request_representation = Google::Apis::AndroiddeviceprovisioningV1::CustomerApplyConfigurationRequest::Representation
command.request_object = customer_apply_configuration_request_object
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::Empty::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::Empty
command.params['parent'] = parent unless parent.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Gets the details of a device.
# @param [String] name
# Required. The device to get. An API resource name in the format
# `customers/[CUSTOMER_ID]/devices/[DEVICE_ID]`.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::Device] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::Device]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_customer_device(name, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/{+name}', options)
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::Device::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::Device
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists a customer's devices.
# @param [String] parent
# Required. The customer managing the devices. An API resource name in the
# format `customers/[CUSTOMER_ID]`.
# @param [Fixnum] page_size
# The maximum number of devices to show in a page of results.
# Must be between 1 and 100 inclusive.
# @param [String] page_token
# A token specifying which result page to return.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::CustomerListDevicesResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::CustomerListDevicesResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_customer_devices(parent, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/{+parent}/devices', options)
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::CustomerListDevicesResponse::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::CustomerListDevicesResponse
command.params['parent'] = parent unless parent.nil?
command.query['pageSize'] = page_size unless page_size.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Removes a configuration from device.
# @param [String] parent
# Required. The customer managing the device in the format
# `customers/[CUSTOMER_ID]`.
# @param [Google::Apis::AndroiddeviceprovisioningV1::CustomerRemoveConfigurationRequest] customer_remove_configuration_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::Empty] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::Empty]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def remove_customer_device_configuration(parent, customer_remove_configuration_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/{+parent}/devices:removeConfiguration', options)
command.request_representation = Google::Apis::AndroiddeviceprovisioningV1::CustomerRemoveConfigurationRequest::Representation
command.request_object = customer_remove_configuration_request_object
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::Empty::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::Empty
command.params['parent'] = parent unless parent.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Unclaims a device from a customer and removes it from zero-touch
# enrollment.
# After removing a device, a customer must contact their reseller to register
# the device into zero-touch enrollment again.
# @param [String] parent
# Required. The customer managing the device. An API resource name in the
# format `customers/[CUSTOMER_ID]`.
# @param [Google::Apis::AndroiddeviceprovisioningV1::CustomerUnclaimDeviceRequest] customer_unclaim_device_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::Empty] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::Empty]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def unclaim_customer_device(parent, customer_unclaim_device_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/{+parent}/devices:unclaim', options)
command.request_representation = Google::Apis::AndroiddeviceprovisioningV1::CustomerUnclaimDeviceRequest::Representation
command.request_object = customer_unclaim_device_request_object
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::Empty::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::Empty
command.params['parent'] = parent unless parent.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists the DPCs (device policy controllers) that support zero-touch
# enrollment.
# @param [String] parent
# Required. The customer that can use the DPCs in configurations. An API
# resource name in the format `customers/[CUSTOMER_ID]`.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::CustomerListDpcsResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::CustomerListDpcsResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_customer_dpcs(parent, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/{+parent}/dpcs', options)
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::CustomerListDpcsResponse::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::CustomerListDpcsResponse
command.params['parent'] = parent unless parent.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Gets the latest state of a long-running operation. Clients can use this
# method to poll the operation result at intervals as recommended by the API
# service.
# @param [String] name
# The name of the operation resource.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_operation(name, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/{+name}', options)
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::Operation::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::Operation
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Creates a customer for zero-touch enrollment. After the method returns
# successfully, admin and owner roles can manage devices and EMM configs
# by calling API methods or using their zero-touch enrollment portal.
# The customer receives an email that welcomes them to zero-touch enrollment
# and explains how to sign into the portal.
# @param [String] parent
# Required. The parent resource ID in the format `partners/[PARTNER_ID]` that
# identifies the reseller.
# @param [Google::Apis::AndroiddeviceprovisioningV1::CreateCustomerRequest] create_customer_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::Company] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::Company]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def create_customer(parent, create_customer_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/{+parent}/customers', options)
command.request_representation = Google::Apis::AndroiddeviceprovisioningV1::CreateCustomerRequest::Representation
command.request_object = create_customer_request_object
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::Company::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::Company
command.params['parent'] = parent unless parent.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists the customers that are enrolled to the reseller identified by the
# `partnerId` argument. This list includes customers that the reseller
# created and customers that enrolled themselves using the portal.
# @param [Fixnum] partner_id
# Required. The ID of the reseller partner.
# @param [Fixnum] page_size
# The maximum number of results to be returned. If not specified or 0, all
# the records are returned.
# @param [String] page_token
# A token identifying a page of results returned by the server.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::ListCustomersResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::ListCustomersResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_partner_customers(partner_id, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/partners/{+partnerId}/customers', options)
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::ListCustomersResponse::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::ListCustomersResponse
command.params['partnerId'] = partner_id unless partner_id.nil?
command.query['pageSize'] = page_size unless page_size.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Claims a device for a customer and adds it to zero-touch enrollment. If the
# device is already claimed by another customer, the call returns an error.
# @param [Fixnum] partner_id
# Required. The ID of the reseller partner.
# @param [Google::Apis::AndroiddeviceprovisioningV1::ClaimDeviceRequest] claim_device_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::ClaimDeviceResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::ClaimDeviceResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def claim_device(partner_id, claim_device_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/partners/{+partnerId}/devices:claim', options)
command.request_representation = Google::Apis::AndroiddeviceprovisioningV1::ClaimDeviceRequest::Representation
command.request_object = claim_device_request_object
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::ClaimDeviceResponse::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::ClaimDeviceResponse
command.params['partnerId'] = partner_id unless partner_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Claims a batch of devices for a customer asynchronously. Adds the devices
# to zero-touch enrollment. To learn more, read [Long‑running batch
# operations](/zero-touch/guides/how-it-works#operations).
# @param [Fixnum] partner_id
# Required. The ID of the reseller partner.
# @param [Google::Apis::AndroiddeviceprovisioningV1::ClaimDevicesRequest] claim_devices_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def claim_partner_device_async(partner_id, claim_devices_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/partners/{+partnerId}/devices:claimAsync', options)
command.request_representation = Google::Apis::AndroiddeviceprovisioningV1::ClaimDevicesRequest::Representation
command.request_object = claim_devices_request_object
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::Operation::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::Operation
command.params['partnerId'] = partner_id unless partner_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Finds devices by hardware identifiers, such as IMEI.
# @param [Fixnum] partner_id
# Required. The ID of the reseller partner.
# @param [Google::Apis::AndroiddeviceprovisioningV1::FindDevicesByDeviceIdentifierRequest] find_devices_by_device_identifier_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::FindDevicesByDeviceIdentifierResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::FindDevicesByDeviceIdentifierResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def find_partner_device_by_identifier(partner_id, find_devices_by_device_identifier_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/partners/{+partnerId}/devices:findByIdentifier', options)
command.request_representation = Google::Apis::AndroiddeviceprovisioningV1::FindDevicesByDeviceIdentifierRequest::Representation
command.request_object = find_devices_by_device_identifier_request_object
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::FindDevicesByDeviceIdentifierResponse::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::FindDevicesByDeviceIdentifierResponse
command.params['partnerId'] = partner_id unless partner_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Finds devices claimed for customers. The results only contain devices
# registered to the reseller that's identified by the `partnerId` argument.
# The customer's devices purchased from other resellers don't appear in the
# results.
# @param [Fixnum] partner_id
# Required. The ID of the reseller partner.
# @param [Google::Apis::AndroiddeviceprovisioningV1::FindDevicesByOwnerRequest] find_devices_by_owner_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::FindDevicesByOwnerResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::FindDevicesByOwnerResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def find_partner_device_by_owner(partner_id, find_devices_by_owner_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/partners/{+partnerId}/devices:findByOwner', options)
command.request_representation = Google::Apis::AndroiddeviceprovisioningV1::FindDevicesByOwnerRequest::Representation
command.request_object = find_devices_by_owner_request_object
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::FindDevicesByOwnerResponse::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::FindDevicesByOwnerResponse
command.params['partnerId'] = partner_id unless partner_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Gets a device.
# @param [String] name
# Required. The device API resource name in the format
# `partners/[PARTNER_ID]/devices/[DEVICE_ID]`.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::Device] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::Device]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_partner_device(name, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/{+name}', options)
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::Device::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::Device
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Updates reseller metadata associated with the device.
# @param [Fixnum] metadata_owner_id
# Required. The owner of the newly set metadata. Set this to the partner ID.
# @param [Fixnum] device_id
# Required. The ID of the device.
# @param [Google::Apis::AndroiddeviceprovisioningV1::UpdateDeviceMetadataRequest] update_device_metadata_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::DeviceMetadata] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::DeviceMetadata]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def metadata_partner_device(metadata_owner_id, device_id, update_device_metadata_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/partners/{+metadataOwnerId}/devices/{+deviceId}/metadata', options)
command.request_representation = Google::Apis::AndroiddeviceprovisioningV1::UpdateDeviceMetadataRequest::Representation
command.request_object = update_device_metadata_request_object
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::DeviceMetadata::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::DeviceMetadata
command.params['metadataOwnerId'] = metadata_owner_id unless metadata_owner_id.nil?
command.params['deviceId'] = device_id unless device_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Unclaims a device from a customer and removes it from zero-touch
# enrollment.
# @param [Fixnum] partner_id
# Required. The ID of the reseller partner.
# @param [Google::Apis::AndroiddeviceprovisioningV1::UnclaimDeviceRequest] unclaim_device_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::Empty] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::Empty]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def unclaim_device(partner_id, unclaim_device_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/partners/{+partnerId}/devices:unclaim', options)
command.request_representation = Google::Apis::AndroiddeviceprovisioningV1::UnclaimDeviceRequest::Representation
command.request_object = unclaim_device_request_object
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::Empty::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::Empty
command.params['partnerId'] = partner_id unless partner_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Unclaims a batch of devices for a customer asynchronously. Removes the
# devices from zero-touch enrollment. To learn more, read [Long‑running batch
# operations](/zero-touch/guides/how-it-works#operations).
# @param [Fixnum] partner_id
# Required. The reseller partner ID.
# @param [Google::Apis::AndroiddeviceprovisioningV1::UnclaimDevicesRequest] unclaim_devices_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def unclaim_partner_device_async(partner_id, unclaim_devices_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/partners/{+partnerId}/devices:unclaimAsync', options)
command.request_representation = Google::Apis::AndroiddeviceprovisioningV1::UnclaimDevicesRequest::Representation
command.request_object = unclaim_devices_request_object
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::Operation::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::Operation
command.params['partnerId'] = partner_id unless partner_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Updates the reseller metadata attached to a batch of devices. This method
# updates devices asynchronously and returns an `Operation` that can be used
# to track progress. Read [Long‑running batch
# operations](/zero-touch/guides/how-it-works#operations).
# @param [Fixnum] partner_id
# Required. The reseller partner ID.
# @param [Google::Apis::AndroiddeviceprovisioningV1::UpdateDeviceMetadataInBatchRequest] update_device_metadata_in_batch_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def update_partner_device_metadata_async(partner_id, update_device_metadata_in_batch_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/partners/{+partnerId}/devices:updateMetadataAsync', options)
command.request_representation = Google::Apis::AndroiddeviceprovisioningV1::UpdateDeviceMetadataInBatchRequest::Representation
command.request_object = update_device_metadata_in_batch_request_object
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::Operation::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::Operation
command.params['partnerId'] = partner_id unless partner_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists the vendors of the partner.
# @param [String] parent
# Required. The resource name in the format `partners/[PARTNER_ID]`.
# @param [Fixnum] page_size
# The maximum number of results to be returned.
# @param [String] page_token
# A token identifying a page of results returned by the server.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::ListVendorsResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::ListVendorsResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_partner_vendors(parent, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/{+parent}/vendors', options)
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::ListVendorsResponse::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::ListVendorsResponse
command.params['parent'] = parent unless parent.nil?
command.query['pageSize'] = page_size unless page_size.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists the customers of the vendor.
# @param [String] parent
# Required. The resource name in the format
# `partners/[PARTNER_ID]/vendors/[VENDOR_ID]`.
# @param [Fixnum] page_size
# The maximum number of results to be returned.
# @param [String] page_token
# A token identifying a page of results returned by the server.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::AndroiddeviceprovisioningV1::ListVendorCustomersResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::AndroiddeviceprovisioningV1::ListVendorCustomersResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_partner_vendor_customers(parent, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/{+parent}/customers', options)
command.response_representation = Google::Apis::AndroiddeviceprovisioningV1::ListVendorCustomersResponse::Representation
command.response_class = Google::Apis::AndroiddeviceprovisioningV1::ListVendorCustomersResponse
command.params['parent'] = parent unless parent.nil?
command.query['pageSize'] = page_size unless page_size.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
protected
def apply_command_defaults(command)
command.query['key'] = key unless key.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
end
end
end
end
end
| 64.515528 | 166 | 0.692436 |
3336c66ac02e8dc08cf9da4d71e3622824116310 | 765 | cask "go-agent" do
version "21.4.0,13469"
sha256 "c1cfc71c5389cbb9d7d290448995515d93a01b7f1c4c236be9f0b39c4f8b89b0"
url "https://download.gocd.io/binaries/#{version.csv.first}-#{version.csv.second}/osx/go-agent-#{version.csv.first}-#{version.csv.second}-osx.zip",
verified: "download.gocd.io/binaries/"
name "Go Agent"
name "GoCD Agent"
desc "Agent for the Go Continuous Delivery platform"
homepage "https://www.gocd.org/"
livecheck do
url "https://download.gocd.org/releases.json"
regex(/go[._-]agent[._-]v?(\d+(?:\.\d+)+)[._-](\d+)[._-]osx\.zip/i)
strategy :page_match do |page, regex|
page.scan(regex).map { |match| "#{match[0]},#{match[1]}" }
end
end
binary "go-agent-#{version.before_comma}/bin/go-agent"
end
| 34.772727 | 149 | 0.670588 |
38f23865a3e46a435a1bb3b2ab794fb2ac6b7abb | 74 | require 'alchemy/ferret/engine'
module Alchemy
module Ferret
end
end
| 10.571429 | 31 | 0.77027 |
bb313b9f974a534592f36dd0bcbd2feb67eec9c6 | 263 | # Load the Rails application.
require_relative 'application'
# Initialize the Rails application.
Rails.application.initialize!
# Cleaner (and less shout-y) reading from the environment variables:
def env(name, default)
ENV["EOL_#{name.upcase}"] || default
end
| 23.909091 | 68 | 0.771863 |
7a970d2b361e3e7fd0161811b1b82b65205468df | 2,814 | class AdvisingStudentController < ApplicationController
include CampusSolutions::StudentLookupFeatureFlagged
include AdvisorAuthorization
before_action :api_authenticate
before_action :authorize_for_student
rescue_from StandardError, with: :handle_api_exception
rescue_from Errors::ClientError, with: :handle_client_error
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
def academics
render json: MyAcademics::FilteredForAdvisor.from_session('user_id' => student_uid_param).get_feed_as_json
end
def academics_cache_expiry
MyAcademics::FilteredForAdvisor.expire student_uid_param
render :nothing => true
end
def advising
render json: Advising::MyAdvising.new(student_uid_param).get_feed_as_json
end
def student_committees
committees = MyCommittees::Merged.new(student_uid_param).get_feed
render json: {
studentCommittees: committees.try(:[], :studentCommittees)
}
end
def degree_progress_graduate
render json: DegreeProgress::GraduateMilestones.new(student_uid_param).get_feed_as_json
end
def degree_progress_undergrad
render json: DegreeProgress::UndergradRequirements.new(student_uid_param).get_feed_as_json
end
def enrollment_instructions
render json: MyAcademics::ClassEnrollments.new(student_uid_param).get_feed_as_json
end
def holds
render json: MyAcademics::MyHolds.new(student_uid_param).get_feed_as_json
end
def standings
render json: MyAcademics::MyStandings.new(student_uid_param).get_feed_as_json
end
def profile
student_uid = student_uid_param
render json: {
academicRoles: MyAcademics::MyAcademicRoles.new(student_uid).get_feed,
attributes: User::AggregatedAttributes.new(student_uid).get_feed,
contacts: HubEdos::V1::Contacts.new(user_id: student_uid, include_fields: %w(names addresses phones emails)).get,
residency: MyAcademics::Residency.new(student_uid).get_feed
}
end
def registrations
render json: MyRegistrations::Statuses.new(student_uid_param).get_feed_as_json
end
def resources
render json: AdvisingResources.student_specific_links(student_uid_param)
end
def student_success
render json: StudentSuccess::Merged.new(user_id: student_uid_param).get_feed
end
def transfer_credit
render json: MyAcademics::MyTransferCredit.new(student_uid_param).get_feed_as_json
end
def employment_appointments
render json: MyEmploymentAppointments.new(student_uid_param).get_feed_as_json
end
private
def authorize_for_student
raise NotAuthorizedError.new('The student lookup feature is disabled') unless is_feature_enabled
authorize_advisor_access_to_student current_user.user_id, student_uid_param
end
def student_uid_param
params.require 'student_uid'
end
end
| 29.93617 | 119 | 0.79602 |
87afa0b67e844f2416c79e84199f4ceb6c4c8401 | 484 | # frozen_string_literal: true
module Blacklight
class DocumentMetadataComponent < ::ViewComponent::Base
with_collection_parameter :fields
# @param fields [Enumerable<Blacklight::FieldPresenter>] Document field presenters
def initialize(fields:, show: false)
@fields = fields
@show = show
end
def render?
@fields.any?
end
def field_component(field)
field.try(:component) || Blacklight::MetadataFieldComponent
end
end
end
| 22 | 86 | 0.702479 |
5d4082a4686fb304e67046354a948f4c91ff4ab8 | 392 | require 'spec_helper'
require 'rdf/spec/repository'
describe RDF::Blazegraph::Repository do
let(:endpoint) { 'http://localhost:9999/bigdata/sparql' }
before { RDF::Blazegraph::Repository.new('http://localhost:9999/bigdata/sparql').clear! }
# @see lib/rdf/spec/repository.rb
let(:repository) { RDF::Blazegraph::Repository.new(endpoint) }
it_behaves_like 'an RDF::Repository'
end
| 28 | 91 | 0.734694 |
5d0b69aa7ce541e48f88b240d4485729155f1ec0 | 1,339 | require 'faraday'
module Dtime
module Connection
# A module for methods that will be available on the faraday body
module Response
module Helpers
RATELIMIT = 'X-RateLimit-Remaining'.freeze
CONTENT_TYPE = 'Content-Type'.freeze
CONTENT_LENGTH = 'content-length'.freeze
attr_reader :env
# Requests are limited to API v3 to 5000 per hour.
def ratelimit
loaded? ? @env[:response_headers][RATELIMIT] : nil
end
def content_type
loaded? ? @env[:response_headers][CONTENT_TYPE] : nil
end
def content_length
loaded? ? @env[:response_headers][CONTENT_LENGTH] : nil
end
def status
loaded? ? @env[:status] : nil
end
def success?
(200..299).include? status
end
def body
loaded? ? @env[:body] : nil
end
def loaded?
!!env
end
# Faraday middleware to mix the response helpers module
# into the body
class Middleware < Faraday::Response::Middleware
def on_complete(env)
env[:body].extend(Dtime::Connection::Response::Helpers)
env[:body].instance_eval { @env = env }
end
end
end
end # Response::Helpers
end
end # Dtime
| 23.086207 | 69 | 0.570575 |
2123f710efcd7822eda7a1cdb9b11bf5364a0d40 | 1,482 | require 'test_helper'
class UsersLoginTest < ActionDispatch::IntegrationTest
def setup
@user = users(:michael)
end
test "login with invalid information" do
get login_path
assert_template 'sessions/new'
post login_path, params: { session: { email: "", password: "" } }
assert_template 'sessions/new'
assert_not flash.empty?
get root_path
assert flash.empty?
end
test "login with valid information followed by logout" do
get login_path
post login_path, params: { session: { email: @user.email, password: "password" }}
assert is_logged_in?
assert_redirected_to @user
follow_redirect!
assert_template "users/show"
assert_select "a[href=?]", login_path, count: 0
assert_select "a[href=?]", logout_path
assert_select "a[href=?]", user_path(@user)
delete logout_path
assert_not is_logged_in?
assert_redirected_to root_url
delete logout_path
follow_redirect!
assert_select "a[href=?]", login_path
assert_select "a[href=?]", logout_path, count: 0
assert_select "a[href=?]", user_path(@user), count: 0
end
test "login with remembering" do
log_in_as(@user, remember_me: "1")
assert_equal cookies["remember_token"], assigns(:user).remember_token
end
test "login without remembering" do
log_in_as(@user, remember_me: "1")
delete logout_path
log_in_as(@user, remember_me: "0")
assert_empty cookies["remember_token"]
end
end
| 27.962264 | 85 | 0.690283 |
abfa0aa8e683c2a907a82f9f4c15ae3d2b14f695 | 222 | object false
node (:success) { true }
node (:info) { 'ok' }
child :data do
node (:students_count) { @students.size }
child @students do
attributes :id, :username, :first_name, :last_name, :status, :avatar
end
end | 24.666667 | 72 | 0.671171 |
aba48a83cdb48e64f60a31d10b15b9d186681820 | 521 | module Harness
class Gauge < Measurement
def initialize(attributes = {})
super
self.units ||= :ms
end
def self.from_event(event)
if event.payload[:gauge].is_a? Hash
gauge = new event.payload[:gauge]
elsif event.payload[:gauge].is_a?(Symbol) || event.payload[:gauge].is_a?(String)
gauge = new :id => event.payload[:gauge].to_s
else
gauge = new
end
gauge.id ||= event.name
gauge.value ||= event.duration
gauge
end
end
end
| 21.708333 | 86 | 0.591171 |
611fa0a539af14f3ffc781874d8eb719260ada2a | 760 | require 'resque_scheduler'
Resque.redis = 'localhost:6379'
Resque.redis.namespace = "resque:SchedulerExample"
# If you want to be able to dynamically change the schedule,
# uncomment this line. A dynamic schedule can be updated via the
# Resque::Scheduler.set_schedule (and remove_schedule) methods.
# When dynamic is set to true, the scheduler process looks for
# schedule changes and applies them on the fly.
# Note: This feature is only available in >=2.0.0.
#Resque::Scheduler.dynamic = true
Dir["#{Rails.root}/app/jobs/*.rb"].each { |file| require file }
# The schedule doesn't need to be stored in a YAML, it just needs to
# be a hash. YAML is usually the easiest.
Resque.schedule = YAML.load_file(Rails.root.join('config', 'resque_schedule.yml'))
| 40 | 82 | 0.751316 |
28fa7ced281bb566824096326e2928201434ea02 | 30,636 | # 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::V2017_09_01
#
# Network Client
#
class VirtualNetworkPeerings
include MsRestAzure
#
# Creates and initializes a new instance of the VirtualNetworkPeerings class.
# @param client service class for accessing basic functionality.
#
def initialize(client)
@client = client
end
# @return [NetworkManagementClient] reference to the NetworkManagementClient
attr_reader :client
#
# Deletes the specified virtual network peering.
#
# @param resource_group_name [String] The name of the resource group.
# @param virtual_network_name [String] The name of the virtual network.
# @param virtual_network_peering_name [String] The name of the virtual network
# peering.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
def delete(resource_group_name, virtual_network_name, virtual_network_peering_name, custom_headers:nil)
response = delete_async(resource_group_name, virtual_network_name, virtual_network_peering_name, custom_headers:custom_headers).value!
nil
end
#
# @param resource_group_name [String] The name of the resource group.
# @param virtual_network_name [String] The name of the virtual network.
# @param virtual_network_peering_name [String] The name of the virtual network
# peering.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Concurrent::Promise] promise which provides async access to http
# response.
#
def delete_async(resource_group_name, virtual_network_name, virtual_network_peering_name, custom_headers:nil)
# Send request
promise = begin_delete_async(resource_group_name, virtual_network_name, virtual_network_peering_name, custom_headers:custom_headers)
promise = promise.then do |response|
# Defining deserialization method.
deserialize_method = lambda do |parsed_response|
end
# Waiting for response.
@client.get_long_running_operation_result(response, deserialize_method)
end
promise
end
#
# Gets the specified virtual network peering.
#
# @param resource_group_name [String] The name of the resource group.
# @param virtual_network_name [String] The name of the virtual network.
# @param virtual_network_peering_name [String] The name of the virtual network
# peering.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [VirtualNetworkPeering] operation results.
#
def get(resource_group_name, virtual_network_name, virtual_network_peering_name, custom_headers:nil)
response = get_async(resource_group_name, virtual_network_name, virtual_network_peering_name, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Gets the specified virtual network peering.
#
# @param resource_group_name [String] The name of the resource group.
# @param virtual_network_name [String] The name of the virtual network.
# @param virtual_network_peering_name [String] The name of the virtual network
# peering.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def get_with_http_info(resource_group_name, virtual_network_name, virtual_network_peering_name, custom_headers:nil)
get_async(resource_group_name, virtual_network_name, virtual_network_peering_name, custom_headers:custom_headers).value!
end
#
# Gets the specified virtual network peering.
#
# @param resource_group_name [String] The name of the resource group.
# @param virtual_network_name [String] The name of the virtual network.
# @param virtual_network_peering_name [String] The name of the virtual network
# peering.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def get_async(resource_group_name, virtual_network_name, virtual_network_peering_name, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'virtual_network_name is nil' if virtual_network_name.nil?
fail ArgumentError, 'virtual_network_peering_name is nil' if virtual_network_peering_name.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'virtualNetworkName' => virtual_network_name,'virtualNetworkPeeringName' => virtual_network_peering_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2017_09_01::Models::VirtualNetworkPeering.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Creates or updates a peering in the specified virtual network.
#
# @param resource_group_name [String] The name of the resource group.
# @param virtual_network_name [String] The name of the virtual network.
# @param virtual_network_peering_name [String] The name of the peering.
# @param virtual_network_peering_parameters [VirtualNetworkPeering] Parameters
# supplied to the create or update virtual network peering operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [VirtualNetworkPeering] operation results.
#
def create_or_update(resource_group_name, virtual_network_name, virtual_network_peering_name, virtual_network_peering_parameters, custom_headers:nil)
response = create_or_update_async(resource_group_name, virtual_network_name, virtual_network_peering_name, virtual_network_peering_parameters, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# @param resource_group_name [String] The name of the resource group.
# @param virtual_network_name [String] The name of the virtual network.
# @param virtual_network_peering_name [String] The name of the peering.
# @param virtual_network_peering_parameters [VirtualNetworkPeering] Parameters
# supplied to the create or update virtual network peering operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Concurrent::Promise] promise which provides async access to http
# response.
#
def create_or_update_async(resource_group_name, virtual_network_name, virtual_network_peering_name, virtual_network_peering_parameters, custom_headers:nil)
# Send request
promise = begin_create_or_update_async(resource_group_name, virtual_network_name, virtual_network_peering_name, virtual_network_peering_parameters, custom_headers:custom_headers)
promise = promise.then do |response|
# Defining deserialization method.
deserialize_method = lambda do |parsed_response|
result_mapper = Azure::Network::Mgmt::V2017_09_01::Models::VirtualNetworkPeering.mapper()
parsed_response = @client.deserialize(result_mapper, parsed_response)
end
# Waiting for response.
@client.get_long_running_operation_result(response, deserialize_method)
end
promise
end
#
# Gets all virtual network peerings in a virtual network.
#
# @param resource_group_name [String] The name of the resource group.
# @param virtual_network_name [String] The name of the virtual network.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Array<VirtualNetworkPeering>] operation results.
#
def list(resource_group_name, virtual_network_name, custom_headers:nil)
first_page = list_as_lazy(resource_group_name, virtual_network_name, custom_headers:custom_headers)
first_page.get_all_items
end
#
# Gets all virtual network peerings in a virtual network.
#
# @param resource_group_name [String] The name of the resource group.
# @param virtual_network_name [String] The name of the virtual network.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_with_http_info(resource_group_name, virtual_network_name, custom_headers:nil)
list_async(resource_group_name, virtual_network_name, custom_headers:custom_headers).value!
end
#
# Gets all virtual network peerings in a virtual network.
#
# @param resource_group_name [String] The name of the resource group.
# @param virtual_network_name [String] The name of the virtual network.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_async(resource_group_name, virtual_network_name, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'virtual_network_name is nil' if virtual_network_name.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'virtualNetworkName' => virtual_network_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2017_09_01::Models::VirtualNetworkPeeringListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Deletes the specified virtual network peering.
#
# @param resource_group_name [String] The name of the resource group.
# @param virtual_network_name [String] The name of the virtual network.
# @param virtual_network_peering_name [String] The name of the virtual network
# peering.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
#
def begin_delete(resource_group_name, virtual_network_name, virtual_network_peering_name, custom_headers:nil)
response = begin_delete_async(resource_group_name, virtual_network_name, virtual_network_peering_name, custom_headers:custom_headers).value!
nil
end
#
# Deletes the specified virtual network peering.
#
# @param resource_group_name [String] The name of the resource group.
# @param virtual_network_name [String] The name of the virtual network.
# @param virtual_network_peering_name [String] The name of the virtual network
# peering.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def begin_delete_with_http_info(resource_group_name, virtual_network_name, virtual_network_peering_name, custom_headers:nil)
begin_delete_async(resource_group_name, virtual_network_name, virtual_network_peering_name, custom_headers:custom_headers).value!
end
#
# Deletes the specified virtual network peering.
#
# @param resource_group_name [String] The name of the resource group.
# @param virtual_network_name [String] The name of the virtual network.
# @param virtual_network_peering_name [String] The name of the virtual network
# peering.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def begin_delete_async(resource_group_name, virtual_network_name, virtual_network_peering_name, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'virtual_network_name is nil' if virtual_network_name.nil?
fail ArgumentError, 'virtual_network_peering_name is nil' if virtual_network_peering_name.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'virtualNetworkName' => virtual_network_name,'virtualNetworkPeeringName' => virtual_network_peering_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:delete, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200 || status_code == 204 || status_code == 202
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
result
end
promise.execute
end
#
# Creates or updates a peering in the specified virtual network.
#
# @param resource_group_name [String] The name of the resource group.
# @param virtual_network_name [String] The name of the virtual network.
# @param virtual_network_peering_name [String] The name of the peering.
# @param virtual_network_peering_parameters [VirtualNetworkPeering] Parameters
# supplied to the create or update virtual network peering operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [VirtualNetworkPeering] operation results.
#
def begin_create_or_update(resource_group_name, virtual_network_name, virtual_network_peering_name, virtual_network_peering_parameters, custom_headers:nil)
response = begin_create_or_update_async(resource_group_name, virtual_network_name, virtual_network_peering_name, virtual_network_peering_parameters, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Creates or updates a peering in the specified virtual network.
#
# @param resource_group_name [String] The name of the resource group.
# @param virtual_network_name [String] The name of the virtual network.
# @param virtual_network_peering_name [String] The name of the peering.
# @param virtual_network_peering_parameters [VirtualNetworkPeering] Parameters
# supplied to the create or update virtual network peering operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def begin_create_or_update_with_http_info(resource_group_name, virtual_network_name, virtual_network_peering_name, virtual_network_peering_parameters, custom_headers:nil)
begin_create_or_update_async(resource_group_name, virtual_network_name, virtual_network_peering_name, virtual_network_peering_parameters, custom_headers:custom_headers).value!
end
#
# Creates or updates a peering in the specified virtual network.
#
# @param resource_group_name [String] The name of the resource group.
# @param virtual_network_name [String] The name of the virtual network.
# @param virtual_network_peering_name [String] The name of the peering.
# @param virtual_network_peering_parameters [VirtualNetworkPeering] Parameters
# supplied to the create or update virtual network peering operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def begin_create_or_update_async(resource_group_name, virtual_network_name, virtual_network_peering_name, virtual_network_peering_parameters, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'virtual_network_name is nil' if virtual_network_name.nil?
fail ArgumentError, 'virtual_network_peering_name is nil' if virtual_network_peering_name.nil?
fail ArgumentError, 'virtual_network_peering_parameters is nil' if virtual_network_peering_parameters.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
# Serialize Request
request_mapper = Azure::Network::Mgmt::V2017_09_01::Models::VirtualNetworkPeering.mapper()
request_content = @client.serialize(request_mapper, virtual_network_peering_parameters)
request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'virtualNetworkName' => virtual_network_name,'virtualNetworkPeeringName' => virtual_network_peering_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
body: request_content,
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:put, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200 || status_code == 201
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2017_09_01::Models::VirtualNetworkPeering.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
# Deserialize Response
if status_code == 201
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2017_09_01::Models::VirtualNetworkPeering.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Gets all virtual network peerings in a virtual network.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [VirtualNetworkPeeringListResult] operation results.
#
def list_next(next_page_link, custom_headers:nil)
response = list_next_async(next_page_link, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Gets all virtual network peerings in a virtual network.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_next_with_http_info(next_page_link, custom_headers:nil)
list_next_async(next_page_link, custom_headers:custom_headers).value!
end
#
# Gets all virtual network peerings in a virtual network.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_next_async(next_page_link, custom_headers:nil)
fail ArgumentError, 'next_page_link is nil' if next_page_link.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{nextLink}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
skip_encoding_path_params: {'nextLink' => next_page_link},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2017_09_01::Models::VirtualNetworkPeeringListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Gets all virtual network peerings in a virtual network.
#
# @param resource_group_name [String] The name of the resource group.
# @param virtual_network_name [String] The name of the virtual network.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [VirtualNetworkPeeringListResult] which provide lazy access to pages
# of the response.
#
def list_as_lazy(resource_group_name, virtual_network_name, custom_headers:nil)
response = list_async(resource_group_name, virtual_network_name, custom_headers:custom_headers).value!
unless response.nil?
page = response.body
page.next_method = Proc.new do |next_page_link|
list_next_async(next_page_link, custom_headers:custom_headers)
end
page
end
end
end
end
| 48.245669 | 217 | 0.72343 |
2800bb0a1c7749717cc14f64070caf4a6e3d1720 | 971 | require 'switches'
namespace :s do
desc "List current"
task :c do
Switches.dump :current
end
desc "Diff current vs. default switches"
task :d do
Switches.dump :diff
end
desc "Turn on switch"
task :on, :name do |t, args|
Switches.turn_on args.name
Switches.dump :current
end
desc "Turn off switch"
task :off, :name do |t, args|
Switches.turn_off args.name
Switches.dump :current
end
desc "Clear switch"
task :clear, :name do |t, args|
Switches.clear args.name
Switches.dump :current
end
desc "Reset all switches to defaults"
task :reset do
Switches.reset
Switches.dump :current
end
desc "Backup all switches to defaults"
task :backup do
Switches.backup
Switches.dump :current
end
desc "Restore all switches to defaults"
task :restore do
Switches.restore
Switches.dump :current
end
desc "List default"
task :default do
Switches.dump :default
end
end
| 17.654545 | 42 | 0.675592 |
5d172163febb9e698a9cb7a3ed5f98bac73d2e03 | 880 | #
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html.
# Run `pod lib lint omnisaude_chatbot.podspec' to validate before publishing.
#
Pod::Spec.new do |s|
s.name = 'omnisaude_chatbot'
s.version = '0.0.1'
s.summary = 'A new flutter plugin project.'
s.description = <<-DESC
A new flutter plugin project.
DESC
s.homepage = 'http://example.com'
s.license = { :file => '../LICENSE' }
s.author = { 'Your Company' => '[email protected]' }
s.source = { :path => '.' }
s.source_files = 'Classes/**/*'
s.dependency 'Flutter'
s.platform = :ios, '8.0'
# Flutter.framework does not contain a i386 slice.
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' }
s.swift_version = '5.0'
end
| 36.666667 | 105 | 0.592045 |
6183e592e9a59746fd96c9053da9fed0b2b5213e | 15,917 | # frozen_string_literal: true
require 'rubygems/test_case'
require 'rubygems/commands/query_command'
module TestGemCommandsQueryCommandSetup
def setup
super
@cmd = Gem::Commands::QueryCommand.new
@specs = add_gems_to_fetcher
@stub_ui = Gem::MockGemUi.new
@stub_fetcher = Gem::FakeFetcher.new
@stub_fetcher.data["#{@gem_repo}Marshal.#{Gem.marshal_version}"] = proc do
raise Gem::RemoteFetcher::FetchError
end
end
end
class TestGemCommandsQueryCommandWithInstalledGems < Gem::TestCase
include TestGemCommandsQueryCommandSetup
def test_execute
spec_fetcher do |fetcher|
fetcher.legacy_platform
end
@cmd.handle_options %w[-r]
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
*** REMOTE GEMS ***
a (2)
pl (1 i386-linux)
EOF
assert_equal expected, @stub_ui.output
assert_equal '', @stub_ui.error
end
def test_execute_all
spec_fetcher do |fetcher|
fetcher.legacy_platform
end
@cmd.handle_options %w[-r --all]
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
*** REMOTE GEMS ***
a (2, 1)
pl (1 i386-linux)
EOF
assert_equal expected, @stub_ui.output
assert_equal '', @stub_ui.error
end
def test_execute_all_prerelease
spec_fetcher do |fetcher|
fetcher.legacy_platform
end
@cmd.handle_options %w[-r --all --prerelease]
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
*** REMOTE GEMS ***
a (3.a, 2, 1)
pl (1 i386-linux)
EOF
assert_equal expected, @stub_ui.output
assert_equal '', @stub_ui.error
end
def test_execute_details
spec_fetcher do |fetcher|
fetcher.spec 'a', 2 do |s|
s.summary = 'This is a lot of text. ' * 4
s.authors = ['Abraham Lincoln', 'Hirohito']
s.homepage = 'http://a.example.com/'
end
fetcher.legacy_platform
end
@cmd.handle_options %w[-r -d]
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
*** REMOTE GEMS ***
a (2)
Authors: Abraham Lincoln, Hirohito
Homepage: http://a.example.com/
This is a lot of text. This is a lot of text. This is a lot of text.
This is a lot of text.
pl (1)
Platform: i386-linux
Author: A User
Homepage: http://example.com
this is a summary
EOF
assert_equal expected, @stub_ui.output
assert_equal '', @stub_ui.error
end
def test_execute_details_cleans_text
spec_fetcher do |fetcher|
fetcher.spec 'a', 2 do |s|
s.summary = 'This is a lot of text. ' * 4
s.authors = ["Abraham Lincoln \x01", "\x02 Hirohito"]
s.homepage = "http://a.example.com/\x03"
end
fetcher.legacy_platform
end
@cmd.handle_options %w[-r -d]
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
*** REMOTE GEMS ***
a (2)
Authors: Abraham Lincoln ., . Hirohito
Homepage: http://a.example.com/.
This is a lot of text. This is a lot of text. This is a lot of text.
This is a lot of text.
pl (1)
Platform: i386-linux
Author: A User
Homepage: http://example.com
this is a summary
EOF
assert_equal expected, @stub_ui.output
assert_equal '', @stub_ui.error
end
def test_execute_details_truncates_summary
spec_fetcher do |fetcher|
fetcher.spec 'a', 2 do |s|
s.summary = 'This is a lot of text. ' * 10_000
s.authors = ["Abraham Lincoln \x01", "\x02 Hirohito"]
s.homepage = "http://a.example.com/\x03"
end
fetcher.legacy_platform
end
@cmd.handle_options %w[-r -d]
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
*** REMOTE GEMS ***
a (2)
Authors: Abraham Lincoln ., . Hirohito
Homepage: http://a.example.com/.
Truncating the summary for a-2 to 100,000 characters:
#{" This is a lot of text. This is a lot of text. This is a lot of text.\n" * 1449} This is a lot of te
pl (1)
Platform: i386-linux
Author: A User
Homepage: http://example.com
this is a summary
EOF
assert_equal expected, @stub_ui.output
assert_equal '', @stub_ui.error
end
def test_execute_installed
@cmd.handle_options %w[-n a --installed]
assert_raises Gem::MockGemUi::SystemExitException do
use_ui @stub_ui do
@cmd.execute
end
end
assert_equal "true\n", @stub_ui.output
assert_equal '', @stub_ui.error
end
def test_execute_installed_inverse
@cmd.handle_options %w[-n a --no-installed]
e = assert_raises Gem::MockGemUi::TermError do
use_ui @stub_ui do
@cmd.execute
end
end
assert_equal "false\n", @stub_ui.output
assert_equal '', @stub_ui.error
assert_equal 1, e.exit_code
end
def test_execute_installed_inverse_not_installed
@cmd.handle_options %w[-n not_installed --no-installed]
assert_raises Gem::MockGemUi::SystemExitException do
use_ui @stub_ui do
@cmd.execute
end
end
assert_equal "true\n", @stub_ui.output
assert_equal '', @stub_ui.error
end
def test_execute_installed_no_name
@cmd.handle_options %w[--installed]
e = assert_raises Gem::MockGemUi::TermError do
use_ui @stub_ui do
@cmd.execute
end
end
assert_equal '', @stub_ui.output
assert_equal "ERROR: You must specify a gem name\n", @stub_ui.error
assert_equal 4, e.exit_code
end
def test_execute_installed_not_installed
@cmd.handle_options %w[-n not_installed --installed]
e = assert_raises Gem::MockGemUi::TermError do
use_ui @stub_ui do
@cmd.execute
end
end
assert_equal "false\n", @stub_ui.output
assert_equal '', @stub_ui.error
assert_equal 1, e.exit_code
end
def test_execute_installed_version
@cmd.handle_options %w[-n a --installed --version 2]
assert_raises Gem::MockGemUi::SystemExitException do
use_ui @stub_ui do
@cmd.execute
end
end
assert_equal "true\n", @stub_ui.output
assert_equal '', @stub_ui.error
end
def test_execute_installed_version_not_installed
@cmd.handle_options %w[-n c --installed --version 2]
e = assert_raises Gem::MockGemUi::TermError do
use_ui @stub_ui do
@cmd.execute
end
end
assert_equal "false\n", @stub_ui.output
assert_equal '', @stub_ui.error
assert_equal 1, e.exit_code
end
def test_execute_local
spec_fetcher do |fetcher|
fetcher.legacy_platform
end
@cmd.options[:domain] = :local
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
*** LOCAL GEMS ***
a (3.a, 2, 1)
pl (1 i386-linux)
EOF
assert_equal expected, @stub_ui.output
assert_equal '', @stub_ui.error
end
def test_execute_local_notty
spec_fetcher do |fetcher|
fetcher.legacy_platform
end
@cmd.handle_options %w[]
@stub_ui.outs.tty = false
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
a (3.a, 2, 1)
pl (1 i386-linux)
EOF
assert_equal expected, @stub_ui.output
assert_equal '', @stub_ui.error
end
def test_execute_local_quiet
spec_fetcher do |fetcher|
fetcher.legacy_platform
end
@cmd.options[:domain] = :local
Gem.configuration.verbose = false
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
a (3.a, 2, 1)
pl (1 i386-linux)
EOF
assert_equal expected, @stub_ui.output
assert_equal '', @stub_ui.error
end
def test_execute_no_versions
spec_fetcher do |fetcher|
fetcher.legacy_platform
end
@cmd.handle_options %w[-r --no-versions]
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
*** REMOTE GEMS ***
a
pl
EOF
assert_equal expected, @stub_ui.output
assert_equal '', @stub_ui.error
end
def test_execute_notty
spec_fetcher do |fetcher|
fetcher.legacy_platform
end
@cmd.handle_options %w[-r]
@stub_ui.outs.tty = false
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
a (2)
pl (1 i386-linux)
EOF
assert_equal expected, @stub_ui.output
assert_equal '', @stub_ui.error
end
def test_execute_prerelease
@cmd.handle_options %w[-r --prerelease]
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
*** REMOTE GEMS ***
a (3.a)
EOF
assert_equal expected, @stub_ui.output
assert_equal '', @stub_ui.error
end
def test_execute_prerelease_local
spec_fetcher do |fetcher|
fetcher.legacy_platform
end
@cmd.handle_options %w[-l --prerelease]
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
*** LOCAL GEMS ***
a (3.a, 2, 1)
pl (1 i386-linux)
EOF
assert_equal expected, @stub_ui.output
end
def test_execute_no_prerelease_local
spec_fetcher do |fetcher|
fetcher.legacy_platform
end
@cmd.handle_options %w[-l --no-prerelease]
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
*** LOCAL GEMS ***
a (2, 1)
pl (1 i386-linux)
EOF
assert_equal expected, @stub_ui.output
end
def test_execute_remote
spec_fetcher do |fetcher|
fetcher.legacy_platform
end
@cmd.options[:domain] = :remote
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
*** REMOTE GEMS ***
a (2)
pl (1 i386-linux)
EOF
assert_equal expected, @stub_ui.output
assert_equal '', @stub_ui.error
end
def test_execute_remote_notty
spec_fetcher do |fetcher|
fetcher.legacy_platform
end
@cmd.handle_options %w[]
@stub_ui.outs.tty = false
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
a (3.a, 2, 1)
pl (1 i386-linux)
EOF
assert_equal expected, @stub_ui.output
assert_equal '', @stub_ui.error
end
def test_execute_remote_quiet
spec_fetcher do |fetcher|
fetcher.legacy_platform
end
@cmd.options[:domain] = :remote
Gem.configuration.verbose = false
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
a (2)
pl (1 i386-linux)
EOF
assert_equal expected, @stub_ui.output
assert_equal '', @stub_ui.error
end
def test_make_entry
a_2_name = @specs['a-2'].original_name
@stub_fetcher.data.delete \
"#{@gem_repo}quick/Marshal.#{Gem.marshal_version}/#{a_2_name}.gemspec.rz"
a2 = @specs['a-2']
entry_tuples = [
[Gem::NameTuple.new(a2.name, a2.version, a2.platform),
Gem.sources.first],
]
platforms = { a2.version => [a2.platform] }
entry = @cmd.send :make_entry, entry_tuples, platforms
assert_equal 'a (2)', entry
end
# Test for multiple args handling!
def test_execute_multiple_args
spec_fetcher do |fetcher|
fetcher.legacy_platform
end
@cmd.handle_options %w[a pl]
use_ui @stub_ui do
@cmd.execute
end
assert_match %r%^a %, @stub_ui.output
assert_match %r%^pl %, @stub_ui.output
assert_equal '', @stub_ui.error
end
def test_show_gems
@cmd.options[:name] = //
@cmd.options[:domain] = :remote
use_ui @stub_ui do
@cmd.send :show_gems, /a/i
end
assert_match %r%^a %, @stub_ui.output
refute_match %r%^pl %, @stub_ui.output
assert_empty @stub_ui.error
end
private
def add_gems_to_fetcher
spec_fetcher do |fetcher|
fetcher.spec 'a', 1
fetcher.spec 'a', 2
fetcher.spec 'a', '3.a'
end
end
end
class TestGemCommandsQueryCommandWithoutInstalledGems < Gem::TestCase
include TestGemCommandsQueryCommandSetup
def test_execute_platform
spec_fetcher do |fetcher|
fetcher.spec 'a', 1
fetcher.spec 'a', 1 do |s|
s.platform = 'x86-linux'
end
fetcher.spec 'a', 2 do |s|
s.platform = 'universal-darwin'
end
end
@cmd.handle_options %w[-r -a]
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
*** REMOTE GEMS ***
a (2 universal-darwin, 1 ruby x86-linux)
EOF
assert_equal expected, @stub_ui.output
assert_equal '', @stub_ui.error
end
def test_execute_show_default_gems
spec_fetcher { |fetcher| fetcher.spec 'a', 2 }
a1 = new_default_spec 'a', 1
install_default_specs a1
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
*** LOCAL GEMS ***
a (2, default: 1)
EOF
assert_equal expected, @stub_ui.output
end
def test_execute_show_default_gems_with_platform
a1 = new_default_spec 'a', 1
a1.platform = 'java'
install_default_specs a1
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
*** LOCAL GEMS ***
a (default: 1 java)
EOF
assert_equal expected, @stub_ui.output
end
def test_execute_default_details
spec_fetcher do |fetcher|
fetcher.spec 'a', 2
end
a1 = new_default_spec 'a', 1
install_default_specs a1
@cmd.handle_options %w[-l -d]
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
*** LOCAL GEMS ***
a (2, 1)
Author: A User
Homepage: http://example.com
Installed at (2): #{@gemhome}
(1, default): #{a1.base_dir}
this is a summary
EOF
assert_equal expected, @stub_ui.output
end
def test_execute_local_details
spec_fetcher do |fetcher|
fetcher.spec 'a', 1 do |s|
s.platform = 'x86-linux'
end
fetcher.spec 'a', 2 do |s|
s.summary = 'This is a lot of text. ' * 4
s.authors = ['Abraham Lincoln', 'Hirohito']
s.homepage = 'http://a.example.com/'
s.platform = 'universal-darwin'
end
fetcher.legacy_platform
end
@cmd.handle_options %w[-l -d]
use_ui @stub_ui do
@cmd.execute
end
str = @stub_ui.output
str.gsub!(/\(\d\): [^\n]*/, "-")
str.gsub!(/at: [^\n]*/, "at: -")
expected = <<-EOF
*** LOCAL GEMS ***
a (2, 1)
Platforms:
1: x86-linux
2: universal-darwin
Authors: Abraham Lincoln, Hirohito
Homepage: http://a.example.com/
Installed at -
-
This is a lot of text. This is a lot of text. This is a lot of text.
This is a lot of text.
pl (1)
Platform: i386-linux
Author: A User
Homepage: http://example.com
Installed at: -
this is a summary
EOF
assert_equal expected, @stub_ui.output
end
def test_execute_exact_remote
spec_fetcher do |fetcher|
fetcher.spec 'coolgem-omg', 3
fetcher.spec 'coolgem', '4.2.1'
fetcher.spec 'wow_coolgem', 1
end
@cmd.handle_options %w[--remote --exact coolgem]
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
*** REMOTE GEMS ***
coolgem (4.2.1)
EOF
assert_equal expected, @stub_ui.output
end
def test_execute_exact_local
spec_fetcher do |fetcher|
fetcher.spec 'coolgem-omg', 3
fetcher.spec 'coolgem', '4.2.1'
fetcher.spec 'wow_coolgem', 1
end
@cmd.handle_options %w[--exact coolgem]
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
*** LOCAL GEMS ***
coolgem (4.2.1)
EOF
assert_equal expected, @stub_ui.output
end
def test_execute_exact_multiple
spec_fetcher do |fetcher|
fetcher.spec 'coolgem-omg', 3
fetcher.spec 'coolgem', '4.2.1'
fetcher.spec 'wow_coolgem', 1
fetcher.spec 'othergem-omg', 3
fetcher.spec 'othergem', '1.2.3'
fetcher.spec 'wow_othergem', 1
end
@cmd.handle_options %w[--exact coolgem othergem]
use_ui @stub_ui do
@cmd.execute
end
expected = <<-EOF
*** LOCAL GEMS ***
coolgem (4.2.1)
*** LOCAL GEMS ***
othergem (1.2.3)
EOF
assert_equal expected, @stub_ui.output
end
private
def add_gems_to_fetcher
spec_fetcher do |fetcher|
fetcher.download 'a', 1
fetcher.download 'a', 2
fetcher.download 'a', '3.a'
end
end
end
| 18.551282 | 109 | 0.631526 |
e98f5844d009db7556f3d64af91563d5ab4fca33 | 3,710 | # vFabric Administration Server Ruby API
# Copyright (c) 2012 VMware, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module Shared
# @abstract A collection of instances
class Instance < Shared::StateResource
include Deletable
# @return [String] the instance's name
attr_reader :name
# @private
def initialize(location, client,
group_class,
installation_class,
live_configurations_class,
pending_configurations_class,
node_instance_class,
node_instance_type)
super(location, client)
@live_configurations_location = Util::LinkUtils.get_link_href(details, 'live-configurations')
@pending_configurations_location = Util::LinkUtils.get_link_href(details, 'pending-configurations')
@group_location = Util::LinkUtils.get_link_href(details, 'group')
@group_class = group_class
@installation_class = installation_class
@node_instance_class = node_instance_class
@live_configurations_class = live_configurations_class
@pending_configurations_class = pending_configurations_class
@node_instance_type = node_instance_type
@name = details['name']
end
# Reloads the instance's details from the server
#
# @return [void]
def reload
super
@installation_location = Util::LinkUtils.get_link_href(details, 'installation')
@installation = nil
@node_instances = nil
end
# @return [Installation] the installation that this instance is using
def installation
@installation ||= @installation_class.new(@installation_location, client)
end
# @return [NodeInstance[]] the instance's individual node instances
def node_instances
@node_instances ||= create_resources_from_links(@node_instance_type, @node_instance_class)
end
# @return [Group] the group that contains this instance
def group
@group ||= @group_class.new(@group_location, client)
end
# @return the instance's live configurations
def live_configurations
@live_configurations ||= @live_configurations_class.new(@live_configurations_location, client)
end
# @return the instance's pending configurations
def pending_configurations
@pending_configurations ||= @pending_configurations_class.new(@pending_configurations_location, client)
end
# Starts the instance
#
# @param serial [Boolean] +true+ if the starting of the individual instances represented by
# this group instance should happen serially, +false+ if they should happen in parallel
def start(serial = false)
client.post(@state_location, { :status => 'STARTED', :serial => serial })
end
# Stops the instance
#
# @param serial [Boolean] +true+ if the stoping of the individual instances represented by this
# group instance should happen serially, +false+ if they should happen in parallel
def stop(serial = false)
client.post(@state_location, { :status => 'STOPPED', :serial => serial })
end
# @return [String] a string representation of the instance
def to_s
"#<#{self.class} name='#@name'>"
end
end
end | 33.727273 | 109 | 0.712938 |
7aa9ae49d74b5c944f6e90ab954e3e2660435366 | 893 | # frozen_string_literal: true
ENV["RACK_ENV"] = "test"
require File.expand_path("../config/environment", __dir__)
abort("DATABASE_URL environment variable is set") if ENV["DATABASE_URL"]
require "rspec/rails"
Dir[Rails.root.join("spec/support/**/*.rb")].sort.each { |file| require file }
module SystemTestHelper
# Extend this module in spec/support/system/*.rb
include Formulaic::Dsl
end
RSpec.configure do |config|
# Ensure that if we are running js tests, we are using latest webpack assets
# This will use the defaults of :js and :server_rendering meta tags
ReactOnRails::TestHelper.configure_rspec_to_compile_assets(config)
config.include SystemTestHelper, type: :system
config.infer_base_class_for_anonymous_controllers = false
config.infer_spec_type_from_file_location!
config.use_transactional_fixtures = true
end
ActiveRecord::Migration.maintain_test_schema!
| 30.793103 | 78 | 0.786114 |
acf2b8ae70c33b8456f462987c618a087f2913e5 | 7,257 | require_relative '../../version1_0'
require_relative '../../function'
require_relative '../../signature'
require_relative '../../semantics'
module BELParser
module Language
module Version1_0
module Functions
# ProteinAbundance: Denotes the abundance of a protein
class ProteinAbundance
extend Function
SHORT = :p
LONG = :proteinAbundance
RETURN_TYPE = BELParser::Language::Version1_0::ReturnTypes::ProteinAbundance
PROTEIN_ENC = BELParser::Language::Version1_0::ValueEncodings::ProteinAbundance
DESCRIPTION = 'Denotes the abundance of a protein'.freeze
def self.short
SHORT
end
def self.long
LONG
end
def self.return_type
RETURN_TYPE
end
def self.description
DESCRIPTION
end
def self.signatures
SIGNATURES
end
module Signatures
# ProteinAbundanceWithFusionSignature
class ProteinAbundanceWithFusionSignature
extend BELParser::Language::Signature
private_class_method :new
AST = BELParser::Language::Semantics::Builder.build do
term(
function(
identifier(
function_of(ProteinAbundance))),
argument(
parameter(
prefix(
has_namespace),
value(
has_encoding,
encoding_of(PROTEIN_ENC)))),
argument(
term(
function(
identifier(
return_type_of(BELParser::Language::Version1_0::ReturnTypes::Fusion))))))
end
private_constant :AST
STRING_FORM = 'proteinAbundance(E:proteinAbundance,F:fusion)proteinAbundance'.freeze
private_constant :STRING_FORM
def self.semantic_ast
AST
end
def self.string_form
STRING_FORM
end
end
# ProteinAbundanceWithProteinModificationSignature
class ProteinAbundanceWithProteinModificationSignature
extend BELParser::Language::Signature
private_class_method :new
AST = BELParser::Language::Semantics::Builder.build do
term(
function(
identifier(
function_of(ProteinAbundance))),
argument(
parameter(
prefix(
has_namespace),
value(
has_encoding,
encoding_of(PROTEIN_ENC)))),
argument(
term(
function(
identifier(
return_type_of(BELParser::Language::Version1_0::ReturnTypes::ProteinModification))))))
end
private_constant :AST
STRING_FORM = 'proteinAbundance(E:proteinAbundance,F:proteinModification)proteinAbundance'.freeze
private_constant :STRING_FORM
def self.semantic_ast
AST
end
def self.string_form
STRING_FORM
end
end
# ProteinAbundanceWithSubstitutionSignature
class ProteinAbundanceWithSubstitutionSignature
extend BELParser::Language::Signature
private_class_method :new
AST = BELParser::Language::Semantics::Builder.build do
term(
function(
identifier(
function_of(ProteinAbundance))),
argument(
parameter(
prefix(
has_namespace),
value(
has_encoding,
encoding_of(PROTEIN_ENC)))),
argument(
term(
function(
identifier(
return_type_of(BELParser::Language::Version1_0::ReturnTypes::Substitution))))))
end
private_constant :AST
STRING_FORM = 'proteinAbundance(E:proteinAbundance,F:substitution)proteinAbundance'.freeze
private_constant :STRING_FORM
def self.semantic_ast
AST
end
def self.string_form
STRING_FORM
end
end
# ProteinAbundanceWithTruncationSignature
class ProteinAbundanceWithTruncationSignature
extend BELParser::Language::Signature
private_class_method :new
AST = BELParser::Language::Semantics::Builder.build do
term(
function(
identifier(
function_of(ProteinAbundance))),
argument(
parameter(
prefix(
has_namespace),
value(
has_encoding,
encoding_of(PROTEIN_ENC)))),
argument(
term(
function(
identifier(
return_type_of(BELParser::Language::Version1_0::ReturnTypes::Truncation))))))
end
private_constant :AST
STRING_FORM = 'proteinAbundance(E:proteinAbundance,F:truncation)proteinAbundance'.freeze
private_constant :STRING_FORM
def self.semantic_ast
AST
end
def self.string_form
STRING_FORM
end
end
# ProteinAbundanceSignature
class ProteinAbundanceSignature
extend BELParser::Language::Signature
private_class_method :new
AST = BELParser::Language::Semantics::Builder.build do
term(
function(
identifier(
function_of(ProteinAbundance))),
argument(
parameter(
prefix(
has_namespace),
value(
has_encoding,
encoding_of(PROTEIN_ENC)))))
end
private_constant :AST
STRING_FORM = 'proteinAbundance(E:proteinAbundance)proteinAbundance'.freeze
private_constant :STRING_FORM
def self.semantic_ast
AST
end
def self.string_form
STRING_FORM
end
end
end
SIGNATURES = Signatures.constants.map do |const|
Signatures.const_get(const)
end.freeze
end
end
end
end
end
| 30.880851 | 112 | 0.481604 |
bf5a31f9ce7d6ba3938234f2d583b3fbf3800dcc | 188 | class CreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
t.string :username
t.string :password_digest
t.timestamps
end
end
end
| 17.090909 | 48 | 0.664894 |
bf025476b70562fbf2ef1be2b54e02f9f96eca06 | 685 | Gem::Specification.new do |s|
# Release Specific Information
s.version = "0.1.alpha.3"
# Gem Details
s.name = "animation"
s.authors = ["Eric Meyer"]
s.summary = %q{css3 animations plugin for compass}
s.description = %q{css3 animations plugin for compass, with core animation mixins, and optional defaul animations from animate.css.}
s.email = "[email protected]"
s.homepage = "https://github.com/ericam/compass-animation"
# Gem Files
s.files = %w(README.mdown)
s.files += Dir.glob("lib/**/*.*")
s.files += Dir.glob("stylesheets/**/*.*")
# Gem Bookkeeping
s.add_dependency("sass", [">= 3.2.0.alpha.95"])
s.add_dependency("compass", [">= 0.12.0"])
end
| 29.782609 | 134 | 0.662774 |
1829f8d81fb1516d37400ba48e813455116ceed5 | 854 | # frozen_string_literal: true
require 'helper'
require 'minitest/autorun'
require 'wrapture'
class VersionTest < Minitest::Test
def test_gemspec_date
spec = Gem::Specification.load('wrapture.gemspec')
date_regex = /^## \[(\d+\.\d+\.\d+)\] - (\d{4}-\d{2}-\d{2})/
File.open('ChangeLog.md').each do |line|
date_regex.match(line) do |match_data|
if match_data[1] == spec.version.to_s
assert_equal(match_data[2], spec.date.strftime('%Y-%m-%d'),
'the changelog date and gem date do not match')
end
end
end
end
def test_gemspec_version
spec = Gem::Specification.load('wrapture.gemspec')
spec_version = spec.version.to_s
assert_equal Wrapture::VERSION, spec_version
end
def test_version_syntax
assert_match(/\d+\.\d+\.\d+/, Wrapture::VERSION)
end
end
| 25.878788 | 70 | 0.641686 |
28270f769f5112a4623f15ef7770418b33cd8c94 | 250 | # frozen_string_literal: true
FactoryGirl.define do
factory :notification_from_admin, class: 'Notification::FromAdmin' do
notification
body { FFaker::Lorem.paragraph }
expiration_date { Time.zone.today + rand(20) }
end
end
| 27.777778 | 71 | 0.712 |
bb4cf25cd8d989c52cc04247280de78a471d89f8 | 4,695 | RSpec.shared_examples :semaphore do
let(:semaphore) { described_class.new(3) }
describe '#initialize' do
it 'raises an exception if the initial count is not an integer' do
expect {
described_class.new('foo')
}.to raise_error(ArgumentError)
end
context 'when initializing with 0' do
let(:semaphore) { described_class.new(0) }
it do
expect(semaphore).to_not be nil
end
end
context 'when initializing with -1' do
let(:semaphore) { described_class.new(-1) }
it do
semaphore.release
expect(semaphore.available_permits).to eq 0
end
end
end
describe '#acquire' do
context 'permits available' do
it 'should return true immediately' do
result = semaphore.acquire
expect(result).to be_nil
end
end
context 'not enough permits available' do
it 'should block thread until permits are available' do
semaphore.drain_permits
in_thread { sleep(0.2); semaphore.release }
result = semaphore.acquire
expect(result).to be_nil
expect(semaphore.available_permits).to eq 0
end
end
context 'when acquiring negative permits' do
it do
expect {
semaphore.acquire(-1)
}.to raise_error(ArgumentError)
end
end
end
describe '#drain_permits' do
it 'drains all available permits' do
drained = semaphore.drain_permits
expect(drained).to eq 3
expect(semaphore.available_permits).to eq 0
end
it 'drains nothing in no permits are available' do
semaphore.reduce_permits 3
drained = semaphore.drain_permits
expect(drained).to eq 0
end
end
describe '#try_acquire' do
context 'without timeout' do
it 'acquires immediately if permits are available' do
result = semaphore.try_acquire(1)
expect(result).to be_truthy
end
it 'returns false immediately in no permits are available' do
result = semaphore.try_acquire(20)
expect(result).to be_falsey
end
context 'when trying to acquire negative permits' do
it do
expect {
semaphore.try_acquire(-1)
}.to raise_error(ArgumentError)
end
end
end
context 'with timeout' do
it 'acquires immediately if permits are available' do
result = semaphore.try_acquire(1, 5)
expect(result).to be_truthy
end
it 'acquires when permits are available within timeout' do
semaphore.drain_permits
in_thread { sleep 0.1; semaphore.release }
result = semaphore.try_acquire(1, 1)
expect(result).to be_truthy
end
it 'returns false on timeout' do
semaphore.drain_permits
result = semaphore.try_acquire(1, 0.1)
expect(result).to be_falsey
end
end
end
describe '#reduce_permits' do
it 'raises ArgumentError if reducing by negative number' do
expect {
semaphore.reduce_permits(-1)
}.to raise_error(ArgumentError)
end
it 'reduces permits below zero' do
semaphore.reduce_permits 1003
expect(semaphore.available_permits).to eq(-1000)
end
it 'reduces permits' do
semaphore.reduce_permits 1
expect(semaphore.available_permits).to eq 2
semaphore.reduce_permits 2
expect(semaphore.available_permits).to eq 0
end
it 'reduces zero permits' do
semaphore.reduce_permits 0
expect(semaphore.available_permits).to eq 3
end
end
describe '#release' do
it 'increases the number of available permits by one' do
semaphore.release
expect(semaphore.available_permits).to eq 4
end
context 'when a number of permits is specified' do
it 'increases the number of available permits by the specified value' do
semaphore.release(2)
expect(semaphore.available_permits).to eq 5
end
context 'when permits is set to negative number' do
it do
expect {
semaphore.release(-1)
}.to raise_error(ArgumentError)
end
end
end
end
end
module Concurrent
RSpec.describe MutexSemaphore do
it_should_behave_like :semaphore
end
if Concurrent.on_jruby?
RSpec.describe JavaSemaphore do
it_should_behave_like :semaphore
end
end
RSpec.describe Semaphore do
if Concurrent.on_jruby?
it 'inherits from JavaSemaphore' do
expect(Semaphore.ancestors).to include(JavaSemaphore)
end
else
it 'inherits from MutexSemaphore' do
expect(Semaphore.ancestors).to include(MutexSemaphore)
end
end
end
end
| 25.516304 | 78 | 0.652822 |
1807e107eb9f8e3a880189a6fa42b3f67cd5ff81 | 1,865 | # -*- encoding: utf-8 -*-
# stub: grape-entity 0.5.2 ruby lib
Gem::Specification.new do |s|
s.name = "grape-entity".freeze
s.version = "0.5.2"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["Michael Bleigh".freeze]
s.date = "2016-11-14"
s.description = "Extracted from Grape, A Ruby framework for rapid API development with great conventions.".freeze
s.email = ["[email protected]".freeze]
s.homepage = "https://github.com/ruby-grape/grape-entity".freeze
s.licenses = ["MIT".freeze]
s.rubygems_version = "3.0.6".freeze
s.summary = "A simple facade for managing the relationship between your model and API.".freeze
s.installed_by_version = "3.0.6" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<multi_json>.freeze, [">= 1.3.2"])
s.add_development_dependency(%q<maruku>.freeze, [">= 0"])
s.add_development_dependency(%q<yard>.freeze, [">= 0"])
s.add_development_dependency(%q<rspec>.freeze, ["~> 2.9"])
s.add_development_dependency(%q<bundler>.freeze, [">= 0"])
else
s.add_dependency(%q<multi_json>.freeze, [">= 1.3.2"])
s.add_dependency(%q<maruku>.freeze, [">= 0"])
s.add_dependency(%q<yard>.freeze, [">= 0"])
s.add_dependency(%q<rspec>.freeze, ["~> 2.9"])
s.add_dependency(%q<bundler>.freeze, [">= 0"])
end
else
s.add_dependency(%q<multi_json>.freeze, [">= 1.3.2"])
s.add_dependency(%q<maruku>.freeze, [">= 0"])
s.add_dependency(%q<yard>.freeze, [">= 0"])
s.add_dependency(%q<rspec>.freeze, ["~> 2.9"])
s.add_dependency(%q<bundler>.freeze, [">= 0"])
end
end
| 41.444444 | 115 | 0.653619 |
384e2141f6c9b5709f7ce5698a62008043242214 | 2,964 | # encoding: UTF-8
# frozen_string_literal: true
module Serializers
module EventAPI
class OrderEvent
def call(order)
{
id: order.id,
market: order.market_id,
type: type(order),
trader_uid: Member.uid(order.member_id),
income_unit: buy?(order) ? order.ask : order.bid,
income_fee_type: 'relative',
income_maker_fee_value: order.maker_fee.to_s('F'),
income_taker_fee_value: order.taker_fee.to_s('F'),
outcome_unit: buy?(order) ? order.bid : order.ask,
outcome_fee_type: 'relative',
outcome_fee_value: '0.0',
initial_income_amount: initial_income_amount(order),
current_income_amount: current_income_amount(order),
initial_outcome_amount: initial_outcome_amount(order),
current_outcome_amount: current_outcome_amount(order),
strategy: order.ord_type,
price: order.price.to_s('F'),
state: state(order),
trades_count: order.trades_count,
created_at: order.created_at.iso8601
}
end
class << self
def call(order)
new.call(order)
end
end
private
def state(order)
case order.state
when Order::CANCEL then 'canceled'
when Order::DONE then 'completed'
else 'open'
end
end
def type(order)
OrderBid === order ? 'buy' : 'sell'
end
def buy?(order)
type(order) == 'buy'
end
def sell?(order)
!buy?(order)
end
def initial_income_amount(order)
multiplier = buy?(order) ? 1.0 : order.price
amount = order.origin_volume
(amount * multiplier).to_s('F')
end
def current_income_amount(order)
multiplier = buy?(order) ? 1.0 : order.price
amount = order.volume
(amount * multiplier).to_s('F')
end
def previous_income_amount(order)
changes = order.previous_changes
multiplier = buy?(order) ? 1.0 : order.price
amount = changes.key?('volume') ? changes['volume'][0] : order.volume
(amount * multiplier).to_s('F')
end
def initial_outcome_amount(order)
attribute = buy?(order) ? 'origin_locked' : 'origin_volume'
order.send(attribute).to_s('F')
end
def current_outcome_amount(order)
attribute = buy?(order) ? 'locked' : 'volume'
order.send(attribute).to_s('F')
end
def previous_outcome_amount(order)
changes = order.previous_changes
attribute = buy?(order) ? 'locked' : 'volume'
(changes.key?(attribute) ? changes[attribute][0] : order.send(attribute)).to_s('F')
end
end
end
end
| 30.875 | 91 | 0.551282 |
5df9f1df26bf8fc7e29ca79da5e8adb9a02108b4 | 6,134 | module TextRank
##
# Primary class for keyword extraction and hub for filters, tokenizers, and
# graph strategies # that customize how the text is processed and how the
# TextRank algorithm is applied.
#
# @see README
##
class KeywordExtractor
# Creates a "basic" keyword extractor with default options
# @option (see #initialize)
# @return [KeywordExtractor]
def self.basic(**options)
new(**{
char_filters: %i[AsciiFolding Lowercase],
tokenizers: %i[Word],
token_filters: %i[Stopwords MinLength],
graph_strategy: :Coocurrence,
}.merge(options))
end
# Creates an "advanced" keyword extractor with a larger set of default filters
# @option (see #initialize)
# @return [KeywordExtractor]
def self.advanced(**options)
new(**{
char_filters: %i[AsciiFolding Lowercase StripHtml StripEmail UndoContractions StripPossessive],
tokenizers: %i[Url Money Number Word Punctuation],
token_filters: %i[PartOfSpeech Stopwords MinLength],
graph_strategy: :Coocurrence,
rank_filters: %i[CollapseAdjacent NormalizeUnitVector SortByValue],
}.merge(options))
end
# @option (see PageRank.new)
# @option options [Array<Class, Symbol, #filter!>] :char_filters A list of filters to be applied prior to tokenization
# @option options [Array<Symbol, Regexp, String>] :tokenizers A list of tokenizer regular expressions to perform tokenization
# @option options [Array<Class, Symbol, #filter!>] :token_filters A list of filters to be applied to each token after tokenization
# @option options [Class, Symbol, #build_graph] :graph_strategy A class or strategy instance for producing a graph from tokens
# @option options [Array<Class, Symbol, #filter!>] :rank_filters A list of filters to be applied to the keyword ranks after keyword extraction
def initialize(**options)
@page_rank_options = {
strategy: options[:strategy] || :sparse,
damping: options[:damping],
tolerance: options[:tolerance],
}
@char_filters = options[:char_filters] || []
@tokenizers = options[:tokenizers] || [Tokenizer::Word]
@token_filters = options[:token_filters] || []
@rank_filters = options[:rank_filters] || []
@graph_strategy = options[:graph_strategy] || GraphStrategy::Coocurrence
end
# Add a new CharFilter for processing text before tokenization
# @param filter [Class, Symbol, #filter!] A filter to process text before tokenization
# @param (see #add_into)
# @return [nil]
def add_char_filter(filter, **options)
add_into(@char_filters, filter, **options)
nil
end
# Add a tokenizer regular expression for producing tokens from filtered text
# @param tokenizer [Symbol, Regexp, String] Tokenizer regular expression
# @param (see #add_into)
# @return [nil]
def add_tokenizer(tokenizer, **options)
add_into(@tokenizers, tokenizer, **options)
nil
end
# Sets the graph strategy for producing a graph from tokens
# @param strategy [Class, Symbol, #build_graph] Strategy for producing a graph from tokens
# @return [Class, Symbol, #build_graph]
attr_writer :graph_strategy
# Add a new TokenFilter for processing tokens after tokenization
# @param filter [Class, Symbol, #filter!] A filter to process tokens after tokenization
# @param (see #add_into)
# @return [nil]
def add_token_filter(filter, **options)
add_into(@token_filters, filter, **options)
nil
end
# Add a new RankFilter for processing ranks after calculating
# @param filter [Class, Symbol, #filter!] A filter to process ranks
# @param (see #add_into)
# @return [nil]
def add_rank_filter(filter, **options)
add_into(@rank_filters, filter, **options)
nil
end
# Filters and tokenizes text
# @param text [String] unfiltered text to be tokenized
# @return [Array<String>] tokens
def tokenize(text)
filtered_text = apply_char_filters(text)
tokens = Tokenizer.tokenize(filtered_text, *tokenizer_regular_expressions)
apply_token_filters(tokens)
end
# Filter & tokenize text, and return PageRank
# @param text [String,Array<String>] unfiltered text to be processed
# @return [Hash<String, Float>] tokens and page ranks (in descending order)
def extract(text, **options)
text = Array(text)
tokens_per_text = text.map do |t|
tokenize(t)
end
graph = PageRank.new(**@page_rank_options)
strategy = classify(@graph_strategy, context: GraphStrategy)
tokens_per_text.each do |tokens|
strategy.build_graph(tokens, graph)
end
ranks = graph.calculate(**options)
tokens_per_text.each_with_index do |tokens, i|
ranks = apply_rank_filters(ranks, tokens: tokens, original_text: text[i])
end
ranks
end
private
def apply_char_filters(text)
@char_filters.reduce(text.clone) do |t, f|
classify(f, context: CharFilter).filter!(t) || t
end
end
def tokenizer_regular_expressions
@tokenizers.map do |t|
case t
when Symbol
Tokenizer.const_get(t)
else
t
end
end
end
def apply_token_filters(tokens)
@token_filters.reduce(tokens) do |t, f|
classify(f, context: TokenFilter).filter!(t) || t
end
end
def apply_rank_filters(ranks, **options)
@rank_filters.reduce(ranks) do |t, f|
classify(f, context: RankFilter).filter!(t, **options) || t
end
end
# @param before [Class, Symbol, Object] item to add before
# @param at [Fixnum] index to insert new item
def add_into(array, value, before: nil, at: nil)
idx = array.index(before) || at || -1
array.insert(idx, value)
end
def classify(clazz, context: self)
case clazz
when Class
clazz.new
when Symbol
context.const_get(clazz).new
else
clazz
end
end
end
end
| 34.852273 | 147 | 0.661396 |
91689563c8ebd75053bfa67b47cdc4642b15c6cc | 10,202 | require File.dirname(__FILE__) + '/test_helper'
require 'satellite'
def return_to; search_body("//input[@name='return_to'").first['value']; end
def cancel_to; search_body("//a[text()='Cancel']").first['href']; end
describe 'The add page' do
setup_and_teardown(:populated)
it 'should not encode the referrer when navigated to directly' do
with @ctx do
get '/new'
should.be.ok
cancel_to.should.equal '/list'
end
end
it 'should encode the referrer in a form parameter when navigated to by a link' do
with @ctx do
get '/new', "HTTP_REFERER" => "#{@base_uri}/page/Home"
should.be.ok
cancel_to.should.equal "#{@base_uri}/page/Home"
end
end
it 'should encode referrers from different domains too' do
with @ctx do
get '/new', "HTTP_REFERER" => 'http://google.ca/search?foo'
should.be.ok
cancel_to.should.equal 'http://google.ca/search?foo'
end
end
it 'should redirect to the show page if no return_to is supplied' do
with @ctx do
post '/new', :input => { :name => 'Frob', :content => '...', :return_to => '' }
should.redirect_to '/page/Frob'
end
end
it 'should redirect to the show page when saved and ignore return_to' do
with @ctx do
post '/new', :input => { :name => 'frimm', :content => '...', :return_to => "#{@base_uri}/list" }
should.redirect_to '/page/frimm'
end
end
end
describe 'The edit page' do
setup_and_teardown(:populated)
it 'should not encode the referrer when navigated to directly' do
with @ctx do
get '/page/Fizz/edit'
should.be.ok
return_to.should.equal ''
cancel_to.should.equal '/page/Fizz'
end
end
it 'should encode the referrer in a form parameter when navigated to by a link' do
with @ctx do
get '/page/Fizz/edit', "HTTP_REFERER" => "#{@base_uri}/page/Home"
should.be.ok
return_to.should.equal "#{@base_uri}/page/Home"
cancel_to.should.equal "#{@base_uri}/page/Home"
end
end
it 'should encode referrers from different domains too' do
with @ctx do
get '/page/Fizz/edit', "HTTP_REFERER" => 'http://google.ca/search?foo'
should.be.ok
return_to.should.equal 'http://google.ca/search?foo'
cancel_to.should.equal 'http://google.ca/search?foo'
end
end
it 'should redirect back to the show page if no return_to is supplied' do
with @ctx do
post '/page/Fizz/edit', :input => { :content => '...', :return_to => '' }
should.redirect_to '/page/Fizz'
end
end
it 'should redirect to return_to if return_to is supplied' do
with @ctx do
post '/page/Fizz/edit', :input => { :content => '...', :return_to => 'http://google.ca/' }
should.redirect_to 'http://google.ca/'
end
end
end
describe 'The rename page' do
setup_and_teardown(:populated)
it 'should not encode the referrer when navigated to directly' do
with @ctx do
get '/page/Fizz/rename'
should.be.ok
return_to.should.equal ''
cancel_to.should.equal '/page/Fizz'
end
end
it 'should encode the referrer in a form parameter when navigated to by a link' do
with @ctx do
get '/page/Fizz/rename', "HTTP_REFERER" => "#{@base_uri}/page/Home"
should.be.ok
return_to.should.equal "#{@base_uri}/page/Home"
cancel_to.should.equal "#{@base_uri}/page/Home"
end
end
it 'should encode referrers from different domains too' do
with @ctx do
get '/page/Fizz/rename', "HTTP_REFERER" => 'http://google.ca/search?foo'
should.be.ok
return_to.should.equal 'http://google.ca/search?foo'
cancel_to.should.equal 'http://google.ca/search?foo'
end
end
it 'should redirect to the show page if no return_to is supplied' do
with @ctx do
post '/page/Fizz/rename', :input => { :new_name => 'Fizzz', :return_to => '' }
should.redirect_to '/page/Fizzz'
end
end
it 'should redirect to return_to if return_to is supplied' do
with @ctx do
post '/page/Bozz/rename', :input => { :new_name => 'Bozzz', :return_to => 'http://google.ca/' }
should.redirect_to 'http://google.ca/'
end
end
it 'should return to the new show page if return_to is the old show page' do
with @ctx do
post '/page/bazz/rename', :input => { :new_name => 'bazzz', :return_to => "#{@base_uri}/page/bazz" }
should.redirect_to '/page/bazzz'
end
end
end
describe 'The delete page' do
setup_and_teardown(:populated)
it 'should not encode the referrer when navigated to directly' do
with @ctx do
get '/page/Fizz/delete'
should.be.ok
return_to.should.equal ''
cancel_to.should.equal '/page/Fizz'
end
end
it 'should encode the referrer in a form parameter when navigated to by a link' do
with @ctx do
get '/page/Fizz/delete', "HTTP_REFERER" => "#{@base_uri}/page/Home"
should.be.ok
return_to.should.equal "#{@base_uri}/page/Home"
cancel_to.should.equal "#{@base_uri}/page/Home"
end
end
it 'should encode referrers from different domains too' do
with @ctx do
get '/page/Fizz/delete', "HTTP_REFERER" => 'http://google.ca/search?foo'
should.be.ok
return_to.should.equal 'http://google.ca/search?foo'
cancel_to.should.equal 'http://google.ca/search?foo'
end
end
it 'should redirect to list page if no return_to is supplied' do
with @ctx do
post '/page/Fizz/delete', :input => { :return_to => '' }
should.redirect_to '/list'
end
end
it 'should redirect to return_to if return_to is supplied' do
with @ctx do
post '/page/Bozz/delete', :input => { :return_to => 'http://google.ca/' }
should.redirect_to 'http://google.ca/'
end
end
it 'should return to the list page if return_to is the show page for the deleted page' do
with @ctx do
post '/page/bazz/delete', :input => { :return_to => "#{@base_uri}/page/bazz" }
should.redirect_to '/list'
end
end
end
describe 'The resolve conflict page' do
setup_and_teardown(:populated)
it 'should not encode the referrer when navigated to directly' do
with @ctx do
get '/page/Fizz/resolve'
should.be.ok
return_to.should.equal ''
cancel_to.should.equal '/page/Fizz'
end
end
it 'should encode the referrer in a form parameter when navigated to by a link' do
with @ctx do
get '/page/Fizz/resolve', "HTTP_REFERER" => "#{@base_uri}/page/Home"
should.be.ok
return_to.should.equal "#{@base_uri}/page/Home"
cancel_to.should.equal "#{@base_uri}/page/Home"
end
end
it 'should encode referrers from different domains too' do
with @ctx do
get '/page/Fizz/resolve', "HTTP_REFERER" => 'http://google.ca/search?foo'
should.be.ok
return_to.should.equal 'http://google.ca/search?foo'
cancel_to.should.equal 'http://google.ca/search?foo'
end
end
it 'should redirect back to the show page if no return_to is supplied' do
with @ctx do
post '/page/Fizz/resolve', :input => { :content => '...', :return_to => '' }
should.redirect_to '/page/Fizz'
end
end
it 'should redirect to return_to if return_to is supplied' do
with @ctx do
post '/page/Fizz/resolve', :input => { :content => '...', :return_to => 'http://google.ca/' }
should.redirect_to 'http://google.ca/'
end
end
end
describe 'The rename upload page' do
setup_and_teardown(:populated)
it 'should not encode the referrer when navigated to directly' do
with @ctx do
get '/upload/blam.txt/rename'
should.be.ok
return_to.should.equal ''
cancel_to.should.equal '/list'
end
end
it 'should encode the referrer in a form parameter when navigated to by a link' do
with @ctx do
get '/upload/blam.txt/rename', "HTTP_REFERER" => "#{@base_uri}/page/Home"
should.be.ok
return_to.should.equal "#{@base_uri}/page/Home"
cancel_to.should.equal "#{@base_uri}/page/Home"
end
end
it 'should encode referrers from different domains too' do
with @ctx do
get '/upload/blam.txt/rename', "HTTP_REFERER" => 'http://google.ca/search?foo'
should.be.ok
return_to.should.equal 'http://google.ca/search?foo'
cancel_to.should.equal 'http://google.ca/search?foo'
end
end
it 'should redirect to the show page if no return_to is supplied' do
with @ctx do
post '/upload/blam.txt/rename', :input => { :new_name => 'blzzam.txt', :return_to => '' }
should.redirect_to '/list'
end
end
it 'should redirect to return_to if return_to is supplied' do
with @ctx do
post '/upload/Baaa.txt/rename', :input => { :new_name => 'Rawr.txt', :return_to => 'http://google.ca/' }
should.redirect_to 'http://google.ca/'
end
end
end
describe 'The delete upload page' do
setup_and_teardown(:populated)
it 'should not encode the referrer when navigated to directly' do
with @ctx do
get '/upload/blam.txt/delete'
should.be.ok
return_to.should.equal ''
cancel_to.should.equal '/list'
end
end
it 'should encode the referrer in a form parameter when navigated to by a link' do
with @ctx do
get '/upload/blam.txt/delete', "HTTP_REFERER" => "#{@base_uri}/page/Home"
should.be.ok
return_to.should.equal "#{@base_uri}/page/Home"
cancel_to.should.equal "#{@base_uri}/page/Home"
end
end
it 'should encode referrers from different domains too' do
with @ctx do
get '/upload/blam.txt/delete', "HTTP_REFERER" => 'http://google.ca/search?foo'
should.be.ok
return_to.should.equal 'http://google.ca/search?foo'
cancel_to.should.equal 'http://google.ca/search?foo'
end
end
it 'should redirect to list page if no return_to is supplied' do
with @ctx do
post '/upload/blam.txt/delete', :input => { :return_to => '' }
should.redirect_to '/list'
end
end
it 'should redirect to return_to if return_to is supplied' do
with @ctx do
post '/upload/Baaa.txt/delete', :input => { :return_to => 'http://google.ca/' }
should.redirect_to 'http://google.ca/'
end
end
end
| 30.728916 | 110 | 0.645168 |
1cc8a65a20455709ec0370fb465097ab9ae902aa | 8,786 | module Formtastic
module Helpers
# FormHelper provides a handful of wrappers around Rails' built-in form helpers methods to set
# the `:builder` option to `Formtastic::FormBuilder` and apply some class names to the `<form>`
# tag.
#
# The following methods are wrapped:
#
# * `semantic_form_for` to `form_for`
# * `semantic_fields_for` to `fields_for`
# * `semantic_remote_form_for` and `semantic_form_remote_for` to `remote_form_for`
#
# The following two examples are effectively equivalent:
#
# <%= form_for(@post, :builder => Formtastic::FormBuilder, :class => 'formtastic post') do |f| %>
# #...
# <% end %>
#
# <%= semantic_form_for(@post) do |f| %>
# #...
# <% end %>
#
# This simple wrapping means that all arguments, options and variations supported by Rails' own
# helpers are also supported by Formtastic.
#
# Since `Formtastic::FormBuilder` subclasses Rails' own `FormBuilder`, you have access to all
# of Rails' built-in form helper methods such as `text_field`, `check_box`, `radio_button`,
# etc **in addition to** all of Formtastic's additional helpers like {InputsHelper#inputs inputs},
# {InputsHelper#input input}, {ButtonsHelper#buttons buttons}, etc:
#
# <%= semantic_form_for(@post) do |f| %>
#
# <!-- Formtastic -->
# <%= f.input :title %>
#
# <!-- Rails -->
# <li class='something-custom'>
# <%= f.label :title %>
# <%= f.text_field :title %>
# <p class='hints'>...</p>
# </li>
# <% end %>
#
# Formtastic is a superset of Rails' FormBuilder. It deliberately avoids overriding or modifying
# the behavior of Rails' own form helpers so that you can use Formtastic helpers when suited,
# and fall back to regular Rails helpers, ERB and HTML when needed. In other words, you're never
# fully committed to The Formtastic Way.
module FormHelper
# Allows the `:builder` option on `form_for` etc to be changed to your own which subclasses
# `Formtastic::FormBuilder`. Change this from `config/initializers/formtastic.rb`.
@@builder = Formtastic::FormBuilder
mattr_accessor :builder
# Allows the default class we add to all `<form>` tags to be changed from `formtastic` to
# `whatever`. Change this from `config/initializers/formtastic.rb`.
@@default_form_class = 'formtastic'
mattr_accessor :default_form_class
# Allows to set a custom field_error_proc wrapper. By default this wrapper
# is disabled since `formtastic` already adds an error class to the LI tag
# containing the input. Change this from `config/initializers/formtastic.rb`.
@@formtastic_field_error_proc = proc { |html_tag, instance_tag| html_tag }
mattr_accessor :formtastic_field_error_proc
# Wrapper around Rails' own `form_for` helper to set the `:builder` option to
# `Formtastic::FormBuilder` and to set some class names on the `<form>` tag such as
# `formtastic` and the downcased and underscored model name (eg `post`).
#
# See Rails' `form_for` for full documentation of all supported arguments and options.
#
# Since `Formtastic::FormBuilder` subclasses Rails' own FormBuilder, you have access to all
# of Rails' built-in form helper methods such as `text_field`, `check_box`, `radio_button`,
# etc **in addition to** all of Formtastic's additional helpers like {InputsHelper#inputs inputs},
# {InputsHelper#input input}, {ButtonsHelper#buttons buttons}, etc.
#
# Most of the examples below have been adapted from the examples found in the Rails `form_for`
# documentation.
#
# @see http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html Rails' FormHelper documentation (`form_for`, etc)
# @see http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html Rails' FormBuilder documentaion (`text_field`, etc)
# @see FormHelper The overview of the FormBuilder module
#
# @example Resource-oriented form generation
# <%= semantic_form_for @user do |f| %>
# <%= f.input :name %>
# <%= f.input :email %>
# <%= f.input :password %>
# <% end %>
#
# @example Generic form generation
# <%= semantic_form_for :user do |f| %>
# <%= f.input :name %>
# <%= f.input :email %>
# <%= f.input :password %>
# <% end %>
#
# @example Resource-oriented with custom URL
# <%= semantic_form_for(@post, :url => super_post_path(@post)) do |f| %>
# ...
# <% end %>
#
# @example Resource-oriented with namespaced routes
# <%= semantic_form_for([:admin, @post]) do |f| %>
# ...
# <% end %>
#
# @example Resource-oriented with nested routes
# <%= semantic_form_for([@user, @post]) do |f| %>
# ...
# <% end %>
#
# @example Rename the resource
# <%= semantic_form_for(@post, :as => :article) do |f| %>
# ...
# <% end %>
#
# @example Remote forms (unobtrusive JavaScript)
# <%= semantic_form_for(@post, :remote => true) do |f| %>
# ...
# <% end %>
#
# @example Namespaced forms all multiple Formtastic forms to exist on the one page without DOM id clashes and invalid HTML documents.
# <%= semantic_form_for(@post, :namespace => 'first') do |f| %>
# ...
# <% end %>
#
# @example Accessing a mixture of Formtastic helpers and Rails FormBuilder helpers.
# <%= semantic_form_for(@post) do |f| %>
# <%= f.input :title %>
# <%= f.input :body %>
# <li class="something-custom">
# <label><%= f.check_box :published %></label>
# </li>
# <% end %>
#
# @param record_or_name_or_array
# Same behavior as Rails' `form_for`
#
# @option *args [Hash] :html
# Pass HTML attributes into the `<form>` tag. Same behavior as Rails' `form_for`, except we add in some of our own classes.
#
# @option *args [String, Hash] :url
# A hash of URL components just like you pass into `link_to` or `url_for`, or a named route (eg `posts_path`). Same behavior as Rails' `form_for`.
#
# @option *args [String] :namespace
def semantic_form_for(record_or_name_or_array, *args, &proc)
options = args.extract_options!
options[:builder] ||= @@builder
options[:html] ||= {}
options[:html][:novalidate] = !@@builder.perform_browser_validations unless options[:html].key?(:novalidate)
@@builder.custom_namespace = options.delete(:namespace).to_s
singularizer = defined?(ActiveModel::Naming.singular) ? ActiveModel::Naming.method(:singular) : ActionController::RecordIdentifier.method(:singular_class_name)
class_names = options[:html][:class] ? options[:html][:class].split(" ") : []
class_names << @@default_form_class
class_names << case record_or_name_or_array
when String, Symbol then record_or_name_or_array.to_s # :post => "post"
when Array then options[:as] || singularizer.call(record_or_name_or_array.last.class) # [@post, @comment] # => "comment"
else options[:as] || singularizer.call(record_or_name_or_array.class) # @post => "post"
end
options[:html][:class] = class_names.compact.join(" ")
with_custom_field_error_proc do
self.form_for(record_or_name_or_array, *(args << options), &proc)
end
end
# Wrapper around Rails' own `fields_for` helper to set the `:builder` option to
# `Formtastic::FormBuilder`.
#
# @see #semantic_form_for
def semantic_fields_for(record_name, record_object = nil, options = {}, &block)
options, record_object = record_object, nil if record_object.is_a?(Hash) && record_object.extractable_options?
options[:builder] ||= @@builder
@@builder.custom_namespace = options.delete(:namespace).to_s # TODO needed?
with_custom_field_error_proc do
self.fields_for(record_name, record_object, options, &block)
end
end
protected
def with_custom_field_error_proc(&block)
default_field_error_proc = ::ActionView::Base.field_error_proc
::ActionView::Base.field_error_proc = @@formtastic_field_error_proc
yield
ensure
::ActionView::Base.field_error_proc = default_field_error_proc
end
end
end
end
| 44.150754 | 167 | 0.615866 |
bb8bcadd3352c3bc46e1fe26e0e9d797be103bf1 | 896 | # frozen_string_literal: true
class SessionsController < ApplicationController
# ensures the authorized function in the applicationController
# does not run when trying to create an account or sign in
skip_before_action :authorized, only: %i[new create welcome]
# creates a new session then sets the current user id to
# the current user
def create
@user = User.find_by(username: params[:username])
# if @user && @user.authenticate(params[:password])
if @user && @user.password == (params[:password])
session[:user_id] = @user.id
redirect_to '/tasks'
else
redirect_to '/login'
end
end
def new
redirect_to '/tasks' if logged_in?
end
def page_requires_login; end
def login
redirect_to '/tasks' if logged_in?
end
def welcome
redirect_to '/tasks' if logged_in?
end
def logout
session[:user_id] = -1
end
end
| 22.974359 | 64 | 0.691964 |
87aad78d010175ed07a13b7c6fcbcafe095b2883 | 2,096 | class Event::Agents::Nodes::PageController < ApplicationController
include Cms::NodeFilter::View
include Event::EventHelper
helper Event::EventHelper
public
def index
@year = Time.zone.today.year.to_i
@month = Time.zone.today.month.to_i
monthly
end
def monthly
@year = params[:year].to_i if @year.blank?
@month = params[:month].to_i if @month.blank?
if within_one_year?(Date.new(@year, @month, 1))
index_monthly
elsif within_one_year?(Date.new(@year, @month, 1).advance(months: 1, days: -1))
index_monthly
else
raise "404"
end
end
def daily
@year = params[:year].to_i
@month = params[:month].to_i
@day = params[:day].to_i
if within_one_year?(Date.new(@year, @month, @day))
index_daily
else
raise "404"
end
end
private
def events(date)
events = Cms::Page.site(@cur_site).public(@cur_date).
where(@cur_node.condition_hash).
where(:event_dates.in => date).
entries.
sort_by{ |page| page.event_dates.size }
end
def index_monthly
@events = {}
start_date = Date.new(@year, @month, 1)
close_date = @month != 12 ? Date.new(@year, @month + 1, 1) : Date.new(@year + 1, 1, 1)
(start_date...close_date).each do |d|
@events[d] = []
end
dates = (start_date...close_date).map { |m| m.mongoize }
events(dates).each do |page|
page.event_dates.split(/\r\n|\n/).each do |date|
d = Date.parse(date)
next unless @events[d]
@events[d] << [
page,
page.categories.in(id: @cur_node.st_categories.pluck(:id)).order_by(order: 1)
]
end
end
render :monthly
end
def index_daily
@date = Date.new(@year, @month, @day)
@events = events([@date.mongoize]).map do |page|
[
page,
page.categories.in(id: @cur_node.st_categories.pluck(:id)).order_by(order: 1)
]
end
render :daily
end
end
| 24.952381 | 92 | 0.56584 |
4a430b92abefaf96ff6223fa09c5e6a797e09fa2 | 460 | class RemoveJurisdictionFromAgencies < ActiveRecord::Migration
def up
remove_column :agencies, :jurisdiction
ActiveRecord::Base.connection.execute <<-SQL
DROP TYPE jurisdiction;
SQL
end
def down
ActiveRecord::Base.connection.execute <<-SQL
CREATE TYPE jurisdiction as ENUM ('none', 'local', 'state', 'federal', 'university', 'private');
SQL
add_column :agencies, :jurisdiction, :jurisdiction, index: true
end
end
| 25.555556 | 102 | 0.706522 |
4a61ca9c852b4eaf0915e7bbb52bf9b0fd18dd19 | 1,366 | require 'http'
require 'sponsored/search'
module Sponsored
class GoogleSearch < Search
GOOGLE_SEARCH_URL = 'https://www.googleapis.com/customsearch/v1'
SEARCH_RESULT_LIMIT = 3
def results
@results ||= response.parse['items'].map { |attributes| Result.new(attributes) }
end
private
def params
{
cx: ENV['GOOGLE_CUSTOM_SEARCH_ENGINE_ID'],
key: ENV['GOOGLE_API_KEY'],
num: SEARCH_RESULT_LIMIT,
q: @search_phrase
}
end
def response
@response ||= HTTP.get(GOOGLE_SEARCH_URL, params: params).tap do |response|
unless response.code == 200
raise GoogleSearchError
end
end
end
class GoogleSearchError < StandardError; end
class Result
attr_reader :title, :url
def initialize(attributes)
@title = attributes['title']
@url = attributes['link']
end
def inspect
"#<#{self.class.name} title=#{title[0..30].strip.inspect}>"
end
def short_url
@short_url ||= BitlyClient.new(url).short_url
end
def to_irc
Cinch::Formatting.format(:green, :bold, title) + " #{url_shortened_if_necessary}"
end
def url_shortened_if_necessary
if url.length > 128
short_url
else
url
end
end
end
end
end
| 21.34375 | 89 | 0.601757 |
e22e96ef332d5ffd302a4752be97f586a1430d2d | 1,553 | class RedditProcessor < AtomProcessor
POINTS_THRESHOLD = 2000
CACHE_HISTORY_DEPTH = 4.hours
protected
def entities
super.select { |entity| enough_points?(entity.uid) }
end
private
def enough_points?(link)
reddit_points(link) >= POINTS_THRESHOLD
end
def reddit_points(link)
data_point(link).details['points'].to_i
end
def data_point(link)
cached_data_point(link) || create_data_point(link)
end
def cached_data_point(link)
logger.debug('attempting to load reddit points from cache')
DataPoint.for(:reddit)
.where('created_at > ?', CACHE_HISTORY_DEPTH.ago)
.where("details->>'link' = ?", link).ordered.first
end
# TODO: Use Reddit API instead
def create_data_point(link)
logger.debug('loading reddit points from reddit')
html = Nokogiri::HTML(page_content(link))
desc = html.at('meta[property="og:description"]').try(:[], :content).to_s
points = parse_points(desc)
raise 'error loading reddit points' unless points
CreateDataPoint.call(
:reddit,
link: link,
points: points,
description: desc
)
end
def parse_points(string)
Integer(string[/^[\d,]+/].gsub(',', ''))
rescue StandardError
nil
end
def page_content(link)
logger.debug("fetching [#{link}]")
# TODO: Figure out why sanitization is required here
safe_link = URI.encode(URI.decode(link))
CreateDataPoint.call(
:test_reddit_links,
link: link,
safe_link: safe_link
)
RestClient.get(safe_link).body
end
end
| 22.838235 | 77 | 0.674823 |
fff1300b80f0794a090bfbc8bb1885976f90a1dc | 5,437 | require_relative '/usr/src/app/sinatra_template/utils.rb'
module LoginService
module SparqlQueries
include SinatraTemplate::Utils
def remove_old_sessions(session)
query = " DELETE WHERE {"
query += " GRAPH <http://mu.semte.ch/graphs/sessions> {"
query += " <#{session}> <#{MU_SESSION.account}> ?account ;"
query += " <#{MU_CORE.uuid}> ?id ; "
query += " <#{RDF::Vocab::DC.modified}> ?modified ; "
query += " <#{MU_EXT.sessionRole}> ?role ;"
query += " <#{MU_EXT.sessionGroup}> ?group ."
query += " }"
query += " }"
update(query)
end
def insert_new_session_for_account(account, session_uri, session_id, group_uri, group_id, roles)
now = DateTime.now
query = " PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>"
query += " INSERT DATA {"
query += " GRAPH <http://mu.semte.ch/graphs/sessions> {"
query += " <#{session_uri}> <#{MU_SESSION.account}> <#{account}> ;"
query += " <#{RDF::Vocab::DC.modified}> #{now.sparql_escape} ;"
query += " <#{MU_EXT.sessionGroup}> <#{group_uri}> ;"
query += " <#{MU_CORE.uuid}> #{session_id.sparql_escape} ."
roles.each do |role|
query += " <#{session_uri}> <#{MU_EXT.sessionRole}> #{role.sparql_escape} ."
end
query += " }"
query += " }"
update(query)
end
def select_account_by_session(session)
query = " SELECT ?session_uuid ?group_uuid ?account_uuid ?account (GROUP_CONCAT(?role; SEPARATOR = ',') as ?roles) WHERE {"
query += " GRAPH <http://mu.semte.ch/graphs/sessions> {"
query += " <#{session}> <#{MU_CORE.uuid}> ?session_uuid;"
query += " <#{MU_SESSION.account}> ?account ;"
query += " <#{MU_EXT.sessionRole}> ?role ;"
query += " <#{MU_EXT.sessionGroup}> ?group ."
query += " }"
query += " GRAPH <#{graph}> {"
query += " ?group a <#{BESLUIT.Bestuurseenheid}> ;"
query += " <#{MU_CORE.uuid}> ?group_uuid ."
query += " }"
query += " GRAPH ?g {"
query += " ?account a <#{RDF::Vocab::FOAF.OnlineAccount}> ;"
query += " <#{MU_CORE.uuid}> ?account_uuid ."
query += " }"
query += " FILTER(?g = IRI(CONCAT(\"http://mu.semte.ch/graphs/organizations/\", ?group_uuid)))"
query += " } GROUP BY ?session_uuid ?group_uuid ?account_uuid ?account"
query(query)
end
def select_current_session(account)
query = " SELECT ?uri WHERE {"
query += " GRAPH <http://mu.semte.ch/graphs/sessions> {"
query += " ?uri <#{MU_SESSION.account}> <#{account}> ;"
query += " <#{MU_CORE.uuid}> ?id . "
query += " }"
query += " }"
query(query)
end
def delete_current_session(account)
query = " DELETE WHERE {"
query += " GRAPH <http://mu.semte.ch/graphs/sessions> {"
query += " ?session <#{MU_SESSION.account}> <#{account}> ;"
query += " <#{MU_CORE.uuid}> ?id ; "
query += " <#{RDF::Vocab::DC.modified}> ?modified ; "
query += " <#{MU_EXT.sessionRole}> ?role ;"
query += " <#{MU_EXT.sessionGroup}> ?group ."
query += " }"
query += " }"
update(query)
end
def select_account(id)
query = " SELECT ?uri WHERE {"
query += " GRAPH <#{graph}> {"
query += " ?group a <#{BESLUIT.Bestuurseenheid}> ;"
query += " <#{MU_CORE.uuid}> ?group_uuid ."
query += " }"
query += " GRAPH ?g {"
query += " ?uri a <#{RDF::Vocab::FOAF.OnlineAccount}> ;"
query += " <#{MU_CORE.uuid}> \"#{id}\" ."
query += " ?person a <#{RDF::Vocab::FOAF.Person}> ;"
query += " <#{RDF::Vocab::FOAF.account}> ?uri ;"
query += " <#{RDF::Vocab::FOAF.member}> ?group ."
query += " }"
query += " BIND(IRI(CONCAT(\"http://mu.semte.ch/graphs/organizations/\", ?group_uuid)) as ?g)"
query += " }"
query(query)
end
def select_group(group_id)
query = " SELECT ?group WHERE {"
query += " GRAPH <#{graph}> {"
query += " ?group a <#{BESLUIT.Bestuurseenheid}> ;"
query += " <#{MU_CORE.uuid}> \"#{group_id}\" ."
query += " }"
query += " }"
query(query)
end
def select_roles(account_id)
query = " SELECT ?role WHERE {"
query += " GRAPH <#{graph}> {"
query += " ?group a <#{BESLUIT.Bestuurseenheid}> ;"
query += " <#{MU_CORE.uuid}> ?group_uuid ."
query += " }"
query += " GRAPH ?g {"
query += " ?uri a <#{RDF::Vocab::FOAF.OnlineAccount}> ;"
query += " <#{MU_CORE.uuid}> \"#{account_id}\" ;"
query += " <#{MU_EXT.sessionRole}> ?role ."
query += " ?person a <#{RDF::Vocab::FOAF.Person}> ;"
query += " <#{RDF::Vocab::FOAF.account}> ?uri ;"
query += " <#{RDF::Vocab::FOAF.member}> ?group ."
query += " }"
query += " BIND(IRI(CONCAT(\"http://mu.semte.ch/graphs/organizations/\", ?group_uuid)) as ?g)"
query += " }"
query(query)
end
end
end
| 42.147287 | 130 | 0.488873 |
62befae5bb27fcd0dcb7d040920211a91419563e | 2,164 | # This queue service is based on aws sqs.
# To make this queue service work, one would need the aws sqs gem to be installed.
module DispatchRider
module QueueServices
class AwsSqs < Base
require "dispatch-rider/queue_services/aws_sqs/message_body_extractor"
require "dispatch-rider/queue_services/aws_sqs/sqs_received_message"
class AbortExecution < RuntimeError; end
class VisibilityTimeoutExceeded < RuntimeError; end
def assign_storage(attrs)
begin
sqs = AWS::SQS.new(logger: nil, region: attrs[:region])
if attrs[:name]
sqs.queues.named(attrs[:name])
elsif attrs[:url]
sqs.queues[attrs[:url]]
else
raise RecordInvalid.new(self, ["Either name or url have to be specified"])
end
rescue NameError
raise AdapterNotFoundError.new(self.class.name, 'aws-sdk')
end
end
def pop
raw_item = queue.receive_message
if raw_item.present?
obj = SqsReceivedMessage.new(construct_message_from(raw_item), raw_item, queue)
visibility_timeout_shield(obj) do
raise AbortExecution, "false received from handler" unless yield(obj)
obj
end
Retriable.retriable(tries: 3) { raw_item.delete }
end
rescue AbortExecution
# ignore, it was already handled, just need to break out if pop
end
def insert(item)
queue.send_message(item)
end
def construct_message_from(item)
deserialize(MessageBodyExtractor.new(item).extract)
end
def delete(item)
item.delete
end
def size
queue.approximate_number_of_messages
end
private
def visibility_timeout_shield(message)
begin
yield
ensure
duration = Time.now - message.start_time
timeout = message.total_timeout
raise VisibilityTimeoutExceeded, "message: #{message.subject}, #{message.body.inspect} took #{duration} seconds while the timeout was #{timeout}" if duration > timeout
end
end
end
end
end
| 29.243243 | 177 | 0.63817 |
616b62ab8b6121e20aff2655d6f94ee25b4197f0 | 2,554 | require "premailer"
module ActionMailer
module InStyle
class Processor
def self.inline!(message)
new(message).inline!
end
attr_reader :message, :premailer
# Initialize
# Accepts one argument:
# - ActionMailer message object
def initialize(message)
@message = message
@existing_html_part = message.html_part || (message.content_type =~ /text\/html/ && message)
@premailer = ActionMailer::InStyle::Premailer.new(html_part.body.to_s, :with_html_string => true, :remove_classes => true)
end
def html_part
@existing_html_part
end
# InStyle!
# Processes the message object, replacing the html part with an inlined
# html version.
#
# If the message contains attachments or text parts, these parts are preserved.
# If the message does not contain a text part, one will be constructed from the text
# content available in the html part.
def inline!
capture_existing_message_parts
reset_message_body!
add_text_part!
add_html_part!
add_attachments!
message
end
# Add an HTML part with CSS inlined.
def add_html_part!
part = Mail::Part.new
part.body = premailer.to_inline_css
part.content_type = "text/html; charset=#{@msg_charset}"
message.html_part = part
end
# Add a text part with either the pre-existing text part, or one generated with premailer.
def add_text_part!
part = Mail::Part.new
part.body = @existing_text_part || premailer.to_plain_text
part.content_type = "text/plain; charset=#{@msg_charset}"
message.text_part = part
end
# Re-add any attachments
def add_attachments!
@existing_attachments.each {|a| message.body << a }
end
def capture_existing_message_parts
@existing_text_part = message.text_part && message.text_part.body.to_s
@existing_attachments = message.attachments
@msg_charset = message.charset
end
def original_message_parts
capture_existing_message_parts
{
:html_part => html_part,
:text_part => @existing_text_part,
:attachments => @existing_attachments,
:charset => @msg_charset
}
end
def reset_message_body!
message.body = nil
message.body.instance_variable_set("@parts", Mail::PartsList.new)
end
end
end
end
| 28.065934 | 130 | 0.630775 |
4aa4400cda0165c558620d09b26c6503f06a8dfa | 1,454 | class Kubevela < Formula
desc "Application Platform based on Kubernetes and Open Application Model"
homepage "https://kubevela.io"
url "https://github.com/oam-dev/kubevela.git",
tag: "v1.0.1",
revision: "1444376b0cf17add8c818078fb9496c23c45ed32"
license "Apache-2.0"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "ff53a1b763ba02bfdd0ba708c6e61c182f52533bdf82128dadaf3042c71602de"
sha256 cellar: :any_skip_relocation, big_sur: "2be99be5cca26877dc3db3da3ab6f7da4ac3b89439cf617d653706e6a048a930"
sha256 cellar: :any_skip_relocation, catalina: "0c5ff9bb16df941887019a3053d68505761a6eda839e01ed69c615578b033bec"
sha256 cellar: :any_skip_relocation, mojave: "9592a5b2a438c98103fa5e546ca19fe375887eba1842d0fd5d26734eacab6c1d"
end
depends_on "go" => :build
def install
system "make", "vela-cli", "VELA_VERSION=#{version}"
bin.install "bin/vela"
# Install bash completion
output = Utils.safe_popen_read("#{bin}/vela", "completion", "bash")
(bash_completion/"vela").write output
# Install zsh completion
output = Utils.safe_popen_read("#{bin}/vela", "completion", "zsh")
(zsh_completion/"_vela").write output
end
test do
# Should error out as vela up need kubeconfig
status_output = shell_output("#{bin}/vela up 2>&1", 1)
assert_match "Error: invalid configuration: no configuration has been provided", status_output
end
end
| 39.297297 | 122 | 0.740715 |
bf1bf8a2d152bfb68c126ad8b7461eced29349fa | 1,324 | =begin
The Trust Payments API allows an easy interaction with the Trust Payments web service.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=end
require 'date'
module TrustPayments
class SubscriptionVersionState
PENDING = 'PENDING'.freeze
INITIALIZING = 'INITIALIZING'.freeze
FAILED = 'FAILED'.freeze
ACTIVE = 'ACTIVE'.freeze
TERMINATING = 'TERMINATING'.freeze
TERMINATED = 'TERMINATED'.freeze
# Builds the enum from string
# @param [String] The enum value in the form of the string
# @return [String] The enum value
def build_from_hash(value)
constantValues = SubscriptionVersionState.constants.select { |c| SubscriptionVersionState::const_get(c) == value }
raise "Invalid ENUM value #{value} for class #SubscriptionVersionState" if constantValues.empty?
value
end
end
end
| 33.1 | 120 | 0.750755 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.