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
|
---|---|---|---|---|---|
113e868c578e022d8ac5a884415a191c998754df | 1,616 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/vision/v1p4beta1/geometry.proto
require 'google/api/annotations_pb'
require 'google/protobuf'
Google::Protobuf::DescriptorPool.generated_pool.build do
add_file("google/cloud/vision/v1p4beta1/geometry.proto", :syntax => :proto3) do
add_message "google.cloud.vision.v1p4beta1.Vertex" do
optional :x, :int32, 1
optional :y, :int32, 2
end
add_message "google.cloud.vision.v1p4beta1.NormalizedVertex" do
optional :x, :float, 1
optional :y, :float, 2
end
add_message "google.cloud.vision.v1p4beta1.BoundingPoly" do
repeated :vertices, :message, 1, "google.cloud.vision.v1p4beta1.Vertex"
repeated :normalized_vertices, :message, 2, "google.cloud.vision.v1p4beta1.NormalizedVertex"
end
add_message "google.cloud.vision.v1p4beta1.Position" do
optional :x, :float, 1
optional :y, :float, 2
optional :z, :float, 3
end
end
end
module Google
module Cloud
module Vision
module V1p4beta1
Vertex = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.vision.v1p4beta1.Vertex").msgclass
NormalizedVertex = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.vision.v1p4beta1.NormalizedVertex").msgclass
BoundingPoly = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.vision.v1p4beta1.BoundingPoly").msgclass
Position = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.vision.v1p4beta1.Position").msgclass
end
end
end
end
| 39.414634 | 142 | 0.729579 |
f7971ffe35cab35f3df42c58114b5c550623a2d1 | 665 | # Be sure to restart your server when you modify this file.
# Your secret key is used for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
# You can use `rake secret` to generate a secure secret key.
# Make sure your secret_key_base is kept private
# if you're sharing your code publicly.
Crossfithub::Application.config.secret_key_base = 'f00e876d3cdc1d69d2ba4ce61a54653856f17853c2600fac52982b79c71fcd9575bea74cd7b5d79df1191f7d805639e389a6320a0637aa45c9b6c69998f14cb1'
| 51.153846 | 180 | 0.816541 |
6a4320b6149af7ec116da43e54f9de627ceebe33 | 412 | default['abc-app']['wordpress_url'] = "http://wordpress.org/latest.tar.gz"
default['abc-app']['dependencies'] = ['php5','php5-gd','php5-mysql','libssh2-php', 'apache2', 'libapache2-mod-php5', 'php5-curl']
default['abc-app']['wpconfig'] = {
:db_name => 'wordpress',
:username => 'wordpress',
:password => 'wordpress',
:hostname => 'abc-dev-db.funit.ro'
}
default['abd-app']['hostname'] = 'abc-dev.funit.ro'
| 34.333333 | 129 | 0.648058 |
62f29992effa96c434a9581f63d4e88af769cbc2 | 3,434 | require 'rails_helper'
describe 'Mass messages requests', type: :request, active_job: true do
let(:user) { create :user }
before do
sign_in user
end
describe 'POST#create' do
let!(:client_1) { create :client, user: user }
let!(:client_2) { create :client, user: user }
let!(:client_3) { create :client, user: user }
let(:message_body) { 'hello this is message one' }
let(:clients) { ['', client_1.id, client_3.id] }
before do
post mass_messages_path, params: {
mass_message: {
message: message_body,
clients: clients
}
}
end
it 'sends message to multiple clients' do
expect(ScheduledMessageJob).to have_been_enqueued.twice
expect(user.messages.count).to eq 2
expect(client_1.messages.count).to eq 1
expect(client_1.messages.first.body).to eq message_body
expect(client_2.messages.count).to eq 0
expect(client_3.messages.count).to eq 1
expect(client_3.messages.first.body).to eq message_body
end
it 'sends an analytics event for each message in mass message' do
expect_analytics_events(
'message_send' => {
'mass_message' => true
}
)
expect_analytics_event_sequence(
'login_success',
'message_send',
'message_send',
'mass_message_send'
)
end
it 'sends a single mass_message_send event with recipient_count' do
expect_analytics_events(
'mass_message_send' => {
'recipients_count' => 2
}
)
end
context 'no message body inputted' do
let(:message_body) { '' }
it 're-renders the page with errors' do
expect(response.body).to include 'You need to add a message.'
end
end
context 'no message recipients selected' do
let(:message_body) { '' }
let(:clients) { [''] }
it 're-renders the page with errors' do
expect(response.body).to include 'You need to pick at least one recipient.'
end
end
end
describe 'GET#new' do
let(:params) { nil }
before do
create_list :client, 3, user: user
end
subject { get new_mass_message_path, params: params }
it 'tracks a visit to the new mass message page' do
subject
expect(response.code).to eq '200'
expect_analytics_events(
'mass_message_compose_view' => {
'clients_count' => 3
}
)
end
context 'using a url to pre-populate' do
let(:params) { {clients: [user.clients[0].id, user.clients[2].id]} }
it 'renders checkboxes selected correctly' do
subject
clients = user.clients
expect(response.body).to include("value=\"#{clients[0].id}\" checked=\"checked\"")
expect(response.body).to include("value=\"#{clients[2].id}\" checked=\"checked\"")
expect(response.body).to include("value=\"#{clients[1].id}\" name")
end
end
context 'client status feature flag enabled' do
let(:status) { create :client_status }
before do
FeatureFlag.create!(flag: 'client_status', enabled: true)
end
it 'renders client list with status column' do
create :client, client_status: status, user: user
get new_mass_message_path
expect(response.body).to include 'Status'
expect(response.body).to include status.name
end
end
end
end
| 26.415385 | 90 | 0.619103 |
b9d17b14c33f939826fc3de84d6df50ceb66521a | 478 | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe Member::DisabledNotificationMailer, type: :mailer do
describe '#notify' do
subject { Member::DisabledNotificationMailer.notify(user.id) }
let(:user) { create(:user) }
its(:subject) { is_expected.to eq I18n.t('dashboard.users.mailers.disabled.subject') }
its(:to) { is_expected.to eq [user.email] }
its(:from) { is_expected.to eq [Settings.notifications.email.default_from] }
end
end
| 31.866667 | 90 | 0.723849 |
4a617e663bdd4feeb8dc6baef768bc66a75a0b56 | 104 | class PUBError < StandardError
def initialize(msg="Opps something happened")
super(msg)
end
end
| 17.333333 | 47 | 0.740385 |
ff686e9b7ae86568096313a2f10842bcda1cf1d8 | 1,192 | require "map"
class MVCLI::Argv
attr_reader :arguments, :options
def initialize(argv, switches = [])
@switches = switches.map(&:to_s)
@arguments, @options = scan argv
end
def scan(argv, arguments = [], options = Map.new)
current, *rest = argv
case current
when nil
[arguments, options]
when /^--(\w[[:graph:]]+)=([[:graph:]]+)$/
scan rest, arguments, merge(options, $1, $2)
when /^--no-(\w[[:graph:]]+)$/
scan rest, arguments, merge(options, $1, false)
when /^--(\w[[:graph:]]+)$/, /^-(\w)$/
key = underscore $1
if switch? key
scan rest, arguments, merge(options, key, true)
elsif rest.first =~ /^-/
scan rest, arguments, merge(options, key)
else
value, *rest = rest
scan rest, arguments, merge(options, key, value)
end
else
scan rest, arguments + [current], options
end
end
def switch?(key)
@switches.member? underscore key
end
def merge(options, key, value = nil)
key = underscore key
values = options[key] || []
options.merge(key => values + [value].compact)
end
def underscore(string)
string.gsub('-','_')
end
end
| 24.326531 | 56 | 0.57802 |
ff64fcf73c8f7128ecd7dcbdd8bc432c8523d111 | 312 | require 'spec_helper'
describe Spree::Api::V2::Platform::StateChangeSerializer do
include_context 'API v2 serializers params'
subject { described_class.new(resource, params: serializer_params) }
let(:resource) { create(:state_change) }
it { expect(subject.serializable_hash).to be_kind_of(Hash) }
end | 28.363636 | 70 | 0.769231 |
b94b351a1d7ad9b668a8891c76c23478454b8447 | 1,391 | #
# Copyright:: Copyright (c) 2015 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# 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.
#
class Chef
class Provider
class DeliveryInspec < Chef::Provider
attr_reader :inspec
def load_current_resource
# There is no existing resource to evaluate, but we are required
# to override it.
end
def initialize(new_resource, run_context)
super
@inspec = DeliverySugar::Inspec.new(
new_resource.repo_path,
run_context,
os: new_resource.os,
infra_node: new_resource.infra_node,
inspec_test_path: new_resource.inspec_test_path
)
end
action :test do
converge_by 'Run inspec tests' do
@inspec.run_inspec
new_resource.updated_by_last_action(true)
end
end
end
end
end
| 28.387755 | 74 | 0.680805 |
878f778bbf17dd80a2dbe1e337ce605f7a7107e5 | 1,524 | Sequel.require 'adapters/shared/mysql'
module Sequel
module DataObjects
# Database and Dataset instance methods for MySQL specific
# support via DataObjects.
module MySQL
# Database instance methods for MySQL databases accessed via DataObjects.
module DatabaseMethods
include Sequel::MySQL::DatabaseMethods
# Return instance of Sequel::DataObjects::MySQL::Dataset with the given opts.
def dataset(opts=nil)
Sequel::DataObjects::MySQL::Dataset.new(self, opts)
end
private
# The database name for the given database. Need to parse it out
# of the connection string, since the DataObjects does no parsing on the
# given connection string by default.
def database_name
(m = /\/(.*)/.match(URI.parse(uri).path)) && m[1]
end
def schema_column_type(db_type)
db_type == 'tinyint(1)' ? :boolean : super
end
end
# Dataset class for MySQL datasets accessed via DataObjects.
class Dataset < DataObjects::Dataset
include Sequel::MySQL::DatasetMethods
# Use execute_insert to execute the replace_sql.
def replace(*args)
execute_insert(replace_sql(*args))
end
private
# do_mysql sets NO_BACKSLASH_ESCAPES, so use standard SQL string escaping
def literal_string(s)
"'#{s.gsub("'", "''")}'"
end
end
end
end
end
| 30.48 | 85 | 0.611549 |
e979c6627e808a7f4a9a8612763cc773f7c7e104 | 1,645 | require 'bibtex'
require 'citeproc'
require 'csl/styles'
module Jekyll
class PublicationIndexGenerator < Generator
priority :high
def generate(site)
config = site.config['publication_index'] || {}
publication_index = PublicationIndex.new(site, site.source, './', config['target'])
site.pages << publication_index
end
end
class PublicationIndex < Page
def initialize(site, base, dir, name)
@site = site
@base = base
@dir = dir
@config = site.config['publication_index'] || {}
@name = "#{name.to_s.gsub(/[:\s]+/, '_')}.html"
process(@name)
read_yaml(File.join(base, '_layouts'), "#{@config['layout']}.html")
@cp = CiteProc::Processor.new style: 'apa', format: 'html'
@cp.import BibTeX.open(@config['source']).to_citeproc
@data['publications_by_year'] = publications_by_year
end
def years
hash = Hash.new { |h, key| h[key] = [] }
@cp.items.values.each { |e| hash[e.issued.year.to_s] << e }
hash.values.each do |ps|
ps.sort! { |a, b| a.issued.mon.to_i <=> b.issued.mon.to_i }.reverse!
end
hash
end
def publication(id)
content = @cp.render(:bibliography, id: id).first
content.
gsub(/[{}]/, '').
gsub(/(De Jay, N\.)/, '<strong>\1</strong>').
gsub(/\.\./, '.')
end
def publications_by_year
years.map do |year, pubs|
{
'name' => year,
'publications' => pubs.map { |p| publication(p.id) },
'publication_count' => pubs.length,
}
end
end
end
end
| 23.169014 | 89 | 0.555623 |
87139371b8ff7f01ffcbf5c38cbae41f21db0dcb | 234 | class ChangeWikipediaSummaryColumnOnProtectedArea < ActiveRecord::Migration
def change
rename_column :protected_areas, :wikipedia_summary_id, :wikipedia_article_id
add_index :protected_areas, :wikipedia_article_id
end
end
| 33.428571 | 80 | 0.837607 |
ace3cb3ff478dc0a82a13caf1d9d3efad752be30 | 681 | require File.expand_path("../lib/pakiderm/version", __FILE__)
Gem::Specification.new do |s|
s.name = "pakiderm"
s.version = Pakiderm::VERSION
s.authors = ["Máximo Mussini"]
s.email = ["[email protected]"]
s.summary = "Pakiderm will never forget the return value."
s.description = "Pakiderm is a simple module that encapsulates a modern memoization technique."
s.homepage = "https://github.com/ElMassimo/pakiderm"
s.license = "MIT"
s.extra_rdoc_files = ["README.md"]
s.files = Dir.glob("{lib}/**/*.rb") + %w(README.md CHANGELOG.md)
s.require_path = "lib"
s.required_ruby_version = ">= 2.0"
s.add_development_dependency "rspec-given", "~> 3.0"
end
| 34.05 | 97 | 0.694567 |
b944a4050e3fa217b9bfb22b0929d5308fc8dbaf | 426 | FactoryBot.define do
factory :gws_column_check_box, class: Gws::Column::CheckBox do
cur_site { gws_site }
name { "name-#{unique_id}" }
order { rand(999) }
required { %w(required optional).sample }
tooltips { "tooltips-#{unique_id}" }
prefix_label { "prefix_label-#{unique_id}" }
postfix_label { "postfix_label-#{unique_id}" }
select_options { Array.new(rand(1..5)) { unique_id } }
end
end
| 30.428571 | 64 | 0.659624 |
6a05fef687d10b907a962958d4c7d2abdbd04bdc | 705 | Pod::Spec.new do |s|
s.name = "MisskeyKit"
s.version = "3.0.1"
s.summary = "An elegant Misskey framework written in Swift."
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.homepage = "https://github.com/yuigawada/MisskeyKit-for-iOS"
s.author = { "YuigaWada" => "[email protected]" }
s.source = { :git => "https://github.com/yuigawada/MisskeyKit-for-iOS.git", :tag => "#{s.version}" }
s.dependency 'Starscream','3.1.1'
s.pod_target_xcconfig = { 'OTHER_LDFLAGS' => '-weak_framework CryptoKit' }
s.platform = :ios, "11.0"
s.requires_arc = true
s.source_files = 'MisskeyKit/**/*.{swift,h}'
s.resources = 'MisskeyKit/**/*.{json}'
s.swift_version = "5.0"
end | 44.0625 | 106 | 0.624113 |
e98f52100e0510fbc40c8e3c7d948feeeb43cc7c | 129 | name "os-base"
description "OpenStack Base role"
run_list(
"recipe[openstack-common]",
"recipe[openstack-common::logging]"
)
| 18.428571 | 37 | 0.736434 |
114ff3cdd241aae1d732827c95856222bce59e1f | 319 | class Theremin < Cask
version '0.7'
sha256 '809d0f7527d072a43f33b9e1088dc2387e08bb1a3696bb60bfd8e82b8853102d'
url 'http://f.nn.lv/ms/l5/29/Theremin.app.zip'
appcast 'http://theremin.amd.co.at/appcastProfileInfo.php'
homepage 'https://github.com/TheStalwart/Theremin'
license :oss
app 'Theremin.app'
end
| 26.583333 | 75 | 0.761755 |
e9c32ec7984e4709f982024ec3350b048fae9616 | 3,486 | # Copyright (C) 2015-2017 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module Mongo
class BulkWrite
# Combines bulk write results together.
#
# @api private
#
# @since 2.1.0
class ResultCombiner
# @return [ Integer ] count The count of documents in the entire batch.
attr_reader :count
# @return [ Hash ] results The results hash.
attr_reader :results
# Create the new result combiner.
#
# @api private
#
# @example Create the result combiner.
# ResultCombiner.new
#
# @since 2.1.0
def initialize
@results = {}
@count = 0
end
# Combines a result into the overall results.
#
# @api private
#
# @example Combine the result.
# combiner.combine!(result, count)
#
# @param [ Operation::Result ] result The result to combine.
# @param [ Integer ] count The count of requests in the batch.
#
# @since 2.1.0
def combine!(result, count)
combine_counts!(result)
combine_ids!(result)
combine_errors!(result)
@count += count
end
# Get the final result.
#
# @api private
#
# @example Get the final result.
# combinator.result
#
# @return [ BulkWrite::Result ] The final result.
#
# @since 2.1.0
def result
BulkWrite::Result.new(results).validate!
end
private
def combine_counts!(result)
Result::FIELDS.each do |field|
if result.respond_to?(field) && value = result.send(field)
results.merge!(field => (results[field] || 0) + value)
end
end
end
def combine_ids!(result)
if result.respond_to?(Result::INSERTED_IDS)
results[Result::INSERTED_IDS] = (results[Result::INSERTED_IDS] || []) +
result.inserted_ids
end
if result.respond_to?(Result::UPSERTED)
results[Result::UPSERTED_IDS] = (results[Result::UPSERTED_IDS] || []) +
result.upserted.map{ |doc| doc['_id'] }
end
end
def combine_errors!(result)
combine_write_errors!(result)
combine_write_concern_errors!(result)
end
def combine_write_errors!(result)
if write_errors = result.aggregate_write_errors(count)
results.merge!(
Error::WRITE_ERRORS => ((results[Error::WRITE_ERRORS] || []) << write_errors).flatten
)
else
result.validate!
end
end
def combine_write_concern_errors!(result)
if write_concern_errors = result.aggregate_write_concern_errors(count)
results[Error::WRITE_CONCERN_ERRORS] = (results[Error::WRITE_CONCERN_ERRORS] || []) +
write_concern_errors
end
end
end
end
end
| 28.809917 | 97 | 0.58864 |
bbd00e6315b0732ae894da0a31a863bc01709ca9 | 2,441 | Knock.setup do |config|
## User handle attribute
## ---------------------
##
## The attribute used to uniquely identify a user.
##
## Default:
# config.handle_attr = :email
## Current user retrieval from handle when signing in
## --------------------------------------------------
##
## This is where you can configure how to retrieve the current user when
## signing in.
##
## Knock uses the `handle_attr` variable to retrieve the handle from the
## AuthTokenController parameters. It also uses the same variable to enforce
## permitted values in the controller.
##
## You must raise ActiveRecord::RecordNotFound if the resource cannot be retrieved.
##
## Default:
# config.current_user_from_handle = -> (handle) { User.find_by! Knock.handle_attr => handle }
## Current user retrieval when validating token
## --------------------------------------------
##
## This is how you can tell Knock how to retrieve the current_user.
## By default, it assumes you have a model called `User` and that
## the user_id is stored in the 'sub' claim.
##
## You must raise ActiveRecord::RecordNotFound if the resource cannot be retrieved.
##
## Default:
# config.current_user_from_token = -> (claims) { User.find claims['sub'] }
## Expiration claim
## ----------------
##
## How long before a token is expired.
##
## Default:
# config.token_lifetime = 1.day
## Audience claim
## --------------
##
## Configure the audience claim to identify the recipients that the token
## is intended for.
##
## Default:
# config.token_audience = nil
## If using Auth0, uncomment the line below
# config.token_audience = -> { Rails.application.secrets.auth0_client_id }
## Signature algorithm
## -------------------
##
## Configure the algorithm used to encode the token
##
## Default:
# config.token_signature_algorithm = 'HS256'
## Signature key
## -------------
##
## Configure the key used to sign tokens.
##
## Default:
# config.token_secret_signature_key = -> { Rails.application.secrets.secret_key_base }
## If using Auth0, uncomment the line below
# config.token_secret_signature_key = -> { JWT.base64url_decode Rails.application.secrets.auth0_client_secret }
## Public key
## ----------
##
## Configure the public key used to decode tokens, if required.
##
## Default:
# config.token_public_key = nil
end
| 28.057471 | 113 | 0.625563 |
21f2a41602e3e721cd97a3649b31d8387ebe9157 | 1,141 | # frozen_string_literal: true
NUMERALS = %w[M D C L X V I].freeze
VALUES = [1_000, 500, 100, 50, 10, 5, 1].freeze
def numeralize(num)
result = ''
VALUES.each_with_index do |val, index|
next unless (num / val).positive?
dividend = num / val
num = num % val
result += assign_numeral(dividend, index)
end
result = simplify(result)
result
end
def assign_numeral(dividend, index)
character = NUMERALS[index]
numeral = character * dividend
# Brute force method
# if %w[I X C].include?(character) && dividend == 4
# result = character + NUMERALS[index - 1]
# end
numeral
end
def simplify(string)
# 99: should be 'XCIX', by default is 'LXXXXVIIII'
array = string.split('')
new_array = []
array.each_with_index do |numeral, index|
if numeral == array[index + 1] && numeral == array[index + 2] && numeral == array[index + 3]
# we are dealing with a four. Are we dealing with a nine?
new_array.push("yay")
else
new_array.push(numeral)
end
end
new_array.join
end
print 'Enter some number: '
num = gets.to_i
puts "#{num} converts to #{numeralize(num)}"
| 21.12963 | 96 | 0.646801 |
4a1cc284cf4b70d03823c2218574f0e8c8a86050 | 1,333 | # 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/servicebroker_v1beta1/service.rb'
require 'google/apis/servicebroker_v1beta1/classes.rb'
require 'google/apis/servicebroker_v1beta1/representations.rb'
module Google
module Apis
# Service Broker API
#
# The Google Cloud Platform Service Broker API provides Google hosted
# implementation of the Open Service Broker API
# (https://www.openservicebrokerapi.org/).
#
# @see https://cloud.google.com/kubernetes-engine/docs/concepts/add-on/service-broker
module ServicebrokerV1beta1
VERSION = 'V1beta1'
REVISION = '20180521'
# View and manage your data across Google Cloud Platform services
AUTH_CLOUD_PLATFORM = 'https://www.googleapis.com/auth/cloud-platform'
end
end
end
| 36.027027 | 89 | 0.747937 |
265a8e2801b9d33ef8c2794b1fbed5058981c56a | 468 | test_name "Reboot Module - POSIX Provider - No Refresh"
extend Puppet::Acceptance::Reboot
reboot_manifest = <<-MANIFEST
reboot { 'now':
}
MANIFEST
confine :except, :platform => 'windows'
posix_agents.each do |agent|
step "Attempt to Reboot Computer without Refresh"
#Apply the manifest.
apply_manifest_on agent, reboot_manifest
#Verify that a shutdown has NOT been initiated because reboot
#was not refreshed.
ensure_shutdown_not_scheduled(agent)
end
| 22.285714 | 63 | 0.767094 |
917b72a199699989919c5ed51e4e179df9bab069 | 231 | class CreateEntries < ActiveRecord::Migration[6.0]
def change
create_table :entries do |t|
t.datetime :date
t.text :content
t.integer :user_id
t.integer :topic_id
t.timestamps
end
end
end
| 17.769231 | 50 | 0.640693 |
abb3e2575dd3280d83a810a9f1ab02e7768bd477 | 4,329 | # encoding: UTF-8
#
# Copyright (c) 2010-2017 GoodData Corporation. All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
require_relative 'base_action'
module GoodData
module LCM2
class CollectDymanicScheduleParams < BaseAction
DESCRIPTION = 'Collect Dynamic Schedule Params'
PARAMS = define_params(self) do
description 'Schedule Title Column'
param :schedule_title_column, instance_of(Type::StringType), required: false
description 'Dynamic Params'
param :dynamic_params, instance_of(Type::HashType), required: false
description 'Client Id Column'
param :client_id_column, instance_of(Type::StringType), required: false
description 'Name Column'
param :param_name_column, instance_of(Type::StringType), required: false
description 'Value Column'
param :param_value_column, instance_of(Type::StringType), required: false
description 'Should the param be hidden?'
param :param_secure_column, instance_of(Type::StringType), required: false
description 'Dynamic params encryption key'
param :dynamic_params_encryption_key, instance_of(Type::StringType), required: false
end
class << self
def call(params)
return [] unless params.dynamic_params
schedule_title_column = params.schedule_title_column&.downcase || 'schedule_title'
client_id_column = params.client_id_column&.downcase || 'client_id'
param_name_column = params.param_name_column&.downcase || 'param_name'
param_value_column = params.param_value_column&.downcase || 'param_value'
param_secure_column = params.param_secure_column&.downcase || 'param_secure'
encryption_key = params.dynamic_params_encryption_key || ''
exist_encryption_key = encryption_key.blank? ? false : true
results = []
input_source = params.dynamic_params.input_source
data_source = GoodData::Helpers::DataSource.new(input_source)
input_data = without_check(PARAMS, params) do
File.open(data_source.realize(params), 'r:UTF-8')
end
schedule_params = {}
schedule_hidden_params = {}
exist_param_secure = false
CSV.foreach(input_data, :headers => true, :return_headers => false, :header_converters => :downcase, :encoding => 'utf-8') do |row|
is_param_secure = row[param_secure_column] == 'true'
is_decrypt_secure_value = is_param_secure && exist_encryption_key ? true : false
exist_param_secure = true if is_param_secure
safe_to_print_row = row.to_hash
safe_to_print_row[param_value_column] = '******' if is_param_secure
GoodData.logger.debug("Processing row: #{safe_to_print_row}")
results << safe_to_print_row
client_id_column_value = row[client_id_column]
client_id = client_id_column_value.blank? ? :all_clients : client_id_column_value
schedule_title_column_value = row[schedule_title_column]
schedule_name = schedule_title_column_value.blank? ? :all_schedules : schedule_title_column_value
param_name = row[param_name_column]
param_value = row[param_value_column]
param_value = GoodData::Helpers.simple_decrypt(param_value, encryption_key) if is_decrypt_secure_value
add_dynamic_param(is_param_secure ? schedule_hidden_params : schedule_params, client_id, schedule_name, param_name, param_value)
end
GoodData.logger.warn("dynamic_params_encryption_key parameter doesn't exist") if exist_param_secure && !exist_encryption_key
{
results: results,
params: {
schedule_params: schedule_params,
schedule_hidden_params: schedule_hidden_params
}
}
end
private
def add_dynamic_param(params, client_id, schedule_name, param_name, param_value)
params[client_id] ||= {}
params[client_id][schedule_name] ||= {}
params[client_id][schedule_name].merge!(param_name => param_value)
end
end
end
end
end
| 40.457944 | 141 | 0.680989 |
ff762ab0cd81d617d4ae979425a04db9e946e221 | 175 | RSpec.describe Peekj do
it "has a version number" do
expect(Peekj::VERSION).not_to be nil
end
it "does something useful" do
expect(false).to eq(true)
end
end
| 17.5 | 40 | 0.691429 |
f832c01666ffe024daf0f10d0df540415ea8a74c | 3,877 | module Utilities
module Import
module Demo
class NodeData
include Utilities::Import::Data
COLLAPSED_NODE_TYPES = %w(section dep)
attr_reader :title, :node_type
attr_reader :lunch
attr_accessor :unit_external_id, :employment_external_id
attr_accessor :parent_node_external_id, :head_external_id
attr_reader :child_node_external_ids
attr_reader :child_employment_external_ids
def initialize(encapsulated_data, hash)
@external_id = encapsulated_data.external_id
@node_type = hash['node_type']
if (lunch_time = hash['lunch']).present?
hours, minutes = *lunch_time.split(':')
lunch_end = (hours.to_i + 1).to_s + ':' + minutes
@lunch = lunch_time .. lunch_end
end
case encapsulated_data
when Utilities::Import::Demo::UnitData
@title = encapsulated_data.short_title || encapsulated_data.long_title
when Utilities::Import::Demo::EmploymentTemplateData
@title = encapsulated_data.post_title
end
@child_node_external_ids = []
@child_employment_external_ids = []
end
def attributes
{
external_id: external_id,
title: title,
node_type: node_type,
default_expanded: !node_type.in?(COLLAPSED_NODE_TYPES)
}
end
def add_node_employment_data(employment_data)
@employment_external_id = employment_data.external_id
employment_data.node_external_id = @external_id
end
def add_node_unit_data(unit_data)
@unit_external_id = unit_data.external_id
unit_data.node_external_id = @external_id
end
def add_child_node_data(child_node_data)
# m = 'BROKEN ID HIERARCHY' unless proper_child_id?(child_node_data)
# puts " add #{ child_node_data.external_id } to #{ external_id } #{ m }"
@child_node_external_ids << child_node_data.external_id
child_node_data.parent_node_external_id = @external_id
end
def add_child_employment_data(employment_node_data)
@child_employment_external_ids << employment_node_data.external_id
employment_node_data.parent_node_external_id = @external_id
end
def proper_child_id?(child_node_data)
external_id.size + 1 == child_node_data.external_id.size and
child_node_data.external_id.start_with?(external_id)
end
def assign_head_id(unit_collection)
if @unit_external_id.present?
unit_entity = unit_collection[@unit_external_id]
if unit_entity.present?
unit_entity.new_data.head_external_id = @head_external_id
end
end
end
def assign_lunch_time_recursively(node_collection, default_lunch_time = '13:00' .. '14:00')
@lunch ||= default_lunch_time
@child_node_external_ids.each do |child_id|
child_node_data = node_collection[child_id].new_data
child_node_data.assign_lunch_time_recursively(node_collection, @lunch)
end
end
def assign_lunch_to_employments(employment_collection)
if (employment = employment_collection[@employment_external_id]&.new_data).present?
employment.lunch = @lunch
end
@child_employment_external_ids.each do |employment_id|
if (employment = employment_collection[employment_id]&.new_data).present?
employment.lunch = @lunch
end
end
end
def inspect
"NodeData #{ @variant } #{ @external_id } <#{ child_node_external_ids.join(', ') }> '#{ title }'"
end
end
end
end
end
| 32.041322 | 107 | 0.634769 |
28a56bd47ac026858de2d7192ebc2e3e6c53e457 | 3,783 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Attempt to read encrypted secrets from `config/secrets.yml.enc`.
# Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or
# `config/secrets.yml.key`.
config.read_encrypted_secrets = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "ellis_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
| 41.119565 | 102 | 0.756807 |
7a31558ad78088991ef06c5f9ad0bd9b0327f62e | 11,550 | # -*- coding: utf-8 -*-
require File.join(File.dirname(__FILE__), 'helper')
class GoogleGeocoderTest < BaseGeocoderTest #:nodoc: all
def setup
super
@full_address = '100 Spear St Apt. 5, San Francisco, CA, 94105-1522, US'
@full_address_short_zip = '100 Spear St Apt. 5, San Francisco, CA, 94105, US'
@google_full_hash = {:street_address=>"100 Spear St Apt. 5", :city=>"San Francisco", :state=>"CA", :zip=>"94105", :country_code=>"US"}
@google_city_hash = {:city=>"San Francisco", :state=>"CA"}
@google_full_loc = Geokit::GeoLoc.new(@google_full_hash)
@google_city_loc = Geokit::GeoLoc.new(@google_city_hash)
end
# Example from:
# https://developers.google.com/maps/documentation/business/webservices#signature_examples
def test_google_signature
cryptographic_key = 'vNIXE0xscrmjlyV-12Nj_BvUPaw='
query_string = '/maps/api/geocode/json?address=New+York&sensor=false&client=clientID'
signature = Geokit::Geocoders::GoogleGeocoder.send(:sign_gmap_bus_api_url, query_string, cryptographic_key)
assert_equal 'KrU1TzVQM7Ur0i8i7K3huiw3MsA=', signature
end
# Example from:
# https://developers.google.com/maps/documentation/business/webservices#signature_examples
def test_google_signature_and_url
Geokit::Geocoders::GoogleGeocoder.client_id = 'clientID'
Geokit::Geocoders::GoogleGeocoder.cryptographic_key = 'vNIXE0xscrmjlyV-12Nj_BvUPaw='
url = Geokit::Geocoders::GoogleGeocoder.send(:submit_url, 'address=New+York')
Geokit::Geocoders::GoogleGeocoder.client_id = nil
Geokit::Geocoders::GoogleGeocoder.cryptographic_key = nil
assert_equal 'https://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=New+York&client=clientID&signature=9mevp7SoVsSKzF9nj-vApMYbatg=', url
end
def test_google_api_key
Geokit::Geocoders::GoogleGeocoder.api_key = 'someKey'
url = Geokit::Geocoders::GoogleGeocoder.send(:submit_url, 'address=New+York')
Geokit::Geocoders::GoogleGeocoder.api_key = nil
assert_equal 'https://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=New+York&key=someKey', url
end
def test_google_insecure_url
Geokit::Geocoders.secure = false
url = Geokit::Geocoders::GoogleGeocoder.send(:submit_url, 'address=New+York')
Geokit::Geocoders.secure = true
assert_equal 'http://maps.google.com/maps/api/geocode/json?sensor=false&address=New+York', url
end
def test_google_full_address
VCR.use_cassette('google_full_short') do
url = "https://maps.google.com/maps/api/geocode/json?sensor=false&address=#{Geokit::Inflector::url_escape(@address)}"
TestHelper.expects(:last_url).with(url)
res=Geokit::Geocoders::GoogleGeocoder.geocode(@address)
assert_equal "CA", res.state
assert_equal "San Francisco", res.city
assert_array_in_delta [37.7749295, -122.4194155], res.to_a # slightly dif from yahoo
assert res.is_us?
assert_equal "San Francisco, CA, USA", res.full_address #slightly different from yahoo
assert_equal "google", res.provider
end
end
def test_google_full_address_with_geo_loc
VCR.use_cassette('google_full') do
url = "https://maps.google.com/maps/api/geocode/json?sensor=false&address=#{Geokit::Inflector::url_escape(@full_address_short_zip)}"
TestHelper.expects(:last_url).with(url)
res=Geokit::Geocoders::GoogleGeocoder.geocode(@google_full_loc)
assert_equal "CA", res.state
assert_equal "San Francisco", res.city
assert_array_in_delta [37.7921509, -122.394], res.to_a # slightly dif from yahoo
assert res.is_us?
assert_equal "100 Spear Street #5, San Francisco, CA 94105, USA", res.full_address #slightly different from yahoo
assert_equal "google", res.provider
end
end
def test_google_full_address_accuracy
VCR.use_cassette('google_full') do
url = "https://maps.google.com/maps/api/geocode/json?sensor=false&address=#{Geokit::Inflector::url_escape(@full_address_short_zip)}"
TestHelper.expects(:last_url).with(url)
res=Geokit::Geocoders::GoogleGeocoder.geocode(@google_full_loc)
assert_equal 9, res.accuracy
end
end
def test_google_city
VCR.use_cassette('google_city') do
url = "https://maps.google.com/maps/api/geocode/json?sensor=false&address=#{Geokit::Inflector::url_escape(@address)}"
TestHelper.expects(:last_url).with(url)
res=Geokit::Geocoders::GoogleGeocoder.do_geocode(@address)
assert_nil res.street_address
assert_equal "CA", res.state
assert_equal "San Francisco", res.city
assert_equal "37.7749295,-122.4194155", res.ll
assert res.is_us?
assert_equal "San Francisco, CA, USA", res.full_address
assert_equal "google", res.provider
end
end
def test_google_city_accuracy
VCR.use_cassette('google_city') do
url = "https://maps.google.com/maps/api/geocode/json?sensor=false&address=#{Geokit::Inflector::url_escape(@address)}"
TestHelper.expects(:last_url).with(url)
res=Geokit::Geocoders::GoogleGeocoder.geocode(@address)
assert_equal 4, res.accuracy
end
end
def test_google_city_with_geo_loc
VCR.use_cassette('google_city') do
url = "https://maps.google.com/maps/api/geocode/json?sensor=false&address=#{Geokit::Inflector::url_escape(@address)}"
TestHelper.expects(:last_url).with(url)
res=Geokit::Geocoders::GoogleGeocoder.geocode(@google_city_loc)
assert_equal "CA", res.state
assert_equal "San Francisco", res.city
assert_equal "37.7749295,-122.4194155", res.ll
assert res.is_us?
assert_equal "San Francisco, CA, USA", res.full_address
assert_nil res.street_address
assert_equal "google", res.provider
end
end
def test_google_suggested_bounds
VCR.use_cassette('google_full') do
url = "https://maps.google.com/maps/api/geocode/json?sensor=false&address=#{Geokit::Inflector::url_escape(@full_address_short_zip)}"
TestHelper.expects(:last_url).with(url)
res = Geokit::Geocoders::GoogleGeocoder.geocode(@google_full_loc)
assert_instance_of Geokit::Bounds, res.suggested_bounds
assert_array_in_delta [37.7908019197085, -122.3953489802915], res.suggested_bounds.sw.to_a
assert_array_in_delta [37.7934998802915, -122.3926510197085], res.suggested_bounds.ne.to_a
end
end
def test_google_suggested_bounds_url
bounds = Geokit::Bounds.new(
Geokit::LatLng.new(33.7036917, -118.6681759),
Geokit::LatLng.new(34.3373061, -118.1552891)
)
url = "https://maps.google.com/maps/api/geocode/json?sensor=false&address=Winnetka&bounds=33.7036917%2C-118.6681759%7C34.3373061%2C-118.1552891"
Geokit::Geocoders::GoogleGeocoder.expects(:call_geocoder_service).with(url)
Geokit::Geocoders::GoogleGeocoder.geocode('Winnetka', :bias => bounds)
end
def test_service_unavailable
response = MockFailure.new
url = "https://maps.google.com/maps/api/geocode/json?sensor=false&address=#{Geokit::Inflector::url_escape(@address)}"
Geokit::Geocoders::GoogleGeocoder.expects(:call_geocoder_service).with(url).returns(response)
assert !Geokit::Geocoders::GoogleGeocoder.geocode(@google_city_loc).success
end
def test_multiple_results
VCR.use_cassette('google_multi') do
url = "https://maps.google.com/maps/api/geocode/json?sensor=false&address=#{Geokit::Inflector.url_escape('via Sandro Pertini 8, Ossona, MI')}"
TestHelper.expects(:last_url).with(url)
res=Geokit::Geocoders::GoogleGeocoder.geocode('via Sandro Pertini 8, Ossona, MI')
assert_equal 5, res.all.size
res = res.all[0]
assert_equal "Lombardy", res.state
assert_equal "Mesero", res.city
assert_array_in_delta [45.4966218, 8.852694], res.to_a
assert !res.is_us?
assert_equal "Via Sandro Pertini, 8, 20010 Mesero Milan, Italy", res.full_address
assert_equal "8 Via Sandro Pertini", res.street_address
assert_equal "google", res.provider
res = res.all[4]
assert_equal "Lombardy", res.state
assert_equal "Ossona", res.city
assert_array_in_delta [45.5074444, 8.90232], res.to_a
assert !res.is_us?
assert_equal "Via S. Pertini, 20010 Ossona Milan, Italy", res.full_address
assert_equal "Via S. Pertini", res.street_address
assert_equal "google", res.provider
end
end
#
def test_reverse_geocode
VCR.use_cassette('google_reverse_madrid') do
madrid = Geokit::GeoLoc.new
madrid.lat, madrid.lng = "40.4167413", "-3.7032498"
url = "https://maps.google.com/maps/api/geocode/json?sensor=false&latlng=#{Geokit::Inflector::url_escape(madrid.ll)}"
TestHelper.expects(:last_url).with(url)
res=Geokit::Geocoders::GoogleGeocoder.do_reverse_geocode(madrid.ll)
assert_equal madrid.lat.to_s.slice(1..5), res.lat.to_s.slice(1..5)
assert_equal madrid.lng.to_s.slice(1..5), res.lng.to_s.slice(1..5)
assert_equal "ES", res.country_code
assert_equal "google", res.provider
assert_equal "Madrid", res.city
assert_equal "Community of Madrid", res.state
assert_equal "Spain", res.country
assert_equal "28013", res.zip
assert_equal true, res.success
end
end
def test_reverse_geocode_language
VCR.use_cassette('google_reverse_madrid_es') do
url = "https://maps.google.com/maps/api/geocode/json?sensor=false&latlng=40.416%2C-3.703&language=es"
TestHelper.expects(:last_url).with(url)
language_result = Geokit::Geocoders::GoogleGeocoder.reverse_geocode('40.416,-3.703', :language => 'es')
assert_equal 'ES', language_result.country_code
assert_equal 'Madrid', language_result.city
end
end
def test_country_code_biasing
VCR.use_cassette('google_country_code_biased_result') do
url = "https://maps.google.com/maps/api/geocode/json?sensor=false&address=Syracuse®ion=it"
TestHelper.expects(:last_url).with(url)
biased_result = Geokit::Geocoders::GoogleGeocoder.geocode('Syracuse', :bias => 'it')
assert_equal 'IT', biased_result.country_code
assert_equal 'Sicilia', biased_result.state
end
end
def test_language_response
VCR.use_cassette('google_language_response_fr') do
url = "https://maps.google.com/maps/api/geocode/json?sensor=false&address=Hanoi&language=FR"
TestHelper.expects(:last_url).with(url)
language_result = Geokit::Geocoders::GoogleGeocoder.geocode('Hanoi', :language => 'FR')
assert_equal 'VN', language_result.country_code
assert_equal 'Hanoï', language_result.city
end
end
def test_too_many_queries
response = MockSuccess.new
response.expects(:body).returns %q/{"status": "OVER_QUERY_LIMIT"}/
url = "https://maps.google.com/maps/api/geocode/json?sensor=false&address=#{Geokit::Inflector.url_escape(@address)}"
Geokit::Geocoders::GoogleGeocoder.expects(:call_geocoder_service).with(url).returns(response)
assert_raise Geokit::Geocoders::TooManyQueriesError do
res=Geokit::Geocoders::GoogleGeocoder.geocode(@address)
end
end
def test_invalid_request
response = MockSuccess.new
response.expects(:body).returns %q/{"results" : [], "status" : "INVALID_REQUEST"}/
url = "https://maps.google.com/maps/api/geocode/json?sensor=false&address=#{Geokit::Inflector.url_escape("3961 V\u00EDa Marisol")}"
Geokit::Geocoders::GoogleGeocoder.expects(:call_geocoder_service).with(url).returns(response)
assert_raise Geokit::Geocoders::GeocodeError do
Geokit::Geocoders::GoogleGeocoder.geocode("3961 V\u00EDa Marisol")
end
end
end
| 44.594595 | 158 | 0.729177 |
116d1fb233d57c08636bc0b4f5a217c040c33391 | 4,037 | # frozen_string_literal: true
require 'uri'
module Integrations
class Irker < Integration
prop_accessor :server_host, :server_port, :default_irc_uri
prop_accessor :recipients, :channels
boolean_accessor :colorize_messages
validates :recipients, presence: true, if: :validate_recipients?
before_validation :get_channels
def title
s_('IrkerService|irker (IRC gateway)')
end
def description
s_('IrkerService|Send update messages to an irker server.')
end
def self.to_param
'irker'
end
def self.supported_events
%w(push)
end
def execute(data)
return unless supported_events.include?(data[:object_kind])
IrkerWorker.perform_async(project_id, channels,
colorize_messages, data, settings)
end
def settings
{
server_host: server_host.presence || 'localhost',
server_port: server_port.presence || 6659
}
end
def fields
recipients_docs_link = ActionController::Base.helpers.link_to s_('IrkerService|How to enter channels or users?'), Rails.application.routes.url_helpers.help_page_url('user/project/integrations/irker', anchor: 'enter-irker-recipients'), target: '_blank', rel: 'noopener noreferrer'
[
{ type: 'text', name: 'server_host', placeholder: 'localhost', title: s_('IrkerService|Server host (optional)'),
help: s_('IrkerService|irker daemon hostname (defaults to localhost).') },
{ type: 'text', name: 'server_port', placeholder: 6659, title: s_('IrkerService|Server port (optional)'),
help: s_('IrkerService|irker daemon port (defaults to 6659).') },
{ type: 'text', name: 'default_irc_uri', title: s_('IrkerService|Default IRC URI (optional)'),
help: s_('IrkerService|URI to add before each recipient.'),
placeholder: 'irc://irc.network.net:6697/' },
{ type: 'textarea', name: 'recipients', title: s_('IrkerService|Recipients'),
placeholder: 'irc[s]://irc.network.net[:port]/#channel', required: true,
help: s_('IrkerService|Channels and users separated by whitespaces. %{recipients_docs_link}').html_safe % { recipients_docs_link: recipients_docs_link.html_safe } },
{ type: 'checkbox', name: 'colorize_messages', title: _('Colorize messages') }
]
end
def help
docs_link = ActionController::Base.helpers.link_to _('Learn more.'), Rails.application.routes.url_helpers.help_page_url('user/project/integrations/irker', anchor: 'set-up-an-irker-daemon'), target: '_blank', rel: 'noopener noreferrer'
s_('IrkerService|Send update messages to an irker server. Before you can use this, you need to set up the irker daemon. %{docs_link}').html_safe % { docs_link: docs_link.html_safe }
end
private
def get_channels
return true unless activated?
return true if recipients.nil? || recipients.empty?
map_recipients
errors.add(:recipients, 'are all invalid') if channels.empty?
true
end
def map_recipients
self.channels = recipients.split(/\s+/).map do |recipient|
format_channel(recipient)
end
channels.reject!(&:nil?)
end
def format_channel(recipient)
uri = nil
# Try to parse the chan as a full URI
begin
uri = consider_uri(URI.parse(recipient))
rescue URI::InvalidURIError
end
unless uri.present? && default_irc_uri.nil?
begin
new_recipient = URI.join(default_irc_uri, '/', recipient).to_s
uri = consider_uri(URI.parse(new_recipient))
rescue StandardError
log_error("Unable to create a valid URL", default_irc_uri: default_irc_uri, recipient: recipient)
end
end
uri
end
def consider_uri(uri)
return if uri.scheme.nil?
# Authorize both irc://domain.com/#chan and irc://domain.com/chan
if uri.is_a?(URI) && uri.scheme[/^ircs?\z/] && !uri.path.nil?
uri.to_s
end
end
end
end
| 34.801724 | 285 | 0.663116 |
bfb4de3f917071a1c512d19b3260c3fefcd8e427 | 954 | # frozen_string_literal: true
module BlogNotification
class HTTP
# Target url.
#
# @return [String]
attr_reader :url
# Request.
#
# @return [Faraday::Connection]
attr_reader :faraday_connection
# Response instance.
#
# @return [Faraday::Response]
attr_reader :response
# Response body.
#
# @return [String]
attr_reader :body
# Initialize HTTP class.
#
# @param url [String] Target url.
def initialize(url)
@url = url
@faraday_connection = Faraday::Connection.new(url: @url) do |faraday|
faraday.adapter Faraday.default_adapter
end
end
# Send request.
#
# @return [Faraday::Response]
def request
@response = @faraday_connection.get
@body = @response.body
@response
end
# Check request was success.
#
# @return [true, false]
def success?
@response.success?
end
end
end | 17.666667 | 75 | 0.600629 |
e92acaea70180e946f15c5d56137c1e53079e040 | 2,747 | #
# The MIT License
# Copyright (c) 2015 Estonian Information System Authority (RIA), Population Register Centre (VRK)
#
# 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.
#
$CLASSPATH << "build/libs"
Dir.glob(File.expand_path("../../../build/libs/*.jar", __FILE__)).each do |file|
require file
end
CenterUi::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
# config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types.
# XXX Make sure the version of pg_dump found first in your path matches the
# version of Postgres used.
# XXX Make sure the local connections are authenticated using the md5 scheme;
# this is set in pg_hba.conf.
config.active_record.schema_format = :sql
end
| 43.603175 | 98 | 0.770659 |
38a32b4aa357443f4348d7c2079473485c100578 | 3,541 | # This file should contain all the record creation needed to seed the database
# with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the
# db with db:setup).
# ******* NOTE ********
# You will have problems if you try to change the titles of
# courses/sections/lessons, since that's currently what's used to uniquely
# identify them!
# rubocop:disable Metrics/AbcSize
def create_or_update_path(path_attrs)
path = Path.where(title: path_attrs[:title]).first
if path.nil?
path = Path.create!(path_attrs)
Rails.logger.info ">>>> Created new path: #{path_attrs[:title]}!"
elsif path.attributes == path_attrs
Rails.logger.info "No changes to existing path: #{path_attrs[:title]}"
else
path.update(path_attrs)
Rails.logger.info "Updated existing << PATH >>: #{path_attrs[:title]}"
end
path
end
def create_or_update_course(course_attrs)
course = Course.where(title: course_attrs[:title]).first
if course.nil?
course = Course.create!(course_attrs)
Rails.logger.info ">>>> Created new course: #{course_attrs[:title]}!"
elsif course.attributes == course_attrs
Rails.logger.info "No changes to existing course: #{course_attrs[:title]}"
else
course.update!(course_attrs)
Rails.logger.info "Updated existing << COURSE >>: #{course_attrs[:title]}"
end
course
end
def create_or_update_section(section_attrs)
section = Section.where(title: section_attrs[:title], course_id: section_attrs[:course_id]).first
if section.nil?
section = Section.create!(section_attrs)
Rails.logger.info ">>>> Created new SECTION: #{section_attrs[:title]}!"
elsif section.attributes == section_attrs
Rails.logger.info "No changes to existing section: #{section_attrs[:title]}"
else
section.update!(section_attrs)
Rails.logger.info "Updated existing SECTION: #{section_attrs[:title]}"
end
section
end
def create_or_update_lesson(lesson_attrs)
lesson = Lesson.where(title: lesson_attrs[:title], section_id: lesson_attrs[:section_id]).first
if lesson.nil?
lesson = Lesson.create!(lesson_attrs)
Rails.logger.info ">>>> Created new lesson: #{lesson_attrs[:title]}!"
elsif lesson.attributes == lesson_attrs
Rails.logger.info "No changes to existing lesson: #{lesson_attrs[:title]}"
else
lesson.update!(lesson_attrs)
Rails.logger.info "Updated existing lesson: #{lesson_attrs[:title]}"
end
lesson
end
# rubocop:enable Metrics/AbcSize
load './db/seeds/01_foundations_seeds.rb'
load './db/seeds/02_ruby_course_seeds.rb'
load './db/seeds/03_database_course_seeds.rb'
load './db/seeds/04_rails_course_seeds.rb'
load './db/seeds/05_html_css_course_seeds.rb'
load './db/seeds/06_javascript_course_seeds.rb'
load './db/seeds/07_getting_hired_course_seeds.rb'
load './db/seeds/08_node_js_course_seeds.rb'
Rails.logger.info "\n\n***** STARTING PATHS *****"
load './db/seeds/paths/foundations.rb'
load './db/seeds/paths/full_stack_rails.rb'
load './db/seeds/paths/full_stack_javascript.rb'
# GENERATE SUCCESS STORY Content
load './db/seeds/success_stories.rb'
# GENERATE test projects
load './db/seeds/test_project_submissions.rb'
#################
# SANITY CHECKS #
#################
Rails.logger.info "\n\n\n\n\n################## SANITY CHECKS ##################\n\n"
Rails.logger.info "#{Path.count} paths, #{Course.count} courses, #{Section.count} sections and #{Lesson.count} lessons in the database.\n"
Rails.logger.info "\n#######################################################\n\n\n\n"
| 33.40566 | 138 | 0.704886 |
7ac8262db1769e26275d7087876013b096306c3e | 1,607 | #-- encoding: UTF-8
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2021 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
module Queries::Operators::Concerns
module ContainsAllValues
extend ActiveSupport::Concern
class_methods do
def sql_for_field(values, db_table, db_field)
values
.first
.split(/\s+/)
.map { |substr| "#{db_table}.#{db_field} ILIKE '%#{connection.quote_string(substr)}%'" }
.join(' AND ')
end
end
end
end
| 34.934783 | 98 | 0.721842 |
abed9497f2299627f0cc36a6c065278aee2b2780 | 517 | # frozen_string_literal: true
require 'spec_helper'
require 'vk/api/board/methods/restore_comment'
RSpec.describe Vk::API::Board::Methods::RestoreComment do
subject(:model) { described_class }
it { is_expected.to be < Dry::Struct }
it { is_expected.to be < Vk::Schema::Method }
describe 'attributes' do
subject(:attributes) { model.instance_methods(false) }
it { is_expected.to include :group_id }
it { is_expected.to include :topic_id }
it { is_expected.to include :comment_id }
end
end
| 28.722222 | 58 | 0.72147 |
bb514d8b76649d19cdebbb2cfd98b63670a2b70c | 3,872 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Attempt to read encrypted secrets from `config/secrets.yml.enc`.
# Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or
# `config/secrets.yml.key`.
config.read_encrypted_secrets = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "app_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
| 42.086957 | 103 | 0.738895 |
286855ea3b1ca3a2ccff37f45b002713f6eff50a | 1,242 | # frozen_string_literal: true
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
# [START speech_v1_generated_Adaptation_DeleteCustomClass_sync]
require "google/cloud/speech/v1"
# Create a client object. The client can be reused for multiple calls.
client = Google::Cloud::Speech::V1::Adaptation::Client.new
# Create a request. To set request fields, pass in keyword arguments.
request = Google::Cloud::Speech::V1::DeleteCustomClassRequest.new
# Call the delete_custom_class method.
result = client.delete_custom_class request
# The returned object is of type Google::Protobuf::Empty.
p result
# [END speech_v1_generated_Adaptation_DeleteCustomClass_sync]
| 36.529412 | 74 | 0.783414 |
08e48bcc1e5e978a2ae4acf0483c62dc73da127e | 936 | # encoding: utf-8
#
# Demonstration of enabling and disabling kerning support
#
require "#{File.dirname(__FILE__)}/../example_helper.rb"
Prawn::Document.generate "kerning.pdf" do
text "To kern?", :at => [200,720], :size => 24, :kerning => true
text "To not kern?", :at => [200,690], :size => 24, :kerning => false
move_down 100
pad(30) do
text "To kern and wrap. " * 5, :size => 24, :kerning => true
end
text "To not kern and wrap. " * 5, :size => 24, :kerning => false
font "#{Prawn::BASEDIR}/data/fonts/DejaVuSans.ttf"
text "To kern?", :at => [200,660], :size => 24, :kerning => true
text "To not kern?", :at => [200,630], :size => 24, :kerning => false
pad(30) do
text "To kern and wrap. " * 5, :size => 24, :kerning => true
end
text "To not kern and wrap. " * 5, :size => 24, :kerning => false
end
| 30.193548 | 76 | 0.53953 |
1d3d349ccbefd7763c768342a508bb4cd6b868cf | 2,996 | # -*- encoding: utf-8 -*-
# stub: rails 4.2.5 ruby lib
Gem::Specification.new do |s|
s.name = "rails".freeze
s.version = "4.2.5"
s.required_rubygems_version = Gem::Requirement.new(">= 1.8.11".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["David Heinemeier Hansson".freeze]
s.date = "2015-11-12"
s.description = "Ruby on Rails is a full-stack web framework optimized for programmer happiness and sustainable productivity. It encourages beautiful code by favoring convention over configuration.".freeze
s.email = "[email protected]".freeze
s.homepage = "http://www.rubyonrails.org".freeze
s.licenses = ["MIT".freeze]
s.required_ruby_version = Gem::Requirement.new(">= 1.9.3".freeze)
s.rubygems_version = "2.7.7".freeze
s.summary = "Full-stack web application framework.".freeze
s.installed_by_version = "2.7.7" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<activesupport>.freeze, ["= 4.2.5"])
s.add_runtime_dependency(%q<actionpack>.freeze, ["= 4.2.5"])
s.add_runtime_dependency(%q<actionview>.freeze, ["= 4.2.5"])
s.add_runtime_dependency(%q<activemodel>.freeze, ["= 4.2.5"])
s.add_runtime_dependency(%q<activerecord>.freeze, ["= 4.2.5"])
s.add_runtime_dependency(%q<actionmailer>.freeze, ["= 4.2.5"])
s.add_runtime_dependency(%q<activejob>.freeze, ["= 4.2.5"])
s.add_runtime_dependency(%q<railties>.freeze, ["= 4.2.5"])
s.add_runtime_dependency(%q<bundler>.freeze, ["< 2.0", ">= 1.3.0"])
s.add_runtime_dependency(%q<sprockets-rails>.freeze, [">= 0"])
else
s.add_dependency(%q<activesupport>.freeze, ["= 4.2.5"])
s.add_dependency(%q<actionpack>.freeze, ["= 4.2.5"])
s.add_dependency(%q<actionview>.freeze, ["= 4.2.5"])
s.add_dependency(%q<activemodel>.freeze, ["= 4.2.5"])
s.add_dependency(%q<activerecord>.freeze, ["= 4.2.5"])
s.add_dependency(%q<actionmailer>.freeze, ["= 4.2.5"])
s.add_dependency(%q<activejob>.freeze, ["= 4.2.5"])
s.add_dependency(%q<railties>.freeze, ["= 4.2.5"])
s.add_dependency(%q<bundler>.freeze, ["< 2.0", ">= 1.3.0"])
s.add_dependency(%q<sprockets-rails>.freeze, [">= 0"])
end
else
s.add_dependency(%q<activesupport>.freeze, ["= 4.2.5"])
s.add_dependency(%q<actionpack>.freeze, ["= 4.2.5"])
s.add_dependency(%q<actionview>.freeze, ["= 4.2.5"])
s.add_dependency(%q<activemodel>.freeze, ["= 4.2.5"])
s.add_dependency(%q<activerecord>.freeze, ["= 4.2.5"])
s.add_dependency(%q<actionmailer>.freeze, ["= 4.2.5"])
s.add_dependency(%q<activejob>.freeze, ["= 4.2.5"])
s.add_dependency(%q<railties>.freeze, ["= 4.2.5"])
s.add_dependency(%q<bundler>.freeze, ["< 2.0", ">= 1.3.0"])
s.add_dependency(%q<sprockets-rails>.freeze, [">= 0"])
end
end
| 49.114754 | 207 | 0.650534 |
28a30233ff5ee2e48df93d80e7aeeac623faefad | 1,127 | class GamesController < ProtectedController
before_action :set_game, only: [:show, :update, :destroy]
# GET /games
# GET /games.json
def index
@games = Game.where(user_id: current_user.id)
render json: @games
end
# GET /games/1
# GET /games/1.json
def show
render json: @game
end
# POST /games
# POST /games.json
def create
@game = Game.new(parent_taxon_id: 1 + rand(ParentTaxon.all.length))
if @game.save
current_user.games << @game
render json: @game, status: :created, location: @game
else
render json: @game.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /games/1
# PATCH/PUT /games/1.json
def update
@game = Game.find(params[:id])
if @game.update(game_params)
head :no_content
else
render json: @game.errors, status: :unprocessable_entity
end
end
# DELETE /games/1
# DELETE /games/1.json
def destroy
@game.destroy
head :no_content
end
private
def set_game
@game = Game.find(params[:id])
end
def game_params
params.require(:game).permit(:game_solved)
end
end
| 18.783333 | 71 | 0.648625 |
b971ec44db27e7bf5898c1ef40884f0f84b18118 | 79 |
Site.index :fast do
include_types "PageClass1", PageClass2, :PageClass3
end
| 15.8 | 53 | 0.772152 |
037f319c1cc1679f5a72d4a5e7d12b0172838369 | 1,179 | module LoanPresenter
extend ActiveSupport::Concern
included do
extend ActiveModel::Naming
extend ActiveModel::Callbacks
include ActiveModel::Conversion
include ActiveModel::MassAssignmentSecurity
include ActiveModel::Validations
attr_reader :loan
delegate :modified_by, :modified_by=, to: :loan
define_model_callbacks :save
define_model_callbacks :validation
def valid?(context = nil)
run_callbacks :validation do
super
end
end
end
module ClassMethods
def attribute(name, options = {})
methods = [name]
unless options[:read_only]
methods << "#{name}="
attr_accessible name
end
delegate *methods, to: :loan
end
end
def initialize(loan)
@loan = loan
end
def attributes=(attributes)
sanitize_for_mass_assignment(attributes).each do |k, v|
public_send("#{k}=", v)
end
end
def persisted?
false
end
def valid?
run_callbacks :validation do
super
end
end
def save
return false unless valid?
loan.transaction do
run_callbacks :save do
loan.save!
end
end
end
end
| 17.338235 | 59 | 0.649703 |
289f758bb2f026f2e8dbc4efc7012b4aa3de9ab4 | 310 | module Hubtran
class Response
def initialize(response)
@response = response
end
def successful?
@response.success?
end
def errors
return [] if successful?
to_hash["errors"]
end
def to_hash
@to_hash ||= JSON.parse(@response.body)
end
end
end
| 14.761905 | 45 | 0.603226 |
1852e9d5f5c4c82a0d38e60cd4881c37ffa9c13e | 322 | module EmarsysLegacy
# Methods for the Lanugage API
#
#
class Language < DataObject
class << self
# List languages
#
# @return [Hash] List of languages
# @example
# EmarsysLegacy::Language.collection
def collection
get 'language', {}
end
end
end
end | 16.1 | 44 | 0.580745 |
79f929f87884c540b774cdf3a5431037078a1883 | 2,251 | # frozen_string_literal: true
# Copyright 2016-2021 Copado NCS LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require "rubygems"
control "precedence" do
title "precedence"
desc "Tests to validate the precedence of overriding system attributes."
describe "attribute(\"output_first_output\")" do
subject do
attribute("output_first_output")
end
it { should eq "First Output" }
end
describe "attribute(\"first_output\")" do
subject do
attribute("first_output")
end
if ::Gem::Requirement.new("~> 3.0").satisfied_by? ::Gem::Version.new ::Inspec::VERSION
it "should eq \"From Attributes File\" in InSpec 3" do
should eq "From Attributes File"
end
else
it "should eq \"Second Output\" in InSpec 4" do
should eq "Second Output"
end
end
end
describe "attribute(\"output_second_output\")" do
subject do
attribute("output_second_output")
end
it { should eq "Second Output" }
end
describe "attribute(\"second_output\")" do
subject do
attribute("second_output")
end
it { should eq "Third Output" }
end
describe "attribute(\"output_third_output\")" do
subject do
attribute("output_third_output")
end
it { should eq "First Output" }
end
describe "attribute(\"third_output\")" do
subject do
attribute("third_output")
end
it { should eq "Third Output" }
end
describe "attribute(\"undefined_output\")" do
subject do
attribute("undefined_output")
end
it { should eq "From Attributes File" }
end
describe "attribute(\"input_passthrough\")" do
subject do
attribute("input_passthrough")
end
it { should eq "value" }
end
end
| 23.694737 | 90 | 0.6757 |
e9fcfc55b3e89164dcba3b7ec9a72b6b4d00f512 | 405 | require 'spec_helper'
describe Seatbelt::GhostTunnel do
let(:tunnel){ Seatbelt::GhostTunnel }
it "is a module" do
expect(tunnel).to be_a Module
end
describe "methods" do
it "provides #enable_tunneling!" do
expect(tunnel).to respond_to(:enable_tunneling!)
end
it "provides #disable_tunneling!" do
expect(tunnel).to respond_to(:disable_tunneling!)
end
end
end | 19.285714 | 55 | 0.696296 |
e85bdbe7c39246386189e614c3fae231a3f9cfe5 | 6,715 | # Use this setup block to configure all options available in SimpleForm.
SimpleForm.setup do |config|
# Wrappers are used by the form builder to generate a
# complete input. You can remove any component from the
# wrapper, change the order or even add your own to the
# stack. The options given below are used to wrap the
# whole input.
config.wrappers :default, :class => :input,
:hint_class => :field_with_hint, :error_class => :field_with_errors do |b|
## Extensions enabled by default
# Any of these extensions can be disabled for a
# given input by passing: `f.input EXTENSION_NAME => false`.
# You can make any of these extensions optional by
# renaming `b.use` to `b.optional`.
# Determines whether to use HTML5 (:email, :url, ...)
# and required attributes
b.use :html5
# Calculates placeholders automatically from I18n
# You can also pass a string as f.input :placeholder => "Placeholder"
b.use :placeholder
## Optional extensions
# They are disabled unless you pass `f.input EXTENSION_NAME => :lookup`
# to the input. If so, they will retrieve the values from the model
# if any exists. If you want to enable the lookup for any of those
# extensions by default, you can change `b.optional` to `b.use`.
# Calculates maxlength from length validations for string inputs
b.optional :maxlength
# Calculates pattern from format validations for string inputs
b.optional :pattern
# Calculates min and max from length validations for numeric inputs
b.optional :min_max
# Calculates readonly automatically from readonly attributes
b.optional :readonly
## Inputs
b.use :label_input
b.use :hint, :wrap_with => { :tag => :span, :class => :hint }
b.use :error, :wrap_with => { :tag => :span, :class => :error }
end
config.wrappers :bootstrap, :tag => 'div', :class => 'control-group', :error_class => 'error' do |b|
b.use :html5
b.use :placeholder
b.use :label
b.wrapper :tag => 'div', :class => 'controls' do |ba|
ba.use :input
ba.use :error, :wrap_with => { :tag => 'span', :class => 'help-inline' }
ba.use :hint, :wrap_with => { :tag => 'p', :class => 'help-block' }
end
end
config.wrappers :prepend, :tag => 'div', :class => "control-group", :error_class => 'error' do |b|
b.use :html5
b.use :placeholder
b.use :label
b.wrapper :tag => 'div', :class => 'controls' do |input|
input.wrapper :tag => 'div', :class => 'input-prepend' do |prepend|
prepend.use :input
end
input.use :hint, :wrap_with => { :tag => 'span', :class => 'help-block' }
input.use :error, :wrap_with => { :tag => 'span', :class => 'help-inline' }
end
end
config.wrappers :append, :tag => 'div', :class => "control-group", :error_class => 'error' do |b|
b.use :html5
b.use :placeholder
b.use :label
b.wrapper :tag => 'div', :class => 'controls' do |input|
input.wrapper :tag => 'div', :class => 'input-append' do |append|
append.use :input
end
input.use :hint, :wrap_with => { :tag => 'span', :class => 'help-block' }
input.use :error, :wrap_with => { :tag => 'span', :class => 'help-inline' }
end
end
# Wrappers for forms and inputs using the Twitter Bootstrap toolkit.
# Check the Bootstrap docs (http://twitter.github.com/bootstrap)
# to learn about the different styles for forms and inputs,
# buttons and other elements.
config.default_wrapper = :bootstrap
# Define the way to render check boxes / radio buttons with labels.
# Defaults to :nested for bootstrap config.
# :inline => input + label
# :nested => label > input
config.boolean_style = :nested
# Default class for buttons
config.button_class = 'btn'
# Method used to tidy up errors.
# config.error_method = :first
# Default tag used for error notification helper.
config.error_notification_tag = :div
# CSS class to add for error notification helper.
config.error_notification_class = 'alert alert-error'
# ID to add for error notification helper.
# config.error_notification_id = nil
# Series of attempts to detect a default label method for collection.
# config.collection_label_methods = [ :to_label, :name, :title, :to_s ]
# Series of attempts to detect a default value method for collection.
# config.collection_value_methods = [ :id, :to_s ]
# You can wrap a collection of radio/check boxes in a pre-defined tag, defaulting to none.
# config.collection_wrapper_tag = nil
# You can define the class to use on all collection wrappers. Defaulting to none.
# config.collection_wrapper_class = nil
# You can wrap each item in a collection of radio/check boxes with a tag,
# defaulting to :span. Please note that when using :boolean_style = :nested,
# SimpleForm will force this option to be a label.
# config.item_wrapper_tag = :span
# You can define a class to use in all item wrappers. Defaulting to none.
# config.item_wrapper_class = nil
# How the label text should be generated altogether with the required text.
# config.label_text = lambda { |label, required| "#{required} #{label}" }
# You can define the class to use on all labels. Default is nil.
config.label_class = 'control-label'
# You can define the class to use on all forms. Default is simple_form.
config.form_class = 'form-horizontal'
# You can define which elements should obtain additional classes
# config.generate_additional_classes_for = [:wrapper, :label, :input]
# Whether attributes are required by default (or not). Default is true.
# config.required_by_default = true
# Tell browsers whether to use default HTML5 validations (novalidate option).
# Default is enabled.
config.browser_validations = false
# Collection of methods to detect if a file type was given.
# config.file_methods = [ :mounted_as, :file?, :public_filename ]
# Custom mappings for input types. This should be a hash containing a regexp
# to match as key, and the input type that will be used when the field name
# matches the regexp as value.
# config.input_mappings = { /count/ => :integer }
# Default priority for time_zone inputs.
# config.time_zone_priority = nil
# Default priority for country inputs.
# config.country_priority = nil
# Default size for text inputs.
# config.default_input_size = 50
# When false, do not use translations for labels.
# config.translate_labels = true
# Automatically discover new inputs in Rails' autoload path.
# config.inputs_discovery = true
# Cache SimpleForm inputs discovery
# config.cache_discovery = !Rails.env.development?
end
| 37.937853 | 102 | 0.685778 |
e2f1020a09d66ca0683fa5c739c5cc0df1bbcc25 | 602 | # frozen_string_literal: true
# WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/version-3/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
$:.unshift(File.expand_path('../../lib', __FILE__))
$:.unshift(File.expand_path('../../../aws-sdk-core/features', __FILE__))
$:.unshift(File.expand_path('../../../aws-sdk-core/lib', __FILE__))
$:.unshift(File.expand_path('../../../aws-sigv4/lib', __FILE__))
require 'features_helper'
require 'aws-sdk-account'
Aws::Account::Client.add_plugin(ApiCallTracker)
| 31.684211 | 74 | 0.722591 |
f77ebbf27daf9ae940f6de5023be979df33825c7 | 2,246 | #!/usr/bin/env ruby
def roller(orignal_spec)
rtn = []
sets, iterations, die, modifier, drop, reroll, totals = 1, 1, 20, 0, false, false, false
spec = orignal_spec.dup
if spec.gsub!(/([+-]\d+)$/, '')
modifier = $&.to_i
end
if spec.gsub!(/[rR]$/, '')
reroll = true
end
drop = true if spec =~ /D/
if spec.gsub!(/^(\d+)[xX]/, '')
sets = $&.to_i
elsif spec.gsub!(/[xX](\d+)$/, '')
sets = $&.to_i
end
if spec =~ /(\d+)[dD](\d+)/
iterations = $1.to_i
die = $2.to_i
end
iterations = 1 if iterations < 1 || iterations > 30
die = 20 if die < 1 || die > 1000000000
sets = 6 if sets < 1 || sets > 40
drop = false if iterations == 1
width = die.to_s.length
1.upto(sets) {
scores = []
lowest = die
total = 0
shown = 0
1.upto(iterations) {
if reroll and (die != 1)
rand_num = 1
rand_num = Kernel.rand(die)+1 while rand_num == 1
else
rand_num = Kernel.rand(die)+1
end
lowest = rand_num if rand_num < lowest
scores.push rand_num
}
rtn << iterations.to_s + "d" + die.to_s
rtn << "r" if reroll
if modifier != 0
rtn << "+" if modifier > 0
rtn << "-" if modifier < 0
rtn << modifier.abs.to_s
end
rtn << ": "
scores.each { |score|
shown += 1
rtn << " + " if shown > 1 and !totals
if (score == lowest) and drop
rtn << sprintf("[%" + width.to_s + "s]", score) if !totals
lowest = -1
else
if !totals and (iterations > 1)
rtn << " " if drop
rtn << sprintf("%" + width.to_s + "s", score)
rtn << " " if drop
end
total += score
end
}
rtn << " = " if !totals and iterations > 1
if (modifier != 0)
if !totals
rtn << sprintf("%" + (width+1).to_s + "s ", total)
rtn << '+' if modifier > 0
rtn << '-' if modifier < 0
rtn << " " + modifier.abs.to_s + " = "
end
total += modifier
end
rtn << sprintf("%" + (width+1).to_s + "s\n", total)
}
return rtn.join
end
#---------------------------------------------------------------------
ARGV.each do |expression|
puts roller(expression)
end
| 20.418182 | 90 | 0.480855 |
acc6b4c80c579ea942ba355e016d3797ae782dde | 2,193 | # frozen_string_literal: true
module GraphQL
module StaticValidation
module ArgumentsAreDefined
def on_argument(node, parent)
parent_defn = parent_definition(parent)
if parent_defn && context.warden.get_argument(parent_defn, node.name)
super
elsif parent_defn
kind_of_node = node_type(parent)
error_arg_name = parent_name(parent, parent_defn)
add_error(GraphQL::StaticValidation::ArgumentsAreDefinedError.new(
"#{kind_of_node} '#{error_arg_name}' doesn't accept argument '#{node.name}'",
nodes: node,
name: error_arg_name,
type: kind_of_node,
argument_name: node.name,
parent: parent_defn
))
else
# Some other weird error
super
end
end
private
# TODO smell: these methods are added to all visitors, since they're included in a module.
def parent_name(parent, type_defn)
case parent
when GraphQL::Language::Nodes::Field
parent.alias || parent.name
when GraphQL::Language::Nodes::InputObject
type_defn.graphql_name
when GraphQL::Language::Nodes::Argument, GraphQL::Language::Nodes::Directive
parent.name
else
raise "Invariant: Unexpected parent #{parent.inspect} (#{parent.class})"
end
end
def node_type(parent)
parent.class.name.split("::").last
end
def parent_definition(parent)
case parent
when GraphQL::Language::Nodes::InputObject
arg_defn = context.argument_definition
if arg_defn.nil?
nil
else
arg_ret_type = arg_defn.type.unwrap
if arg_ret_type.kind.input_object?
arg_ret_type
else
nil
end
end
when GraphQL::Language::Nodes::Directive
context.schema.directives[parent.name]
when GraphQL::Language::Nodes::Field
context.field_definition
else
raise "Unexpected argument parent: #{parent.class} (##{parent})"
end
end
end
end
end
| 30.458333 | 96 | 0.598723 |
e89c87d769fb1de05dbe1367f73f5051ebecb01c | 3,206 | # This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
require 'database_cleaner'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }
# Checks for pending migrations and applies them before tests are run.
# If you are not using ActiveRecord, you can remove these lines.
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
puts e.to_s.strip
exit 1
end
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
config.include FactoryBot::Syntax::Methods
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
DatabaseCleaner.strategy = :transaction
end
config.around(:each) do |example|
DatabaseCleaner.cleaning do
example.run
end
end
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
end
| 38.626506 | 86 | 0.745789 |
086b2a15fc8eadb069fc8010390cacf9f311731c | 3,890 | module MyRegistrations
class Statuses < UserSpecificModel
include RegistrationsModule
include Berkeley::UserRoles
include Cache::CachedFeed
include Cache::JsonifiedFeed
include Cache::UserCacheExpiry
include ClassLogger
PRIORITIZED_CAREERS = ['LAW', 'GRAD', 'UGRD', 'UCBX']
def get_feed_internal
{
terms: flagged_terms,
registrations: get_registration_statuses
}
end
private
def get_registration_statuses
match_terms(registrations, flagged_terms).tap do |term_registrations|
match_positive_indicators term_registrations
set_summer_flags term_registrations
set_regstatus_flags term_registrations
set_regstatus_messaging term_registrations
set_cnp_flags term_registrations
set_cnp_messaging term_registrations
end
end
# Match registration terms with Berkeley::Terms-defined terms.
def match_terms(registrations = [], terms = [])
matched_terms = {}
terms.each do |term_key, term_value|
next if (term_value.nil? || matched_terms[term_value[:id]].present?)
term_id = term_value[:id]
# Array format due to the possibility of a single term containing multiple academic career registrations
term_registrations = []
registrations.to_a.each do |registration|
if term_id == registration.try(:[], 'term').try(:[], 'id')
registration[:termFlags] = term_value
registration['term']['name'] = normalized_english registration['term']['name']
term_registrations.push(registration)
end
end
# If there is more than one career in a term, we prioritize them and only show the most relevant one.
term_registration = find_relevant_career term_registrations
matched_terms[term_id] = term_registration if term_registration.present?
end
matched_terms
end
# If a student is activated for more than one career within a term, we prioritize the careers
# and only show the most relevant one. Prioritization of careers follows the pattern of LAW -> GRAD -> UGRD
def find_relevant_career(registrations)
return nil if registrations.length == 0
return registrations[0] if registrations.length == 1
PRIORITIZED_CAREERS.each do |career|
relevant_career = registrations.find do |registration|
registration.try(:[], 'academicCareer').try(:[], 'code') == career
end
return relevant_career if relevant_career
end
nil
end
# Match positive service indicators from student attributes with their registration term.
def match_positive_indicators(term_registrations = {})
# Create a clone of the positive service indicators array, since we'll be altering it.
pos_indicators = MyRegistrations::PositiveServiceIndicators.new(@uid).get.clone
term_registrations.each do |term_id, term_values|
term_values[:positiveIndicators] = [].tap do |term_indicators|
# Each indicator has a "fromTerm" and a "toTerm", but UC Berkeley usage of the positive service indicator is
# term-specific, so these should always be the same.
pos_indicators.delete_if do |indicator|
if term_id.try(:to_i) == indicator.try(:[], 'fromTerm').try(:[], 'id').try(:to_i)
term_indicators << indicator
# Delete the indicator from our array so we don't have to process it again
true
end
end
end
end
term_registrations
end
def flagged_terms
@flagged_terms ||= MyRegistrations::FlaggedTerms.new.get
end
def registrations
@registrations ||= HubEdos::StudentApi::V2::Feeds::Registrations.new(user_id: @uid).get
@registrations.try(:[], :feed).try(:[], 'registrations') || []
end
end
end
| 39.292929 | 118 | 0.67892 |
6a4d00ae7c7f02e9e1f509ea906b9a5847965b75 | 7,427 | require 'spree/backend/action_callbacks'
class Spree::Admin::ResourceController < Spree::Admin::BaseController
helper_method :new_object_url, :edit_object_url, :object_url, :collection_url
before_filter :load_resource, :except => [:update_positions]
rescue_from ActiveRecord::RecordNotFound, :with => :resource_not_found
respond_to :html
respond_to :js, :except => [:show, :index]
def new
invoke_callbacks(:new_action, :before)
respond_with(@object) do |format|
format.html { render :layout => !request.xhr? }
format.js { render :layout => false }
end
end
def edit
respond_with(@object) do |format|
format.html { render :layout => !request.xhr? }
format.js { render :layout => false }
end
end
def update
invoke_callbacks(:update, :before)
if @object.update_attributes(permitted_resource_params)
invoke_callbacks(:update, :after)
flash[:success] = flash_message_for(@object, :successfully_updated)
respond_with(@object) do |format|
format.html { redirect_to location_after_save }
format.js { render :layout => false }
end
else
invoke_callbacks(:update, :fails)
respond_with(@object)
end
end
def create
invoke_callbacks(:create, :before)
@object.attributes = permitted_resource_params
if @object.save
invoke_callbacks(:create, :after)
flash[:success] = flash_message_for(@object, :successfully_created)
respond_with(@object) do |format|
format.html { redirect_to location_after_save }
format.js { render :layout => false }
end
else
invoke_callbacks(:create, :fails)
respond_with(@object)
end
end
def update_positions
params[:positions].each do |id, index|
model_class.where(:id => id).update_all(:position => index)
end
respond_to do |format|
format.js { render :text => 'Ok' }
end
end
def destroy
invoke_callbacks(:destroy, :before)
if @object.destroy
invoke_callbacks(:destroy, :after)
flash[:success] = flash_message_for(@object, :successfully_removed)
respond_with(@object) do |format|
format.html { redirect_to collection_url }
format.js { render :partial => "spree/admin/shared/destroy" }
end
else
invoke_callbacks(:destroy, :fails)
respond_with(@object) do |format|
format.html { redirect_to collection_url }
end
end
end
protected
def resource_not_found
flash[:error] = flash_message_for(model_class.new, :not_found)
redirect_to collection_url
end
class << self
attr_accessor :parent_data
attr_accessor :callbacks
def belongs_to(model_name, options = {})
@parent_data ||= {}
@parent_data[:model_name] = model_name
@parent_data[:model_class] = model_name.to_s.classify.constantize
@parent_data[:find_by] = options[:find_by] || :id
end
def new_action
@callbacks ||= {}
@callbacks[:new_action] ||= Spree::ActionCallbacks.new
end
def create
@callbacks ||= {}
@callbacks[:create] ||= Spree::ActionCallbacks.new
end
def update
@callbacks ||= {}
@callbacks[:update] ||= Spree::ActionCallbacks.new
end
def destroy
@callbacks ||= {}
@callbacks[:destroy] ||= Spree::ActionCallbacks.new
end
end
def model_class
"Spree::#{controller_name.classify}".constantize
end
def model_name
parent_data[:model_name].gsub('spree/', '')
end
def object_name
controller_name.singularize
end
def load_resource
if member_action?
@object ||= load_resource_instance
# call authorize! a third time (called twice already in Admin::BaseController)
# this time we pass the actual instance so fine-grained abilities can control
# access to individual records, not just entire models.
authorize! action, @object
instance_variable_set("@#{object_name}", @object)
else
@collection ||= collection
# note: we don't call authorize here as the collection method should use
# CanCan's accessible_by method to restrict the actual records returned
instance_variable_set("@#{controller_name}", @collection)
end
end
def load_resource_instance
if new_actions.include?(action)
build_resource
elsif params[:id]
find_resource
end
end
def parent_data
self.class.parent_data
end
def parent
if parent_data.present?
@parent ||= parent_data[:model_class].send("find_by_#{parent_data[:find_by]}", params["#{model_name}_id"])
instance_variable_set("@#{model_name}", @parent)
else
nil
end
end
def find_resource
if parent_data.present?
parent.send(controller_name).find(params[:id])
else
model_class.find(params[:id])
end
end
def build_resource
if parent_data.present?
parent.send(controller_name).build
else
model_class.new
end
end
def collection
return parent.send(controller_name) if parent_data.present?
if model_class.respond_to?(:accessible_by) && !current_ability.has_block?(params[:action], model_class)
model_class.accessible_by(current_ability, action)
else
model_class.scoped
end
end
def location_after_save
collection_url
end
def invoke_callbacks(action, callback_type)
callbacks = self.class.callbacks || {}
return if callbacks[action].nil?
case callback_type.to_sym
when :before then callbacks[action].before_methods.each {|method| send method }
when :after then callbacks[action].after_methods.each {|method| send method }
when :fails then callbacks[action].fails_methods.each {|method| send method }
end
end
# URL helpers
def new_object_url(options = {})
if parent_data.present?
spree.new_polymorphic_url([:admin, parent, model_class], options)
else
spree.new_polymorphic_url([:admin, model_class], options)
end
end
def edit_object_url(object, options = {})
if parent_data.present?
spree.send "edit_admin_#{model_name}_#{object_name}_url", parent, object, options
else
spree.send "edit_admin_#{object_name}_url", object, options
end
end
def object_url(object = nil, options = {})
target = object ? object : @object
if parent_data.present?
spree.send "admin_#{model_name}_#{object_name}_url", parent, target, options
else
spree.send "admin_#{object_name}_url", target, options
end
end
def collection_url(options = {})
if parent_data.present?
spree.polymorphic_url([:admin, parent, model_class], options)
else
spree.polymorphic_url([:admin, model_class], options)
end
end
# Allow all attributes to be updatable.
#
# Other controllers can, should, override it to set custom logic
def permitted_resource_params
params.require(object_name).permit!
end
def collection_actions
[:index]
end
def member_action?
!collection_actions.include? action
end
def new_actions
[:new, :create]
end
end
| 27.609665 | 114 | 0.649522 |
7a1ee8258558581f3a281a4966992446a21c6dcc | 12,406 | # Copyright 2010-2014 Greg Hurrell. All rights reserved.
# Licensed under the terms of the BSD 2-clause license.
module CommandT
class Controller
include PathUtilities
include SCMUtilities
def initialize
@prompt = Prompt.new
end
def show_buffer_finder
@path = VIM::pwd
@active_finder = buffer_finder
show
end
def show_jump_finder
@path = VIM::pwd
@active_finder = jump_finder
show
end
def show_mru_finder
@path = VIM::pwd
@active_finder = mru_finder
show
end
def show_tag_finder
@path = VIM::pwd
@active_finder = tag_finder
show
end
def show_file_finder
# optional parameter will be desired starting directory, or ""
arg = ::VIM::evaluate('a:arg')
if arg && arg.size > 0
@path = File.expand_path(arg, VIM::pwd)
else
traverse = VIM::get_string('g:CommandTTraverseSCM') || 'file'
case traverse
when 'file'
@path = nearest_ancestor(VIM::current_file_dir, scm_markers) || VIM::pwd
when 'dir'
@path = nearest_ancestor(VIM::pwd, scm_markers) || VIM::pwd
else
@path = VIM::pwd
end
end
@active_finder = file_finder
file_finder.path = @path
show
rescue Errno::ENOENT
# probably a problem with the optional parameter
@match_window.print_no_such_file_or_directory
end
def hide
@match_window.leave
if VIM::Window.select @initial_window
if @initial_buffer.number == 0
# upstream bug: buffer number misreported as 0
# see: https://wincent.com/issues/1617
::VIM::command "silent b #{@initial_buffer.name}"
else
::VIM::command "silent b #{@initial_buffer.number}"
end
end
end
# Take current matches and stick them in the quickfix window.
def quickfix
hide
matches = @matches.map do |match|
"{ 'filename': '#{VIM::escape_for_single_quotes match}' }"
end.join(', ')
::VIM::command 'call setqflist([' + matches + '])'
::VIM::command 'cope'
end
def refresh
return unless @active_finder && @active_finder.respond_to?(:flush)
@active_finder.flush
list_matches!
end
def flush
@max_height = nil
@min_height = nil
@file_finder = nil
@tag_finder = nil
end
def handle_key
key = ::VIM::evaluate('a:arg').to_i.chr
if @focus == @prompt
@prompt.add! key
@needs_update = true
else
@match_window.find key
end
end
def backspace
if @focus == @prompt
@prompt.backspace!
@needs_update = true
end
end
def delete
if @focus == @prompt
@prompt.delete!
@needs_update = true
end
end
def accept_selection(options = {})
selection = @match_window.selection
hide
open_selection(selection, options) unless selection.nil?
end
def toggle_focus
@focus.unfocus # old focus
@focus = @focus == @prompt ? @match_window : @prompt
@focus.focus # new focus
end
def cancel
hide
end
def select_next
@match_window.select_next
end
def select_prev
@match_window.select_prev
end
def clear
@prompt.clear!
list_matches!
end
def clear_prev_word
@prompt.clear_prev_word!
list_matches!
end
def cursor_left
@prompt.cursor_left if @focus == @prompt
end
def cursor_right
@prompt.cursor_right if @focus == @prompt
end
def cursor_end
@prompt.cursor_end if @focus == @prompt
end
def cursor_start
@prompt.cursor_start if @focus == @prompt
end
def leave
@match_window.leave
end
def unload
@match_window.unload
end
def list_matches(options = {})
return unless @needs_update || options[:force]
@matches = @active_finder.sorted_matches_for(
@prompt.abbrev,
:case_sensitive => case_sensitive?,
:limit => match_limit,
:threads => CommandT::Util.processor_count
)
@match_window.matches = @matches
@needs_update = false
end
def tab_command
VIM::get_string('g:CommandTAcceptSelectionTabCommand') || 'tabe'
end
def split_command
VIM::get_string('g:CommandTAcceptSelectionSplitCommand') || 'sp'
end
def vsplit_command
VIM::get_string('g:CommandTAcceptSelectionVSplitCommand') || 'vs'
end
private
def scm_markers
markers = VIM::get_string('g:CommandTSCMDirectories')
markers = markers && markers.split(/\s*,\s*/)
markers = %w[.git .hg .svn .bzr _darcs] unless markers && markers.length
markers
end
def list_matches!
list_matches(:force => true)
end
def show
@initial_window = $curwin
@initial_buffer = $curbuf
@match_window = MatchWindow.new \
:highlight_color => VIM::get_string('g:CommandTHighlightColor'),
:match_window_at_top => VIM::get_bool('g:CommandTMatchWindowAtTop'),
:match_window_reverse => VIM::get_bool('g:CommandTMatchWindowReverse'),
:min_height => min_height,
:debounce_interval => VIM::get_number('g:CommandTInputDebounce') || 50,
:prompt => @prompt
@focus = @prompt
@prompt.focus
register_for_key_presses
set_up_autocmds
clear # clears prompt and lists matches
end
def max_height
@max_height ||= VIM::get_number('g:CommandTMaxHeight') || 0
end
def min_height
@min_height ||= begin
min_height = VIM::get_number('g:CommandTMinHeight') || 0
min_height = max_height if max_height != 0 && min_height > max_height
min_height
end
end
def case_sensitive?
if @prompt.abbrev.match(/[A-Z]/)
if VIM::exists?('g:CommandTSmartCase')
smart_case = VIM::get_bool('g:CommandTSmartCase')
else
smart_case = VIM::get_bool('&smartcase')
end
if smart_case
return true
end
end
if VIM::exists?('g:CommandTIgnoreCase')
return !VIM::get_bool('g:CommandTIgnoreCase')
end
false
end
# Backslash-escape space, \, |, %, #, "
def sanitize_path_string(str)
# for details on escaping command-line mode arguments see: :h :
# (that is, help on ":") in the Vim documentation.
str.gsub(/[ \\|%#"]/, '\\\\\0')
end
def current_buffer_visible_in_other_window
count = (0...::VIM::Window.count).to_a.inject(0) do |acc, i|
acc += 1 if ::VIM::Window[i].buffer.number == $curbuf.number
acc
end
count > 1
end
def default_open_command
if !VIM::get_bool('&modified') ||
VIM::get_bool('&hidden') ||
VIM::get_bool('&autowriteall') && !VIM::get_bool('&readonly') ||
current_buffer_visible_in_other_window
VIM::get_string('g:CommandTAcceptSelectionCommand') || 'e'
else
'sp'
end
end
def ensure_appropriate_window_selection
# normally we try to open the selection in the current window, but there
# is one exception:
#
# - we don't touch any "unlisted" buffer with buftype "nofile" (such as
# NERDTree or MiniBufExplorer); this is to avoid things like the "Not
# enough room" error which occurs when trying to open in a split in a
# shallow (potentially 1-line) buffer like MiniBufExplorer is current
#
# Other "unlisted" buffers, such as those with buftype "help" are treated
# normally.
initial = $curwin
while true do
break unless ::VIM::evaluate('&buflisted').to_i == 0 &&
::VIM::evaluate('&buftype').to_s == 'nofile'
::VIM::command 'wincmd w' # try next window
break if $curwin == initial # have already tried all
end
end
def open_selection(selection, options = {})
command = options[:command] || default_open_command
selection = File.expand_path selection, @path
selection = relative_path_under_working_directory selection
selection = sanitize_path_string selection
selection = File.join('.', selection) if selection =~ /^\+/
ensure_appropriate_window_selection
@active_finder.open_selection command, selection, options
end
def map(key, function, param = nil)
::VIM::command "noremap <silent> <buffer> #{key} " \
":call CommandT#{function}(#{param})<CR>"
end
def term
@term ||= ::VIM::evaluate('&term')
end
def register_for_key_presses
# "normal" keys (interpreted literally)
numbers = ('0'..'9').to_a.join
lowercase = ('a'..'z').to_a.join
uppercase = lowercase.upcase
punctuation = '<>`@#~!"$%&/()=+*-_.,;:?\\\'{}[] ' # and space
(numbers + lowercase + uppercase + punctuation).each_byte do |b|
map "<Char-#{b}>", 'HandleKey', b
end
# "special" keys (overridable by settings)
{
'AcceptSelection' => '<CR>',
'AcceptSelectionSplit' => ['<C-CR>', '<C-s>'],
'AcceptSelectionTab' => '<C-t>',
'AcceptSelectionVSplit' => '<C-v>',
'Backspace' => '<BS>',
'Cancel' => ['<C-c>', '<Esc>'],
'Clear' => '<C-u>',
'ClearPrevWord' => '<C-w>',
'CursorEnd' => '<C-e>',
'CursorLeft' => ['<Left>', '<C-h>'],
'CursorRight' => ['<Right>', '<C-l>'],
'CursorStart' => '<C-a>',
'Delete' => '<Del>',
'Quickfix' => '<C-q>',
'Refresh' => '<C-f>',
'SelectNext' => ['<C-n>', '<C-j>', '<Down>'],
'SelectPrev' => ['<C-p>', '<C-k>', '<Up>'],
'ToggleFocus' => '<Tab>',
}.each do |key, value|
if override = VIM::get_list_or_string("g:CommandT#{key}Map")
Array(override).each do |mapping|
map mapping, key
end
else
Array(value).each do |mapping|
unless mapping == '<Esc>' && term =~ /\A(screen|xterm|vt100)/
map mapping, key
end
end
end
end
end
def set_up_autocmds
::VIM::command 'augroup Command-T'
::VIM::command 'au!'
::VIM::command 'autocmd CursorHold <buffer> :call CommandTListMatches()'
::VIM::command 'augroup END'
end
# Returns the desired maximum number of matches, based on available vertical
# space and the g:CommandTMaxHeight option.
#
# Note the "available" space is actually a theoretical upper bound; it takes
# into account screen dimensions but not things like existing splits which
# may reduce the amount of space in practice.
def match_limit
limit = [1, VIM::Screen.lines - 5].max
limit = [limit, max_height].min if max_height > 0
limit
end
def buffer_finder
@buffer_finder ||= CommandT::Finder::BufferFinder.new
end
def mru_finder
@mru_finder ||= CommandT::Finder::MRUBufferFinder.new
end
def file_finder
@file_finder ||= CommandT::Finder::FileFinder.new nil,
:max_depth => VIM::get_number('g:CommandTMaxDepth'),
:max_files => VIM::get_number('g:CommandTMaxFiles'),
:max_caches => VIM::get_number('g:CommandTMaxCachedDirectories'),
:always_show_dot_files => VIM::get_bool('g:CommandTAlwaysShowDotFiles'),
:never_show_dot_files => VIM::get_bool('g:CommandTNeverShowDotFiles'),
:scan_dot_directories => VIM::get_bool('g:CommandTScanDotDirectories'),
:wild_ignore => VIM::get_string('g:CommandTWildIgnore'),
:scanner => VIM::get_string('g:CommandTFileScanner')
end
def jump_finder
@jump_finder ||= CommandT::Finder::JumpFinder.new
end
def tag_finder
@tag_finder ||= CommandT::Finder::TagFinder.new \
:include_filenames => VIM::get_bool('g:CommandTTagIncludeFilenames')
end
end # class Controller
end # module CommandT
| 28.784223 | 85 | 0.581896 |
bb6b9fc691ab8b56dee8c6aac78d04d2e2d1cd39 | 433 | require 'systemu'
module EmbulkRuby
class Embulk
extend EmbulkRuby
class << self
def exec command: "run", config: nil, bundler: nil
bundler = (bundler.nil? ? "" : "-b #{bundler}")
embulk = "#{path} #{command} #{config.to_s} #{bundler}"
Bundler.with_clean_env do
status, stdout, stderr = systemu embulk
[status, stdout, stderr]
end
end
end
end
end
| 25.470588 | 63 | 0.572748 |
ab34c2160a77951d7fff018599ce3d59250b9a5a | 26 | # include_recipe 'apache2' | 26 | 26 | 0.807692 |
03805216dc48d3d257237dfe0ea39eeb943ec91c | 702 | # frozen_string_literal: true
class Users::SessionsController < Devise::SessionsController
# before_action :configure_sign_in_params, only: [:create]
# GET /resource/sign_in
# def new
# super
# end
# POST /resource/sign_in
# def create
# super
# end
# DELETE /resource/sign_out
# def destroy
# super
# end
# protected
# If you have extra params to permit, append them to the sanitizer.
# def configure_sign_in_params
# devise_parameter_sanitizer.permit(:sign_in, keys: [:attribute])
# end
def destroy
sign_out(current_user)
redirect_to new_user_session_path
end
protected
def after_sign_in_path_for(_resource)
root_path
end
end
| 18.473684 | 69 | 0.709402 |
26855b2018fc420b1517064e5e0045833cf42cb1 | 1,843 | class FactsController < ApplicationController
before_action :set_fact, only: [:show, :edit, :update, :destroy]
# GET /facts
# GET /facts.json
def index
@facts = Fact.includes(:activity).limit(15)
end
# GET /facts/1
# GET /facts/1.json
def show
end
# GET /facts/new
def new
@fact = Fact.new
end
# GET /facts/1/edit
def edit
end
# POST /facts
# POST /facts.json
def create
@fact = Fact.new(fact_params)
respond_to do |format|
if @fact.save
format.html { redirect_to @fact, notice: 'Fact was successfully created.' }
format.json { render :show, status: :created, location: @fact }
else
format.html { render :new }
format.json { render json: @fact.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /facts/1
# PATCH/PUT /facts/1.json
def update
respond_to do |format|
if @fact.update(fact_params)
format.html { redirect_to @fact, notice: 'Fact was successfully updated.' }
format.json { render :show, status: :ok, location: @fact }
else
format.html { render :edit }
format.json { render json: @fact.errors, status: :unprocessable_entity }
end
end
end
# DELETE /facts/1
# DELETE /facts/1.json
def destroy
@fact.destroy
respond_to do |format|
format.html { redirect_to facts_url, notice: 'Fact was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_fact
@fact = Fact.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def fact_params
params.require(:fact).permit(:activity_id, :start_time, :end_time, :description)
end
end
| 24.573333 | 88 | 0.642973 |
ab6d5c1187a3f9709f9547f1f22e84c283c56659 | 1,355 | #!/usr/bin/env ruby
#
# Generate Go constants for standardized DHCP options from IANA web page.
#
require "open-uri"
require "nokogiri"
def rfc_name(rfc)
file = open("https://tools.ietf.org/html/rfc%d" % rfc)
doc = Nokogiri::XML.parse(file.read)
title = doc / 'title'
parts = title.inner_text.split(' - ', 2)
parts[1]
end
file = open("https://www.iana.org/assignments/bootp-dhcp-parameters/bootp-dhcp-parameters.xhtml")
doc = Nokogiri::XML.parse(file.read)
rfcs = {}
(doc / 'table#table-options tbody > tr').each do |tr|
cells = (tr / 'td').to_a
name = cells[1].inner_text
name = name.
split(/[\-\/ ]/).
map { |e|
if e == e.downcase
e.capitalize
else
e
end
}.
join
next if name =~ /unassigned/i
number = cells[0].inner_text.to_i
# Munge the "vendor-specific" part for these options
if name =~ /^PXEUndefined/
name = "PXEUndefined%d" % number
end
rfc = cells[4].inner_text[/RFC(\d+)/, 1].to_i
rfcs[rfc] ||= []
rfcs[rfc] << [name, number]
end
rfcs.keys.sort.each do |rfc|
# Skip RFC if it only contains >= 128 numbers
next if rfcs[rfc].all? { |(_, number)| number >= 128 }
puts "// From RFC%d: %s" % [rfc, rfc_name(rfc)]
puts "const ("
rfcs[rfc].each do |(name, number)|
puts "Option%s = Option(%d)" % [name, number]
end
puts ")"
puts
end
| 21.507937 | 97 | 0.611808 |
2106e86cc2a8fb46cd9caa080880369dda77c367 | 5,072 | #
# Be sure to run `pod spec lint HJAudioBubble.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
# ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# These will help people to find your library, and whilst it
# can feel like a chore to fill in it's definitely to your advantage. The
# summary should be tweet-length, and the description more in depth.
#
s.name = "HJAudioBubble"
s.version = "0.0.1"
s.summary = "简单的语音气泡视图."
# 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
简单的语音气泡视图
DESC
s.homepage = "https://github.com/WuHuijian/HJAudioBubbleDemo"
# s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif"
# ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Licensing your code is important. See http://choosealicense.com for more info.
# CocoaPods will detect a license file if there is a named LICENSE*
# Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'.
#
# s.license = "MIT"
s.license = { :type => "MIT", :file => "LICENSE" }
# ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the authors of the library, with email addresses. Email addresses
# of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also
# accepts just a name if you'd rather not provide an email address.
#
# Specify a social_media_url where others can refer to, for example a twitter
# profile URL.
#
s.author = { "WHJ" => "[email protected]" }
# Or just: s.author = "WHJ"
# s.authors = { "WHJ" => "[email protected]" }
# s.social_media_url = "http://twitter.com/WHJ"
# ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If this Pod runs only on iOS or OS X, then specify the platform and
# the deployment target. You can optionally include the target after the platform.
#
s.platform = :ios
# s.platform = :ios, "5.0"
# When using multiple platforms
# s.ios.deployment_target = "5.0"
# s.osx.deployment_target = "10.7"
# s.watchos.deployment_target = "2.0"
# s.tvos.deployment_target = "9.0"
# ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the location from where the source should be retrieved.
# Supports git, hg, bzr, svn and HTTP.
#
s.source = { :git => "https://github.com/WuHuijian/HJAudioBubbleDemo.git", :tag => "#{s.version}" }
# ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# CocoaPods is smart about how it includes source code. For source files
# giving a folder will include any swift, h, m, mm, c & cpp files.
# For header files it will include any header in the folder.
# Not including the public_header_files will make all headers public.
#
s.source_files = "HJAudioBubbleDemo/HJAudioBubble", "*.{h,m,xcassets}"
s.exclude_files = "Classes/Exclude"
# s.public_header_files = "Classes/**/*.h"
# ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# A list of resources included with the Pod. These are copied into the
# target bundle with a build phase script. Anything else will be cleaned.
# You can preserve files from being cleaned, please don't preserve
# non-essential files like tests, examples and documentation.
#
# s.resource = "icon.png"
# s.resources = "Resources/*.png"
# s.preserve_paths = "FilesToSave", "MoreFilesToSave"
# ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Link your library with frameworks, or libraries. Libraries do not include
# the lib prefix of their name.
#
# s.framework = "SomeFramework"
# s.frameworks = "SomeFramework", "AnotherFramework"
# s.library = "iconv"
# s.libraries = "iconv", "xml2"
# ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If your library depends on compiler flags you can set them in the xcconfig hash
# where they will only apply to your library. If you depend on other Podspecs
# you can include multiple dependencies to ensure it works.
# s.requires_arc = true
# s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
# s.dependency "JSONKit", "~> 1.4"
end
| 36.489209 | 107 | 0.589708 |
18acfc1eed2bc60a857aa657e30af097ceda7fcb | 1,484 | Gem::Specification.new do |s|
s.name = 'logstash-output-oss'
s.version = '0.1.1'
s.licenses = ['Apache-2.0']
s.summary = 'Sends Logstash events to the Aliyun Object Storage Service'
s.description = "This gem is a Logstash plugin required to be installed on top of the Logstash core pipeline using $LS_HOME/bin/logstash-plugin install gem-name. This gem is not a stand-alone program"
s.authors = ['jinhu.wu']
s.email = '[email protected]'
s.require_paths = ['lib']
s.homepage = "http://www.elastic.co/guide/en/logstash/current/index.html"
# Files
s.files = Dir['lib/**/*','spec/**/*','vendor/**/*','*.gemspec','*.md','CONTRIBUTORS','Gemfile','LICENSE','NOTICE.TXT']
# Tests
s.test_files = s.files.grep(%r{^(test|spec|features)/})
# Special flag to let us know this is actually a logstash plugin
s.metadata = { "logstash_plugin" => "true", "logstash_group" => "output" }
# Gem dependencies
s.add_runtime_dependency "logstash-core-plugin-api", "~> 2.0"
s.add_runtime_dependency "logstash-codec-plain", "~> 3.0"
s.add_runtime_dependency "concurrent-ruby", "~> 1.0"
s.add_runtime_dependency "uuid", '~> 2.3', '>= 2.3.9'
s.add_development_dependency "logstash-devutils", "~> 1.3"
s.add_development_dependency "logstash-codec-line", "~> 3.0"
s.platform = 'java'
s.add_runtime_dependency 'jar-dependencies', '~> 0.3'
s.requirements << 'jar com.aliyun.oss:aliyun-sdk-oss, 3.4.0'
end
| 47.870968 | 206 | 0.660377 |
28f62165cda82955953f120cf89cb01803a52f63 | 1,429 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'msfca/version'
Gem::Specification.new do |spec|
spec.name = "msfca"
spec.version = Msfca::VERSION
spec.authors = ["Wei Zhu"]
spec.email = ["[email protected]"]
spec.summary = "Ruby version MultiStage Faster Concepts Analysis"
spec.description = "Ruby version MultiStage Faster Concepts Analysis"
spec.homepage = "http://ibi.uky.edu/"
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
# to allow pushing to a single host or delete this section to allow pushing to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "http://rubygems.com"
else
raise "RubyGems 2.0 or newer is required to protect against " \
"public gem pushes."
end
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.13"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.0"
spec.add_dependency "activesupport", "~> 4.2.0"
spec.add_dependency "thor"
end
| 36.641026 | 96 | 0.664801 |
e91f93acae82cdfbd5ba008be875ca669152ee84 | 4,897 | require "language_pack"
require "pathname"
require "yaml"
require "digest/sha1"
require "language_pack/shell_helpers"
require "language_pack/cache"
require "language_pack/helpers/bundler_cache"
require "language_pack/metadata"
require "language_pack/fetcher"
require "language_pack/instrument"
Encoding.default_external = Encoding::UTF_8 if defined?(Encoding)
# abstract class that all the Ruby based Language Packs inherit from
class LanguagePack::Base
include LanguagePack::ShellHelpers
VENDOR_URL = ENV['BUILDPACK_VENDOR_URL'] || "https://s3-external-1.amazonaws.com/heroku-buildpack-ruby"
DEFAULT_LEGACY_STACK = "cedar"
attr_reader :build_path, :cache
# changes directory to the build_path
# @param [String] the path of the build dir
# @param [String] the path of the cache dir this is nil during detect and release
def initialize(build_path, cache_path=nil)
self.class.instrument "base.initialize" do
@build_path = build_path
@stack = ENV["STACK"]
@cache = LanguagePack::Cache.new(cache_path) if cache_path
@metadata = LanguagePack::Metadata.new(@cache)
@bundler_cache = LanguagePack::BundlerCache.new(@cache, @stack)
@id = Digest::SHA1.hexdigest("#{Time.now.to_f}-#{rand(1000000)}")[0..10]
@warnings = []
@deprecations = []
@fetchers = {:buildpack => LanguagePack::Fetcher.new(VENDOR_URL) }
Dir.chdir build_path
end
end
def instrument(*args, &block)
self.class.instrument(*args, &block)
end
def self.instrument(*args, &block)
LanguagePack::Instrument.instrument(*args, &block)
end
def self.===(build_path)
raise "must subclass"
end
# name of the Language Pack
# @return [String] the result
def name
raise "must subclass"
end
# list of default addons to install
def default_addons
raise "must subclass"
end
# config vars to be set on first push.
# @return [Hash] the result
# @not: this is only set the first time an app is pushed to.
def default_config_vars
raise "must subclass"
end
# process types to provide for the app
# Ex. for rails we provide a web process
# @return [Hash] the result
def default_process_types
raise "must subclass"
end
# this is called to build the slug
def compile
write_release_yaml
instrument 'base.compile' do
Kernel.puts ""
@warnings.each do |warning|
Kernel.puts "###### WARNING:"
puts warning
Kernel.puts ""
end
if @deprecations.any?
topic "DEPRECATIONS:"
puts @deprecations.join("\n")
end
end
end
def write_release_yaml
release = {}
release["addons"] = default_addons
release["config_vars"] = default_config_vars
release["default_process_types"] = default_process_types
FileUtils.mkdir("tmp") unless File.exists?("tmp")
File.open("tmp/heroku-buildpack-release-step.yml", 'w') do |f|
f.write(release.to_yaml)
end
unless File.exist?("Procfile")
msg = "No Procfile detected, using the default web server (webrick)\n"
msg << "https://devcenter.heroku.com/articles/ruby-default-web-server"
warn msg
end
end
# log output
# Ex. log "some_message", "here", :someattr="value"
def log(*args)
args.concat [:id => @id]
args.concat [:framework => self.class.to_s.split("::").last.downcase]
start = Time.now.to_f
log_internal args, :start => start
if block_given?
begin
ret = yield
finish = Time.now.to_f
log_internal args, :status => "complete", :finish => finish, :elapsed => (finish - start)
return ret
rescue StandardError => ex
finish = Time.now.to_f
log_internal args, :status => "error", :finish => finish, :elapsed => (finish - start), :message => ex.message
raise ex
end
end
end
private ##################################
# sets up the environment variables for the build process
def setup_language_pack_environment
end
def add_to_profiled(string)
FileUtils.mkdir_p "#{build_path}/.profile.d"
File.open("#{build_path}/.profile.d/ruby.sh", "a") do |file|
file.puts string
end
end
def set_env_default(key, val)
add_to_profiled "export #{key}=${#{key}:-#{val}}"
end
def set_env_override(key, val)
add_to_profiled %{export #{key}="#{val.gsub('"','\"')}"}
end
def log_internal(*args)
message = build_log_message(args)
%x{ logger -p user.notice -t "slugc[$$]" "buildpack-ruby #{message}" }
end
def build_log_message(args)
args.map do |arg|
case arg
when Float then "%0.2f" % arg
when Array then build_log_message(arg)
when Hash then arg.map { |k,v| "#{k}=#{build_log_message([v])}" }.join(" ")
else arg
end
end.join(" ")
end
end
| 28.306358 | 118 | 0.64611 |
6aa36c7f4f8ce83e14dc6a51ee70be5e68ab266b | 3,702 | # coding: utf-8
# vim: et ts=2 sw=2
RSpec.describe HrrRbSsh::Transport::ServerHostKeyAlgorithm::EcdsaSha2Nistp256 do
let(:name){ 'ecdsa-sha2-nistp256' }
it "can be looked up in HrrRbSsh::Transport::ServerHostKeyAlgorithm dictionary" do
expect( HrrRbSsh::Transport::ServerHostKeyAlgorithm[name] ).to eq described_class
end
it "is registered in HrrRbSsh::Transport::ServerHostKeyAlgorithm.list_supported" do
expect( HrrRbSsh::Transport::ServerHostKeyAlgorithm.list_supported ).to include name
end
it "appears in HrrRbSsh::Transport::ServerHostKeyAlgorithm.list_preferred" do
expect( HrrRbSsh::Transport::ServerHostKeyAlgorithm.list_preferred ).to include name
end
context "when secret_key is specified" do
let(:server_host_key_algorithm){ described_class.new secret_key }
let(:secret_key){
<<-'EOB'
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIB+8vCekxXfgw+Nz10ZykUGaI+X6ftdGG6b2UX2iz7oEoAoGCCqGSM49
AwEHoUQDQgAEt1em9ko6A2kZFFwVtKgQ0xpggZg17EJQmhFz7ObGNsZ8VIFEc0Hg
SpNC6qrqdhUfVAjsF9y5O/3Z/LGh/lNTig==
-----END EC PRIVATE KEY-----
EOB
}
describe '#server_public_host_key' do
it "returns encoded \"ecdsa-sha2-nistp256\" || \"nistp256\" || Q" do
encoded_server_public_host_key = \
"00000013" "65636473" "612d7368" "61322d6e" \
"69737470" "32353600" "0000086e" "69737470" \
"32353600" "00004104" "b757a6f6" "4a3a0369" \
"19145c15" "b4a810d3" "1a608198" "35ec4250" \
"9a1173ec" "e6c636c6" "7c548144" "7341e04a" \
"9342eaaa" "ea76151f" "5408ec17" "dcb93bfd" \
"d9fcb1a1" "fe53538a"
expect( server_host_key_algorithm.server_public_host_key ).to eq [encoded_server_public_host_key].pack("H*")
end
end
describe '#verify' do
let(:data){ 'testing' }
context "with correct sign" do
let(:sign){ server_host_key_algorithm.sign(data) }
it "returns true" do
expect( server_host_key_algorithm.verify sign, data ).to be true
end
end
context "with not \"ecdsa-sha2-nistp256\"" do
let(:encoded_data){
"00000013" "01234567" "01234567" "01234567" \
"01234567" "01234500" "00004900" "0000201b" \
"6866cc78" "bfca96b6" "fc5a2c3c" "7b576268" \
"28398e21" "137b945a" "bf62e288" "c4444b00" \
"00002100" "ad13b8c7" "5c7aa574" "42ca9e33" \
"ea992ea3" "34729c4b" "04d2af4d" "41b58de6" \
"1cc3c978"
}
let(:sign){ [encoded_data].pack("H*") }
it "returns false" do
expect( server_host_key_algorithm.verify sign, data ).to be false
end
end
context "with incorrect sign" do
let(:encoded_data){
"00000013" "65636473" "612d7368" "61322d6e" \
"69737470" "32353600" "00004900" "0000201b" \
"6866cc78" "bfca96b6" "fc5a2c3c" "7b576268" \
"28398e21" "137b945a" "bf62e288" "c4444b00" \
"00002100" "ad13b8c7" "5c7aa574" "42ca9e33" \
"ea992ea3" "34729c4b" "04d2af4d" "41b58de6" \
"01234567"
}
let(:sign){ [encoded_data].pack("H*") }
it "returns false" do
expect( server_host_key_algorithm.verify sign, data ).to be false
end
end
end
end
context "when secret_key is specified" do
let(:server_host_key_algorithm){ described_class.new }
describe '#verify' do
let(:data){ 'testing' }
context "with correct sign" do
let(:sign){ server_host_key_algorithm.sign(data) }
it "returns true" do
expect( server_host_key_algorithm.verify sign, data ).to be true
end
end
end
end
end
| 34.277778 | 116 | 0.640465 |
d5ad27878f219015c926adaede9315c77d3a0f06 | 2,984 | module Smartsheet
# Groups Endpoints
# @see https://smartsheet-platform.github.io/api-docs/?ruby#groups API Groups Docs
class Groups
attr_reader :client
private :client
def initialize(client)
@client = client
end
def create(body:, params: {}, header_overrides: {})
endpoint_spec = Smartsheet::API::EndpointSpec.new(:post, ['groups'], body_type: :json)
request_spec = Smartsheet::API::RequestSpec.new(
params: params,
header_overrides: header_overrides,
body: body
)
client.make_request(endpoint_spec, request_spec)
end
def delete(group_id:, params: {}, header_overrides: {})
endpoint_spec = Smartsheet::API::EndpointSpec.new(:delete, ['groups', :group_id])
request_spec = Smartsheet::API::RequestSpec.new(
params: params,
header_overrides: header_overrides,
group_id: group_id
)
client.make_request(endpoint_spec, request_spec)
end
def get(group_id:, params: {}, header_overrides: {})
endpoint_spec = Smartsheet::API::EndpointSpec.new(:get, ['groups', :group_id])
request_spec = Smartsheet::API::RequestSpec.new(
params: params,
header_overrides: header_overrides,
group_id: group_id
)
client.make_request(endpoint_spec, request_spec)
end
def list(params: {}, header_overrides: {})
endpoint_spec = Smartsheet::API::EndpointSpec.new(:get, ['groups'])
request_spec = Smartsheet::API::RequestSpec.new(
header_overrides: header_overrides,
params: params
)
client.make_request(endpoint_spec, request_spec)
end
def update(group_id:, body:, params: {}, header_overrides: {})
endpoint_spec = Smartsheet::API::EndpointSpec.new(:put, ['groups', :group_id], body_type: :json)
request_spec = Smartsheet::API::RequestSpec.new(
params: params,
header_overrides: header_overrides,
body: body,
group_id: group_id
)
client.make_request(endpoint_spec, request_spec)
end
def add_members(group_id:, body:, params: {}, header_overrides: {})
endpoint_spec = Smartsheet::API::EndpointSpec.new(:post, ['groups', :group_id, 'members'], body_type: :json)
request_spec = Smartsheet::API::RequestSpec.new(
params: params,
header_overrides: header_overrides,
body: body,
group_id: group_id
)
client.make_request(endpoint_spec, request_spec)
end
def remove_member(group_id:, user_id:, params: {}, header_overrides: {})
endpoint_spec = Smartsheet::API::EndpointSpec.new(:delete, ['groups', :group_id, 'members', :user_id])
request_spec = Smartsheet::API::RequestSpec.new(
params: params,
header_overrides: header_overrides,
group_id: group_id,
user_id: user_id
)
client.make_request(endpoint_spec, request_spec)
end
end
end | 35.52381 | 114 | 0.649464 |
9156323b229fd9a1f22c12e5bf920cd4a8dfc4bd | 530 | require 'spec_helper'
describe 'rsync::server::section' do
context 'supported operating systems' do
on_supported_os.each do |os, os_facts|
let(:title) { 'test' }
let(:facts) { os_facts }
let(:pre_condition) {
'include "::rsync::server"'
}
let(:params) {{
:path => '/test/dir'
}}
context "on #{os}" do
it { is_expected.to compile.with_all_deps }
it { is_expected.to create_concat__fragment("rsync_#{title}.section") }
end
end
end
end
| 21.2 | 79 | 0.583019 |
1a92598fc8a3025cb8805894f4643f99dacd8f9d | 1,844 | module Reek
module Cli
module Report
module Strategy
#
# Base class for report startegies.
# Each gathers results according to strategy chosen
#
class Base
attr_reader :report_formatter, :warning_formatter, :examiners
def initialize(report_formatter, warning_formatter, examiners)
@report_formatter = report_formatter
@warning_formatter = warning_formatter
@examiners = examiners
end
def summarize_single_examiner(examiner)
result = report_formatter.header examiner
if examiner.smelly?
formatted_list = report_formatter.format_list(examiner.smells,
warning_formatter)
result += ":\n#{formatted_list}"
end
result
end
end
#
# Lists out each examiner, even if it has no smell
#
class Verbose < Base
def gather_results
examiners.each_with_object([]) do |examiner, result|
result << summarize_single_examiner(examiner)
end
end
end
#
# Lists only smelly examiners
#
class Quiet < Base
def gather_results
examiners.each_with_object([]) do |examiner, result|
result << summarize_single_examiner(examiner) if examiner.smelly?
end
end
end
#
# Lists smells without summarization
# Used for yaml and html reports
#
class Normal < Base
def gather_results
examiners.each_with_object([]) { |examiner, smells| smells << examiner.smells }.
flatten
end
end
end
end
end
end
| 28.369231 | 92 | 0.546638 |
4a3d57d39ae7011c6eb9fe0a62ff469bea1cb206 | 588 | Pod::Spec.new do |s|
s.name = 'RKValueTransformers'
s.version = '1.1.0'
s.license = 'Apache2'
s.summary = 'A powerful value transformation API extracted from RestKit.'
s.homepage = 'https://github.com/RestKit/RKValueTransformers'
s.authors = { 'Blake Watters' => '[email protected]', 'Samuel E. Giddins' => '[email protected]' }
s.source = { :git => 'https://github.com/RestKit/RKValueTransformers.git', :tag => "v#{s.version}" }
s.source_files = 'Code'
s.requires_arc = true
s.ios.deployment_target = '5.0'
s.osx.deployment_target = '10.7'
end
| 39.2 | 111 | 0.670068 |
2181c11412ddd1aa9e80bc81cbf120e66e75e321 | 823 | # frozen_string_literal: true
# A module to include for easy access to the GitHub API
module ApiClient
extend ActiveSupport::Concern
def github_token
ENV["GITHUB_TOKEN"] || "<unknown>"
end
def github_client_id
ENV["GITHUB_CLIENT_ID"] || "<unknown-client-id>"
end
def github_client_secret
ENV["GITHUB_CLIENT_SECRET"] || "<unknown-client-secret>"
end
def github_api_endpoint
ENV["OCTOKIT_API_ENDPOINT"] || "https://api.github.com/"
end
def api
@api ||= Octokit::Client.new(access_token: github_token,
api_endpoint: github_api_endpoint)
end
def oauth_client_api
@oauth_client_api ||= Octokit::Client.new(
client_id: github_client_id,
client_secret: github_client_secret,
api_endpoint: github_api_endpoint
)
end
end
| 23.514286 | 67 | 0.688943 |
26900d7f19bd9a7a82b2451d80812c4e6edac29d | 1,330 | class Asciinema < Formula
desc "Record and share terminal sessions"
homepage "https://asciinema.org"
url "https://github.com/asciinema/asciinema/archive/v2.0.1.tar.gz"
sha256 "7087b247dae36d04821197bc14ebd4248049592b299c9878d8953c025ac802e4"
revision 1
head "https://github.com/asciinema/asciinema.git"
bottle do
cellar :any_skip_relocation
sha256 "d5beedf1dd255d1bc2793aee0d5ed024730f2c9162b4fa52680311371d0c9c11" => :mojave
sha256 "7673916f20d752ad61c5bc859fef8d5a4baec23e684b1bff0363fac3e789ae68" => :high_sierra
sha256 "7673916f20d752ad61c5bc859fef8d5a4baec23e684b1bff0363fac3e789ae68" => :sierra
sha256 "7673916f20d752ad61c5bc859fef8d5a4baec23e684b1bff0363fac3e789ae68" => :el_capitan
sha256 "128cbb4ea6c84202cd7d46a25e0c43278d21f99cf45b90c5f48cccbc186f9d69" => :x86_64_linux
end
depends_on "python"
def install
xy = Language::Python.major_minor_version "python3"
ENV.prepend_create_path "PYTHONPATH", libexec/"lib/python#{xy}/site-packages"
system "python3", *Language::Python.setup_install_args(libexec)
bin.install Dir[libexec/"bin/*"]
bin.env_script_all_files(libexec/"bin", :PYTHONPATH => ENV["PYTHONPATH"])
end
test do
ENV["LC_ALL"] = "en_US.UTF-8"
system "#{bin}/asciinema", "--version"
system "#{bin}/asciinema", "--help"
end
end
| 38 | 94 | 0.767669 |
0161ef3828d38aef0b4a9050a47a1d1685c25080 | 62 | module OmniAuth
module SAML
VERSION = '1.3.1'
end
end
| 10.333333 | 21 | 0.645161 |
03288ba45d917817dfe00fa2af84e70636e6f347 | 961 | require 'test_helper'
class SiteLayoutTest < ActionDispatch::IntegrationTest
def setup
@user = users(:michael)
end
test "layout links" do
get root_path
assert_template 'static_pages/home'
assert_select "a[href=?]", root_path, count: 2
assert_select "a[href=?]", help_path
assert_select "a[href=?]", about_path
assert_select "a[href=?]", contact_path
get contact_path
assert_select "title", full_title("Contact")
get signup_path
assert_select "title", full_title("Sign up")
end
test "layout links logged in user" do
log_in_as(@user)
get root_path
assert_template 'static_pages/home'
assert_select "a[href=?]", users_path
assert_select "a[href=?]", user_path(@user)
assert_select "a[href=?]", edit_user_path(@user)
assert_select "a[href=?]", logout_path
get user_path(@user)
assert_template 'users/show'
get edit_user_path
assert_template 'users/edit'
end
end
| 27.457143 | 54 | 0.695109 |
ac88f683e743769cac924bc9fcc94cd1dd7511e4 | 3,764 | require_relative '../test_helper'
module Batch
class CallbacksTest < Minitest::Test
# This job adds each callback as they run into an array
class BatchSlicesJob < RocketJob::Job
include RocketJob::Batch
field :call_list, type: Array, default: []
before_slice do
call_list << 'before_slice_block'
end
after_slice do
call_list << 'after_slice_block'
end
around_slice do |_job, block|
call_list << 'around_slice_block_before'
block.call
call_list << 'around_slice_block_after'
end
before_slice :before_slice_method
around_slice :around_slice_method
after_slice :after_slice_method
def perform(record)
call_list << "perform#{record}"
end
private
def before_slice_method
call_list << 'before_slice_method'
end
def around_slice_method
call_list << 'around_slice_method_before'
yield
call_list << 'around_slice_method_after'
end
def after_slice_method
call_list << 'after_slice_method'
end
end
# This job adds each callback as they run into an array
class BatchCallbacksJob < RocketJob::Job
include RocketJob::Batch
field :call_list, type: Array, default: []
before_batch do
call_list << 'before_batch_block'
end
after_batch do
call_list << 'after_batch_block'
end
before_batch :before_batch_method
before_batch :before_batch_method2
after_batch :after_batch_method
after_batch :after_batch_method2
def perform(record)
call_list << "perform#{record}"
end
private
def before_batch_method
call_list << 'before_batch_method'
end
def after_batch_method
call_list << 'after_batch_method'
end
def before_batch_method2
call_list << 'before_batch_method2'
end
def after_batch_method2
call_list << 'after_batch_method2'
end
end
describe RocketJob::Batch::Callbacks do
after do
@job.destroy if @job && [email protected]_record?
end
describe 'slice callbacks' do
it 'runs them in the right order' do
records = 7
@job = BatchSlicesJob.new(slice_size: 5)
@job.upload do |stream|
records.times.each { |i| stream << i }
end
@job.perform_now
assert @job.completed?, @job.attributes.ai
performs = records.times.collect { |i| "perform#{i}" }
befores = %w[before_slice_block around_slice_block_before before_slice_method around_slice_method_before]
afters = %w[after_slice_method around_slice_method_after around_slice_block_after after_slice_block]
expected = befores + performs[0..4] + afters + befores + performs[5..-1] + afters
assert_equal expected, @job.call_list, 'Sequence of slice callbacks is incorrect'
end
end
describe 'batch callbacks' do
it 'runs them in the right order' do
records = 7
@job = BatchCallbacksJob.new(slice_size: 5)
@job.upload do |stream|
records.times.each { |i| stream << i }
end
@job.perform_now
assert @job.completed?, @job.attributes.ai
performs = records.times.collect { |i| "perform#{i}" }
befores = %w[before_batch_block before_batch_method before_batch_method2]
afters = %w[after_batch_method2 after_batch_method after_batch_block]
expected = befores + performs + afters
assert_equal expected, @job.call_list, 'Sequence of batch callbacks is incorrect'
end
end
end
end
end
| 27.676471 | 116 | 0.633369 |
5d06ef123e95f69fe92c6cea86f72ee282c99787 | 250 | class Sign < Middleman::Extension
def initialize(app, **opts, &block)
super(app, **opts, &block)
end
#alias :included :registered
def after_build(builder)
builder.thor.run 'app/sign.sh'
end
end
::Middleman::Extensions.register(:sign, Sign)
| 20.833333 | 45 | 0.72 |
33fe3ffbf9a271326b5085dfc32caff0ca980253 | 1,053 | require File.join(File.dirname(__FILE__), 'spec_helper')
describe "Core Extensions" do
describe Hash do
describe "#to_params" do
def should_be_same_params(query_string, expected)
query_string.split(/&/).sort.should == expected.split(/&/).sort
end
it "should encode characters in URL parameters" do
{:q => "?&\" +"}.to_params.should == "q=%3F%26%22%20%2B"
end
it "should handle multiple parameters" do
should_be_same_params({:q1 => "p1", :q2 => "p2"}.to_params, "q1=p1&q2=p2")
end
it "should handle nested hashes like rails does" do
should_be_same_params({
:name => "Bob",
:address => {
:street => '111 Ruby Ave.',
:city => 'Ruby Central',
:phones => ['111-111-1111', '222-222-2222']
}
}.to_params, "name=Bob&address[city]=Ruby%20Central&address[phones][]=111-111-1111&address[phones][]=222-222-2222&address[street]=111%20Ruby%20Ave.")
end
end
end
end
| 33.967742 | 159 | 0.574549 |
bf52c39ac0536967c2dd391af5bde7299231b0f1 | 3,038 | #-- encoding: UTF-8
#-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2018 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2017 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
Given /^the [Uu]ser "([^\"]*)" is a "([^\"]*)" (?:in|of) the [Pp]roject "([^\"]*)"$/ do |user, role, project|
u = User.find_by_login(user)
r = Role.find_by(name: role)
p = Project.find_by(name: project) || Project.find_by(identifier: project)
as_admin do
Member.new.tap do |m|
m.user = u
m.roles << r
m.project = p
end.save!
end
end
Given /^there is a [rR]ole "([^\"]*)"$/ do |name, _table = nil|
FactoryBot.create(:role, name: name) unless Role.find_by(name: name)
end
Given /^there is a [rR]ole "([^\"]*)" with the following permissions:?$/ do |name, table|
FactoryBot.create(:role, name: name, permissions: table.raw.flatten) unless Role.find_by(name: name)
end
Given /^there are the following roles:$/ do |table|
table.raw.flatten.each do |name|
FactoryBot.create(:role, name: name) unless Role.find_by(name: name)
end
end
Given /^the [rR]ole "([^\"]*)" may have the following [rR]ights:$/ do |role, table|
r = Role.find_by(name: role)
raise "No such role was defined: #{role}" unless r
as_admin do
available_perms = Redmine::AccessControl.permissions.map(&:name)
r.permissions = []
table.raw.each do |_perm|
perm = _perm.first
unless perm.blank?
perm = perm.gsub(' ', '_').underscore.to_sym
if available_perms.include?(:"#{perm}")
r.add_permission! perm
end
end
end
r.save!
end
end
Given /^the [rR]ole "(.+?)" has no (?:[Pp]ermissions|[Rr]ights)$/ do |role_name|
role = Role.find_by(name: role_name)
raise "No such role was defined: #{role_name}" unless role
as_admin do
role.permissions = []
role.save!
end
end
Given /^the user "(.*?)" is a "([^\"]*?)"$/ do |user, role|
step %{the user "#{user}" is a "#{role}" in the project "#{get_project.name}"}
end
| 33.755556 | 109 | 0.673469 |
797d17eed4bb3623e22bbd017297742072ba471a | 6,831 | require 'logger'
require 'rubygems'
gem 'soap4r'
module Jira4R
class JiraTool
attr_accessor :enhanced
# Create a new JiraTool
#
# where:
# version ... the version of the SOAP API you wish to use - currently supported versions [ 2 ]
# base_url ... the base URL of the JIRA instance - eg. http://confluence.atlassian.com
def initialize(version, base_url)
@version = version
@base_url = base_url
@logger = Logger.new(STDERR)
@endpoint_url = "#{@base_url}/rpc/soap/jirasoapservice-v#{version}"
end
#Assign a new logger to the tool. By default a STDERR logger is used.
def logger=(logger)
@logger = logger
end
#Retrieve the driver, creating as required.
def driver()
if not @driver
@logger.info( "Connecting driver to #{@endpoint_url}" )
require "jira4r/v#{@version}/jiraService.rb"
require "jira4r/v#{@version}/JiraSoapServiceDriver.rb"
require "jira4r/v#{@version}/jiraServiceMappingRegistry.rb"
service_classname = "Jira4R::V#{@version}::JiraSoapService"
puts "Service: #{service_classname}"
service = eval(service_classname)
@driver = service.send(:new, @endpoint_url)
end
@driver
end
#Assign a wiredump file prefix to the driver.
def wiredump_file_base=(base)
driver().wiredump_file_base = base
end
#Login to the JIRA instance, storing the token for later calls.
#
#This is typically the first call that is made on the JiraTool.
def login(username, password)
@token = driver().login(username, password)
end
#Clients should avoid using the authentication token directly.
def token()
@token
end
#Call a method on the driver, adding in the authentication token previously determined using login()
def call_driver(method_name, *args)
@logger.debug("Finding method #{method_name}")
method = driver().method(method_name)
if args.length > 0
method.call(@token, *args)
else
method.call(@token)
end
end
#Retrieve a project without the associated PermissionScheme.
#This will be significantly faster for larger Jira installations.
#See: JRA-10660
def getProjectNoScheme(key)
puts "getProjectNoScheme is deprecated. Please call getProjectNoSchemes."
getProjectNoSchemes(key)
end
def getProjectNoSchemes(key)
self.getProjectsNoSchemes().find { |project| project.key == key }
end
def getProject(key)
#Jira > 3.10 has been patched to support this method directly as getProjectByKey
puts "Using deprecated JIRA4R API call getProject(key); replace with getProjectByKey(key)"
return getProjectByKey(key)
end
def getProjectByKey( projectKey )
begin
return call_driver( "getProjectByKey", projectKey )
rescue SOAP::FaultError => soap_error
#XXX surely there is a better way to detect this kind of condition in the JIRA server
if soap_error.faultcode.to_s == "soapenv:Server.userException" and soap_error.faultstring.to_s == "com.atlassian.jira.rpc.exception.RemoteException: Project: #{projectKey} does not exist"
return nil
else
raise soap_error
end
end
end
def getGroup( groupName )
begin
return call_driver( "getGroup", groupName )
rescue SOAP::FaultError => soap_error
#XXX surely there is a better way to detect this kind of condition in the JIRA server
if soap_error.faultcode.to_s == "soapenv:Server.userException" and soap_error.faultstring.to_s == "com.atlassian.jira.rpc.exception.RemoteValidationException: no group found for that groupName: #{groupName}"
return nil
else
raise soap_error
end
end
end
def getProjectRoleByName( projectRoleName )
getProjectRoles.each{ |projectRole|
return projectRole if projectRole.name == projectRoleName
}
end
def getPermissionScheme( permissionSchemeName )
self.getPermissionSchemes().each { |permission_scheme|
return permission_scheme if permission_scheme.name == permissionSchemeName
}
return nil
end
def getNotificationScheme( notificationSchemeName )
self.getNotificationSchemes().each { |notification_scheme|
return notification_scheme if notification_scheme.name == notificationSchemeName
}
return nil
end
def getPermission( permissionName )
if not @permissions
@permissions = self.getAllPermissions()
end
@permissions.each { |permission|
return permission if permission.name.downcase == permissionName.downcase
}
@logger.warn("No permission #{permissionName} found")
return nil
end
def findPermission(allowedPermissions, permissionName)
allowedPermissions.each { |allowedPermission|
#puts "Checking #{allowedPermission.name} against #{permissionName} "
return allowedPermission if allowedPermission.name == permissionName
}
return nil
end
def findEntityInPermissionMapping(permissionMapping, entityName)
permissionMapping.remoteEntities.each { |entity|
return entity if entity.name == entityName
}
return nil
end
#Removes entity
def setPermissions( permissionScheme, allowedPermissions, entity)
allowedPermissions = [ allowedPermissions ].flatten.compact
#Remove permissions that are no longer allowed
permissionScheme.permissionMappings.each { |mapping|
next unless findEntityInPermissionMapping(mapping, entity.name)
allowedPermission = findPermission(allowedPermissions, mapping.permission.name)
if allowedPermission
puts "Already has #{allowedPermission.name} in #{permissionScheme.name} for #{entity.name}"
allowedPermissions.delete(allowedPermission)
next
end
puts "Deleting #{mapping.permission.name} from #{permissionScheme.name} for #{entity.name}"
deletePermissionFrom( permissionScheme, mapping.permission, entity)
}
puts allowedPermissions.inspect
allowedPermissions.each { |allowedPermission|
puts "Granting #{allowedPermission.name} to #{permissionScheme.name} for #{entity.name}"
addPermissionTo(permissionScheme, allowedPermission, entity)
}
end
private
def fix_args(args)
args.collect { |arg|
if arg == nil
SOAP::SOAPNil.new
else
arg
end
}
end
def method_missing(method_name, *args)
args = fix_args(args)
call_driver(method_name, *args)
end
end
end
| 32.221698 | 215 | 0.669302 |
183f59b89e0c7bdc0bd865c7b0494d0833d04f1f | 3,387 | # Copyright, 2017, by Samuel G. D. Williams. <http://www.codeotaku.com>
#
# 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_relative 'edge'
module Graphviz
# Represents a visual node in the graph, which can be connected to other nodes.
class Node
# Initialize the node in the graph with the unique name.
# @param attributes [Hash] The associated graphviz attributes for this node.
def initialize(name, graph = nil, **attributes)
@name = name
@attributes = attributes
@connections = []
# This sets up the connection between the node and the parent.
@graph = nil
graph << self if graph
end
# Attach this node to the given graph:
def attach(parent)
@graph = parent
end
# @return [String] The unique name of the node.
attr :name
# @return [Array<Edge>] Any edges connecting to other nodes.
attr :connections
# @return [Hash] Any attributes specified for this node.
attr_accessor :attributes
# Create an edge between this node and the destination with the specified options.
# @param attributes [Hash] The associated graphviz attributes for the edge.
def connect(destination, attributes = {})
edge = Edge.new(@graph, self, destination, attributes)
@connections << edge
return edge
end
# Calculate if this node is connected to another. +O(N)+ search required.
def connected?(node)
return @connections.find{|edge| edge.destination == node}
end
# Add a node and #connect to it.
# @param attributes [Hash] The associated graphviz attributes for the new node.
def add_node(name = nil, **attributes)
node = @graph.add_node(name, **attributes)
connect(node)
return node
end
def identifier
@name
end
def dump_graph(buffer, indent, **options)
node_attributes_text = dump_attributes(@attributes)
node_name = dump_value(self.identifier)
buffer.puts "#{indent}#{node_name}#{node_attributes_text};"
end
def to_s
dump_value(@name)
end
# Dump the value to dot text format.
def dump_value(value)
if Symbol === value
value.to_s
else
value.inspect
end
end
# Dump the attributes to dot text format.
def dump_attributes(attributes)
if attributes.size > 0
"[" + attributes.collect{|name, value| "#{name}=#{dump_value(value)}"}.join(", ") + "]"
else
""
end
end
end
end
| 30.241071 | 91 | 0.710954 |
0866f81fe69d1ae897437284b1f3310783dce26a | 1,493 | title 'Tests to confirm libgpg-error library exists'
plan_origin = ENV['HAB_ORIGIN']
plan_name = input('plan_name', value: 'libgpg-error')
control 'core-plans-libgpg-error-library-exists' do
impact 1.0
title 'Ensure libgpg-error library exists'
desc '
Verify libgpg-error library by ensuring that
(1) its installation directory exists;
(2) the library exists;
(3) its pkgconfig metadata contains the expected version
'
plan_installation_directory = command("hab pkg path #{plan_origin}/#{plan_name}")
describe plan_installation_directory do
its('exit_status') { should eq 0 }
its('stdout') { should_not be_empty }
end
library_filename = input('library_filename', value: 'libgpg-error.so')
library_full_path = File.join(plan_installation_directory.stdout.strip, 'lib', library_filename)
describe file(library_full_path) do
it { should exist }
end
plan_pkg_ident = ((plan_installation_directory.stdout.strip).match /(?<=pkgs\/)(.*)/)[1]
plan_pkg_version = (plan_pkg_ident.match /^#{plan_origin}\/#{plan_name}\/(?<version>.*)\//)[:version]
pkgconfig_filename = input('pkgconfig_filename', value: 'gpg-error.pc')
pkgconfig_full_path = File.join(plan_installation_directory.stdout.strip, 'lib', 'pkgconfig', pkgconfig_filename)
describe command("cat #{pkgconfig_full_path}") do
its('exit_status') { should eq 0 }
its('stdout') { should_not be_empty }
its('stdout') { should match /Version:\s+#{plan_pkg_version}/ }
end
end | 40.351351 | 115 | 0.728064 |
7a4fd5c89db965f98a288de45beead8c143de39e | 553 | def power(x,n)
result = 1
while n.nonzero?
if n[0].nonzero?
result *= x
n -= 1
end
x *= x
n /= 2
end
return result
end
def f(x)
Math.sqrt(x.abs) + 5*x ** 3
end
(0...11).collect{ gets.to_i }.reverse.each do |x|
y = f(x)
puts "#{x} #{y.infinite? ? 'TOO LARGE' : y}"
end
# Map color names to short hex
COLORS = { :black => "000",
:red => "f00",
:green => "0f0",
:yellow => "ff0",
:blue => "00f",
:magenta => "f0f",
:cyan => "0ff",
| 18.433333 | 49 | 0.439421 |
3338ae21b792a4101561ca41cf8f25efcba6ecbf | 1,453 | module OmniAuthFixtures
def self.facebook_response
{provider: 'facebook',
uid: 10205522242159630,
info:
{email: '[email protected]',
name: 'Thomas Ochman',
image: 'http://graph.facebook.com/v2.6/10205522242159630/picture'},
credentials:
{token:
'EAAXC253O740BANfJYLjz2LCzT1UcfuEsoHpZBMAifdiud8sulF2LIfjDy5BeGiNPEPQjUn7xpvAu0neqnGeoCAvCU2KIucyP5sYNQDaDtCj06UmOF2POEq8ZAajS2zaQ4B7uIIRgv4p3wlACmh9f9MsMnDZB6gZD',
expires_at: 1517839337,
expires: true},
extra:
{raw_info:
{name: 'Thomas Ochman', email: '[email protected]', id: '10205522242159630'}}}
end
def self.facebook_response_without_email
{provider: 'facebook',
uid: 10205522242159630,
info:
{name: 'Thomas Ochman',
image: 'http://graph.facebook.com/v2.6/10205522242159630/picture'},
credentials:
{token:
'EAAXC253O740BANfJYLjz2LCzT1UcfuEsoHpZBMAifdiud8sulF2LIfjDy5BeGiNPEPQjUn7xpvAu0neqnGeoCAvCU2KIucyP5sYNQDaDtCj06UmOF2POEq8ZAajS2zaQ4B7uIIRgv4p3wlACmh9f9MsMnDZB6gZD',
expires_at: 1517839337,
expires: true},
extra:
{raw_info:
{name: 'Thomas Ochman', id: '10205522242159630'}}}
end
end | 40.361111 | 185 | 0.599449 |
e9bc34f1c013cf62786c18ed225b396ec8c14c71 | 476 | Shindo.tests("Storage[:atmos] | nested directories", ['atmos']) do
unless Fog.mocking?
@directory = Fog::Storage[:atmos].directories.create(:key => 'updatefiletests')
end
atmos = Fog::Storage[:atmos]
tests("update a file").succeeds do
pending if Fog.mocking?
file = @directory.files.create(:key => 'lorem.txt', :body => lorem_file)
file.body = "xxxxxx"
file.save
end
unless Fog.mocking?
@directory.destroy(:recursive => true)
end
end
| 23.8 | 83 | 0.661765 |
117d607693b90d2c42e1cea46518ba3493f1cb52 | 1,021 | # frozen_string_literal: false
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** Type: MMv1 ***
#
# ----------------------------------------------------------------------------
#
# This file is automatically generated by Magic Modules and manual
# changes will be clobbered when the file is regenerated.
#
# Please read more about how to change this file in README.md and
# CONTRIBUTING.md located at the root of this package.
#
# ----------------------------------------------------------------------------
module GoogleInSpec
module Container
module Property
class ClusterLegacyAbac
attr_reader :enabled
def initialize(args = nil, parent_identifier = nil)
return if args.nil?
@parent_identifier = parent_identifier
@enabled = args['enabled']
end
def to_s
"#{@parent_identifier} ClusterLegacyAbac"
end
end
end
end
end
| 29.171429 | 78 | 0.488737 |
7a09c396e114a12d2796c670002abef0c4935aa1 | 687 | # frozen_string_literal: false
#
# help.rb - helper using ri
# $Release Version: 0.9.6$
# $Revision$
#
# --
#
#
#
require 'rdoc/ri/driver'
require "irb/cmd/nop.rb"
# :stopdoc:
module IRB
module ExtendCommand
class Help<Nop
begin
Ri = RDoc::RI::Driver.new
rescue SystemExit
else
def execute(*names)
if names.empty?
Ri.interactive
return
end
names.each do |name|
begin
Ri.display_name(name.to_s)
rescue RDoc::RI::Error
puts $!.message
end
end
nil
end
end
end
end
end
# :startdoc:
| 15.976744 | 40 | 0.505095 |
b930e8c51d3ad2817a39d2e11f96e1619cd4f274 | 367 | require "bundler/setup"
require "exact_cover"
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
| 24.466667 | 66 | 0.754768 |
6a972aee3231bf609153494a80251188b6e3d96e | 8,503 | # Transaction mailer
#
# Responsible for:
# - transactions created
# - transaction status changes
# - reminders
#
include ApplicationHelper
include ListingsHelper
class TransactionMailer < ActionMailer::Base
include MailUtils
default :from => APP_CONFIG.sharetribe_mail_from_address
layout 'email'
include MoneyRails::ActionViewExtension # this is for humanized_money_with_symbol
add_template_helper(EmailTemplateHelper)
def transaction_preauthorized(transaction)
@transaction = transaction
@community = transaction.community
recipient = transaction.author
set_up_layout_variables(recipient, transaction.community)
with_locale(recipient.locale, transaction.community.locales.map(&:to_sym), transaction.community.id) do
payment_type = MarketplaceService::Community::Query.payment_type(@community.id)
gateway_expires = MarketplaceService::Transaction::Entity.authorization_expiration_period(payment_type)
expires = Maybe(transaction).booking.end_on.map { |booking_end|
MarketplaceService::Transaction::Entity.preauth_expires_at(gateway_expires.days.from_now, booking_end)
}.or_else(gateway_expires.days.from_now)
buffer = 1.minute # Add a small buffer (it might take a couple seconds until the email is sent)
expires_in = TimeUtils.time_to(expires + buffer)
premailer_mail(
mail_params(
@recipient,
@community,
t("emails.transaction_preauthorized.subject", requester: transaction.starter.name(@community), listing_title: transaction.listing.title))) do |format|
format.html {
render locals: {
payment_expires_in_unit: expires_in[:unit],
payment_expires_in_count: expires_in[:count]
}
}
end
end
end
def transaction_preauthorized_reminder(transaction)
@transaction = transaction
@community = transaction.community
recipient = transaction.author
set_up_layout_variables(recipient, transaction.community)
with_locale(recipient.locale, transaction.community.locales.map(&:to_sym), transaction.community.id) do
premailer_mail(
mail_params(
@recipient,
@community,
t("emails.transaction_preauthorized_reminder.subject", requester: transaction.starter.name(@community), listing_title: transaction.listing.title)))
end
end
# seller_model, buyer_model and community can be passed as params for testing purposes
def paypal_new_payment(transaction, seller_model = nil, buyer_model = nil, community = nil)
seller_model ||= Person.find(transaction[:listing_author_id])
buyer_model ||= Person.find(transaction[:starter_id])
community ||= Community.find(transaction[:community_id])
payment_total = transaction[:payment_total]
service_fee = Maybe(transaction[:charged_commission]).or_else(Money.new(0, payment_total.currency))
gateway_fee = transaction[:payment_gateway_fee]
prepare_template(community, seller_model, "email_about_new_payments")
with_locale(seller_model.locale, community.locales.map(&:to_sym), community.id) do
you_get = payment_total - service_fee - gateway_fee
unit_type = Maybe(transaction).select { |t| t[:unit_type].present? }.map { |t| ListingViewUtils.translate_unit(t[:unit_type], t[:unit_tr_key]) }.or_else(nil)
quantity_selector_label = Maybe(transaction).select { |t| t[:unit_type].present? }.map { |t| ListingViewUtils.translate_quantity(t[:unit_type], t[:unit_selector_tr_key]) }.or_else(nil)
premailer_mail(:to => seller_model.confirmed_notification_emails_to,
:from => community_specific_sender(community),
:subject => t("emails.new_payment.new_payment")) do |format|
format.html {
render "paypal_payment_receipt_to_seller", locals: {
conversation_url: person_transaction_url(seller_model, @url_params.merge(id: transaction[:id])),
listing_title: transaction[:listing_title],
price_per_unit_title: t("emails.new_payment.price_per_unit_type", unit_type: unit_type),
quantity_selector_label: quantity_selector_label,
listing_price: humanized_money_with_symbol(transaction[:listing_price]),
listing_quantity: transaction[:listing_quantity],
duration: transaction[:booking].present? ? transaction[:booking][:duration] : nil,
subtotal: humanized_money_with_symbol(transaction[:item_total]),
payment_total: humanized_money_with_symbol(payment_total),
shipping_total: humanized_money_with_symbol(transaction[:shipping_price]),
payment_service_fee: humanized_money_with_symbol(-service_fee),
paypal_gateway_fee: humanized_money_with_symbol(-gateway_fee),
payment_seller_gets: humanized_money_with_symbol(you_get),
payer_full_name: buyer_model.name(community),
payer_given_name: buyer_model.given_name_or_username,
}
}
end
end
end
# seller_model, buyer_model and community can be passed as params for testing purposes
def paypal_receipt_to_payer(transaction, seller_model = nil, buyer_model = nil, community = nil)
seller_model ||= Person.find(transaction[:listing_author_id])
buyer_model ||= Person.find(transaction[:starter_id])
community ||= Community.find(transaction[:community_id])
prepare_template(community, buyer_model, "email_about_new_payments")
with_locale(buyer_model.locale, community.locales.map(&:to_sym), community.id) do
unit_type = Maybe(transaction).select { |t| t[:unit_type].present? }.map { |t| ListingViewUtils.translate_unit(t[:unit_type], t[:unit_tr_key]) }.or_else(nil)
quantity_selector_label = Maybe(transaction).select { |t| t[:unit_type].present? }.map { |t| ListingViewUtils.translate_quantity(t[:unit_type], t[:unit_selector_tr_key]) }.or_else(nil)
premailer_mail(:to => buyer_model.confirmed_notification_emails_to,
:from => community_specific_sender(community),
:subject => t("emails.receipt_to_payer.receipt_of_payment")) { |format|
format.html {
render "payment_receipt_to_buyer", locals: {
conversation_url: person_transaction_url(buyer_model, @url_params.merge({:id => transaction[:id]})),
listing_title: transaction[:listing_title],
price_per_unit_title: t("emails.receipt_to_payer.price_per_unit_type", unit_type: unit_type),
quantity_selector_label: quantity_selector_label,
listing_price: humanized_money_with_symbol(transaction[:listing_price]),
listing_quantity: transaction[:listing_quantity],
duration: transaction[:booking].present? ? transaction[:booking][:duration] : nil,
subtotal: humanized_money_with_symbol(transaction[:item_total]),
shipping_total: humanized_money_with_symbol(transaction[:shipping_price]),
payment_total: humanized_money_with_symbol(transaction[:payment_total]),
recipient_full_name: seller_model.name(community),
recipient_given_name: seller_model.given_name_or_username,
automatic_confirmation_days: nil,
show_money_will_be_transferred_note: false
}
}
}
end
end
private
def premailer_mail(opts, &block)
premailer(mail(opts, &block))
end
# TODO Get rid of this method. Pass all data in local variables, not instance variables.
def prepare_template(community, recipient, email_type = nil)
@email_type = email_type
@community = community
@current_community = community
@recipient = recipient
@url_params = build_url_params(community, recipient)
@show_branding_info = !PlanService::API::Api.plans.get_current(community_id: community.id).data[:features][:whitelabel]
end
def mail_params(recipient, community, subject)
{
to: recipient.confirmed_notification_emails_to,
from: community_specific_sender(community),
subject: subject
}
end
def build_url_params(community, recipient, ref="email")
{
host: community.full_domain,
ref: ref,
locale: recipient.locale
}
end
end
| 45.962162 | 190 | 0.699753 |
2610ebd29ac7b708aa61a9fdd26a1f7fbd6d1c28 | 424 | require "test_helper"
describe Slop do
describe ".option_defined?" do
it "handles bad constant names" do
assert_equal false, Slop.option_defined?("Foo?Bar")
end
it "returns false if the option is not defined" do
assert_equal false, Slop.option_defined?("FooBar")
end
it "returns true if the option is defined" do
assert_equal true, Slop.option_defined?("String")
end
end
end
| 23.555556 | 57 | 0.693396 |
e92b8e825d3a1f1cb86f5593c77490edf335031a | 724 | RSpec.configure do |config|
config.before do
Wallaby.configuration.resources_controller.try(:clear)
Wallaby.configuration.clear
Wallaby::Map.clear
Wallaby::ModelAuthorizer.provider_name = nil
end
config.around :suite do |example|
Wallaby.configuration.resources_controller.try(:clear)
Wallaby.configuration.clear
Wallaby::Map.clear
Wallaby::ModelAuthorizer.provider_name = nil
const_before = Object.constants
example.run
const_after = Object.constants
(const_after - const_before).each do |const|
Object.send :remove_const, const
end
Wallaby.configuration.resources_controller.try(:clear)
Wallaby.configuration.clear
Wallaby::Map.clear
end
end
| 27.846154 | 58 | 0.743094 |
d58f6d3f1cc49dfb909babe724939d27900cedcb | 144 | class UserWithCustomMessage
include ActiveModel::Validations
attr_accessor :homepage
validates :homepage, url: { message: "wrong" }
end
| 18 | 48 | 0.770833 |
9106971af06f82e2338505c855263cd0023590a2 | 1,637 | class RaxmlNg < Formula
desc "RAxML Next Generation: faster, easier-to-use and more flexible"
homepage "https://sco.h-its.org/exelixis/web/software/raxml/"
url "https://github.com/amkozlov/raxml-ng.git",
:tag => "0.9.0",
:revision => "0a064e9a40f2e00828662795141659d946440c81"
bottle do
cellar :any
sha256 "3deb449ed9ce39343945ed4b003a8f0ed3caaf84cdd240e990f3a1262edaa1da" => :catalina
sha256 "5b99cd4e7bbc3b688dc32e73c728fc5ff9c1cd7f567e584523c418285de77cd0" => :mojave
sha256 "8e3e83381139bacde52257180a17a9928e6c9c0a833776b245925970570f1937" => :high_sierra
sha256 "1659ae7540aa047066312928b9fecbe3243b92e8b27d3442913c18b686820075" => :x86_64_linux
end
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "cmake" => :build
depends_on "libtool" => :build
depends_on "gmp"
depends_on "open-mpi"
uses_from_macos "bison" => :build
uses_from_macos "flex" => :build
resource "example" do
url "https://sco.h-its.org/exelixis/resource/download/hands-on/dna.phy"
sha256 "c2adc42823313831b97af76b3b1503b84573f10d9d0d563be5815cde0effe0c2"
end
def install
args = std_cmake_args + ["-DUSE_GMP=ON"]
mkdir "build" do
system "cmake", "..", *args
system "make", "install"
end
mkdir "build_mpi" do
ENV["CC"] = "mpicc"
ENV["CXX"] = "mpicxx"
system "cmake", "..", *args, "-DUSE_MPI=ON", "-DRAXML_BINARY_NAME=raxml-ng-mpi"
system "make", "install"
end
end
test do
testpath.install resource("example")
system "#{bin}/raxml-ng", "--msa", "dna.phy", "--start", "--model", "GTR"
end
end
| 32.74 | 94 | 0.695174 |
aceab72d96fd7bcd27b6bed18fe99e9ed527a974 | 1,696 | class Daemonize < Formula
desc "Run a command as a UNIX daemon"
homepage "https://software.clapper.org/daemonize/"
url "https://github.com/bmc/daemonize/archive/release-1.7.8.tar.gz"
sha256 "20c4fc9925371d1ddf1b57947f8fb93e2036eb9ccc3b43a1e3678ea8471c4c60"
license "BSD-3-Clause"
bottle do
cellar :any_skip_relocation
sha256 "a5c898ee425aecfb5c3d41e75da436ebbd44ad2fa343fa85b60573bd4fd8c7a7" => :catalina
sha256 "45a895642c3be14e888b66607c2a4567408657111686437a431a730358b2feea" => :mojave
sha256 "bc501e9e4ba9fd11390fa9749a7b9a38a70353edaf75499bd969c45921d06bfe" => :high_sierra
sha256 "d4d5109292158ef32eb73a37b9b6a037dcae620e234be945410ea927322bb998" => :sierra
sha256 "5e05991cf0462e4fe32dd70354d2520a378831d2b1c0fc2cf0b4fbca8dc85489" => :el_capitan
end
def install
system "./configure", "--disable-debug", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make"
system "make", "install"
end
test do
dummy_script_file = testpath/"script.sh"
output_file = testpath/"outputfile.txt"
pid_file = testpath/"pidfile.txt"
dummy_script_file.write <<~EOS
#!/bin/sh
echo "#{version}" >> "#{output_file}"
EOS
chmod 0700, dummy_script_file
system "#{sbin}/daemonize", "-p", pid_file, dummy_script_file
assert_predicate pid_file, :exist?,
"The file containing the PID of the child process was not created."
sleep(4) # sleep while waiting for the dummy script to finish
assert_predicate output_file, :exist?,
"The file which should have been created by the child process doesn't exist."
assert_match version.to_s, output_file.read
end
end
| 40.380952 | 93 | 0.735849 |
ed93b08ecdfb44814b67cf94215e8a1ce9a28901 | 1,021 | require "spec_helper"
describe "Flnt::Configuration" do
it "should have default values" do
expect(Flnt::Configuration()).to eq(
[
nil,
{
host: 'localhost',
port: 24224,
}
]
)
end
it "should be customized" do
Flnt::Configuration.configure do |c|
c.prefix = "foobar"
c.host = 'fluentd.example.jp'
c.port = 12345
end
expect(Flnt::Configuration()).to eq(
[
"foobar",
{
host: 'fluentd.example.jp',
port: 12345,
}
]
)
end
it "should be force to hook Flint.initialize!(true)" do
allow(Flnt).to receive(:initialized?).and_return(true)
expect(Fluent::Logger::FluentLogger).to receive(:open)
expect(Flnt).to receive(:Configuration)
Flnt::Configuration.configure do |c|
c.host = 'fluentd.example.jp'
end
end
after do
Flnt::Configuration.instance_eval do
@host = nil
@port = nil
@prefix = nil
end
end
end
| 19.634615 | 58 | 0.565132 |
1a35f153153cec773cb6525a8f83520e1e03c362 | 5,437 | describe Escort::Setup::Configuration::Generator do
let(:generator) {Escort::Setup::Configuration::Generator.new(setup)}
let(:setup) { Escort::SetupAccessor.new(app_configuration) }
describe "#default_data" do
subject {generator.default_data}
context "when basic configuration" do
let(:app_configuration) do
Escort::Setup::Dsl::Global.new do |app|
app.options do |opts|
opts.opt :option1, "option1", :short => :none, :long => '--option1', :type => :string
end
app.action do |options, arguments|
end
end
end
it("should have a user config") {subject[:user].should_not be_nil}
it("user config should be empty") {subject[:user].should be_empty}
it("shoud have a global config") {subject[:global].should_not be_nil}
it("global config should not be empty") {subject[:global].should_not be_empty}
it("should have a global commands config") {subject[:global][:commands].should_not be_nil}
it("global commands config should be empty") {subject[:global][:commands].should be_empty}
it("should have a global options config") {subject[:global][:options].should_not be_nil}
it("global options config should not be empty") {subject[:global][:options].should_not be_empty}
it("options config should have a key for configured option") {subject[:global][:options].keys.size.should == 1}
it("options config key for configured config should be nil when no default value") {subject[:global][:options][:option1].should be_nil}
context "and configured option has default value" do
let(:app_configuration) do
Escort::Setup::Dsl::Global.new do |app|
app.options do |opts|
opts.opt :option1, "option1", :short => :none, :long => '--option1', :type => :string, :default => "hello"
end
app.action do |options, arguments|
end
end
end
it("options config key for configured config should equal to default value") {subject[:global][:options][:option1].should == 'hello'}
end
end
context "when suite configuration" do
let(:app_configuration) do
Escort::Setup::Dsl::Global.new do |app|
app.options do |opts|
opts.opt :option1, "option1", :short => :none, :long => '--option1', :type => :string
end
app.command :command1, :aliases => [:c1, :com1] do |command|
command.options do |opts|
opts.opt :option2, "option2", :short => :none, :long => '--option2', :type => :string, :default => 'blah'
end
end
end
end
it("should have a global commands config") {subject[:global][:commands].should_not be_nil}
it("global commands config should be empty") {subject[:global][:commands].should_not be_empty}
it("command1 commands config should not be nil") {subject[:global][:commands][:command1][:commands].should_not be_nil}
it("command1 commands config should be empty") {subject[:global][:commands][:command1][:commands].should be_empty}
it("command1 options config should not be nil") {subject[:global][:commands][:command1][:options].should_not be_nil}
it("command1 options config should not be empty") {subject[:global][:commands][:command1][:options].should_not be_empty}
it("command1 options option value should be the same as default value") {subject[:global][:commands][:command1][:options][:option2].should == 'blah'}
end
context "when suite with sub commands configuration" do
let(:app_configuration) do
Escort::Setup::Dsl::Global.new do |app|
app.options do |opts|
opts.opt :option1, "option1", :short => :none, :long => '--option1', :type => :string
end
app.command :command1, :aliases => [:c1, :com1] do |command|
command.options do |opts|
opts.opt :option2, "option2", :short => :none, :long => '--option2', :type => :string, :default => 'blah'
end
command.command :sub_command1 do |command|
command.options do |opts|
opts.opt :option3, "option3", :short => :none, :long => '--option3', :type => :string, :default => 'yadda'
end
end
end
end
end
it("command1 commands config should not be nil") {subject[:global][:commands][:command1][:commands].should_not be_nil}
it("command1 commands config should not be empty") {subject[:global][:commands][:command1][:commands].should_not be_empty}
it("sub_command1 command config should not be nil") {subject[:global][:commands][:command1][:commands][:sub_command1][:commands].should_not be_nil}
it("sub_command1 command config should be empty") {subject[:global][:commands][:command1][:commands][:sub_command1][:commands].should be_empty}
it("sub_command1 options config should not be nil") {subject[:global][:commands][:command1][:commands][:sub_command1][:options].should_not be_nil}
it("sub_command1 options config should not be empty") {subject[:global][:commands][:command1][:commands][:sub_command1][:options].should_not be_empty}
it("sub_command1 options option value should be the same as default value") {subject[:global][:commands][:command1][:commands][:sub_command1][:options][:option3].should == 'yadda'}
end
end
end
| 53.303922 | 186 | 0.642634 |
87ad03bb9a03b91d4702c7e7d4b44bb640892f39 | 65 | class Instruction < ApplicationRecord
belongs_to :recipe
end
| 16.25 | 37 | 0.8 |
38dd19ae01881582726aed0afbb373d36b72b21e | 1,223 | module Specjour::RSpec::Runner
::RSpec.configuration.backtrace_exclusion_patterns << %r(lib/specjour/)
def self.run(spec, output)
Specjour.logger.debug '------------------in Specjour::Runner.run---------------'
Specjour.logger.debug spec
if spec.include?('--description')
location = spec.split('--description')[0]
full_description = spec.split('--description')[1]
args = ['--format=Specjour::RSpec::WorkerFormatter',location, "-e#{full_description}"]
else
args = ['--format=Specjour::RSpec::WorkerFormatter',spec]
end
Specjour.logger.debug "----rspec args=#{args}"
Specjour.logger.debug 'before rspec core run'
::RSpec::Core::Runner.run args, $stderr, output
Specjour.logger.debug 'after rspec core run'
ensure
Specjour.logger.debug 'in runner ensure'
clear_example_data
end
def self.clear_example_data
::RSpec.configuration.filter_manager = ::RSpec::Core::FilterManager.new
::RSpec.world.ordered_example_groups.clear
::RSpec.world.filtered_examples.clear
::RSpec.world.inclusion_filter.clear
::RSpec.world.exclusion_filter.clear
::RSpec.world.send(:instance_variable_set, :@line_numbers, nil)
end
end | 34.942857 | 93 | 0.68193 |
61492ce448c98a591a0f0ca8bd02d11b6b220e77 | 538 | # frozen_string_literal: true
module ActionView
module Template::Handlers
class Builder
class_attribute :default_format, default: :xml
def call(template)
require_engine
"xml = ::Builder::XmlMarkup.new(:indent => 2);" \
"self.output_buffer = xml.target!;" +
template.source +
";xml.target!;"
end
private
def require_engine # :doc:
@required ||= begin
require "builder"
true
end
end
end
end
end
| 20.692308 | 57 | 0.552045 |
87ed52cad59f0e1da3d92c4123ceffa77069153b | 146 | # frozen_string_literal: true
FactoryBot.define do
factory :partner_company do
name { 'Company Name' }
identity { 'P/ABCD' }
end
end
| 16.222222 | 29 | 0.691781 |
28300d09ef28869245769ba5edf543fb75c1dc31 | 561 | module Travis
module Yml
module Configs
module Model
class Job < Struct.new(:attrs)
def [](key)
attrs[key]
end
def stage
attrs[:stage] if attrs[:stage].is_a?(String)
end
def stage=(stage)
attrs[:stage] = stage
end
def allow_failure?
!!attrs[:allow_failure]
end
def allow_failure=(allow_failure)
attrs[:allow_failure] = allow_failure
end
end
end
end
end
end
| 18.7 | 56 | 0.486631 |
b9d1fe27942378d54fb1b4447d30a8c1349c17ff | 2,052 | #-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2015 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See doc/COPYRIGHT.rdoc for more details.
#++
require File.expand_path('../../../../../spec_helper', __FILE__)
describe 'api/experimental/work_packages/column_sums.api.rabl', type: :view do
before do
params[:format] = 'json'
assign(:column_sums, column_sums)
render
end
subject { response.body }
describe 'with no summed columns' do
let(:column_sums) { [] }
it { is_expected.to have_json_path('column_sums') }
it { is_expected.to have_json_size(0).at_path('column_sums') }
end
describe 'with 4 summed columns' do
let(:column_sums) { [45, 67, 12.99, 44444444444] }
it { is_expected.to have_json_path('column_sums') }
it { is_expected.to have_json_size(4).at_path('column_sums') }
it { is_expected.to have_json_type(Float).at_path('column_sums/2') }
it { is_expected.to have_json_type(Integer).at_path('column_sums/3') }
end
end
| 35.37931 | 91 | 0.730507 |
bbdb610635241496c4f65c68895687f3671e4115 | 1,037 | include_recipe "postgresql::server"
include_recipe "postgresql::client"
include_recipe "database::postgresql"
postgresql_connection_info = {:host => "localhost",
:port => node['postgresql']['config']['port'],
:username => 'postgres',
:password => node['postgresql']['password']['postgres']}
# create a postgresql database
postgresql_database node.fileops.database do
connection postgresql_connection_info
action :create
end
# create a postgresql user but grant no privileges
postgresql_database_user node['fileops']['database-user'] do
connection postgresql_connection_info
password node['fileops']['database-password']
action :create
end
# grant all privileges on all tables in foo db
postgresql_database_user node['fileops']['database-user'] do
connection postgresql_connection_info
database_name node.fileops.database
privileges [:all]
action :grant
#notifies :query, "postgresql_database[create postgis extension]"
end
| 33.451613 | 86 | 0.712633 |
6a599b80187fcf99e58983f7ad713e71a4964baa | 1,823 | # -*- coding: utf-8 -*- #
module Rouge
module Lexers
class Matlab < RegexLexer
desc "Matlab"
tag 'matlab'
aliases 'm'
filenames '*.m'
mimetypes 'text/x-matlab', 'application/x-matlab'
def self.analyze_text(text)
return 0.4 if text.match(/^\s*% /) # % comments are a dead giveaway
end
def self.keywords
@keywords = Set.new %w(
break case catch classdef continue else elseif end for function
global if otherwise parfor persistent return spmd switch try while
)
end
def self.builtins
load Pathname.new(__FILE__).dirname.join('matlab/builtins.rb')
self.builtins
end
state :root do
rule /\s+/m, Text # Whitespace
rule %r([{]%.*?%[}])m, Comment::Multiline
rule /%.*$/, Comment::Single
rule /([.][.][.])(.*?)$/ do
groups(Keyword, Comment)
end
rule /^(!)(.*?)(?=%|$)/ do |m|
token Keyword, m[1]
delegate Shell, m[2]
end
rule /[a-zA-Z][_a-zA-Z0-9]*/m do |m|
match = m[0]
if self.class.keywords.include? match
token Keyword
elsif self.class.builtins.include? match
token Name::Builtin
else
token Name
end
end
rule %r{[(){};:,\/\\\]\[]}, Punctuation
rule /~=|==|<<|>>|[-~+\/*%=<>&^|.]/, Operator
rule /(\d+\.\d*|\d*\.\d+)(e[+-]?[0-9]+)?/i, Num::Float
rule /\d+e[+-]?[0-9]+/i, Num::Float
rule /\d+L/, Num::Integer::Long
rule /\d+/, Num::Integer
rule /'/, Str::Single, :string
end
state :string do
rule /[^']+/, Str::Single
rule /''/, Str::Escape
rule /'/, Str::Single, :pop!
end
end
end
end
| 24.635135 | 76 | 0.487109 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.