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
|
---|---|---|---|---|---|
91a993688cec39143b51eff3e067107554fa3eea | 559 | class JekyllAlfredJson < Jekyll::Generator
safe true
def generate(site)
items = site.posts.docs
.sort_by { |post| -post.date.to_i }
.map do |post|
{
title: post.data['title'],
arg: URI.join(site.config['url'], post.url),
variables: {
filename: post.path,
liquid_link: "{% post_url #{post.basename_without_ext} %}"
}
}
end
File.open(File.join(site.source, 'alfred.json'), 'w') do |f|
f << JSON.pretty_generate(items: items)
end
end
end
| 24.304348 | 70 | 0.549195 |
fffd416a23643c80fd4c818bca27afaf3ab2ba85 | 443 | # Copyright (c) 2002 Cunningham & Cunningham, Inc.
# Released under the terms of the GNU General Public License version 2 or later.
require 'test/unit'
require 'test/column_fixture_test'
require 'test/file_runner_test'
require 'test/fit_server_test'
require 'test/fixture_test'
require 'test/fixture_loader_test'
#require 'test/framework_test'
require 'test/parse_test'
require 'test/scientific_double_test'
require 'test/type_adapter_test'
| 29.533333 | 80 | 0.810384 |
6a9b244841119876335c12f6ca2545f99b800631 | 759 | class Di < Formula
desc "Advanced df-like disk information utility"
homepage "https://gentoo.com/di/"
url "https://gentoo.com/di/di-4.44.tar.gz"
sha256 "963d00cadbf5a115ff31b31b0d6141be751c7b0a209e50990cb78e36d1a50320"
bottle do
cellar :any_skip_relocation
sha256 "24faa78ee9d622d8316595e38d19e5ba40da3d9cbc64942b969ec2675c2d1a5f" => :high_sierra
sha256 "bdf922a2d6b32c5c3bb7cacb3efac022eeec7fc2b923904cee17d0c0aded6550" => :sierra
sha256 "a8449b5fc5e3e28570f2311a3aa9a7a95beff6373b5e207ae64688773cc3e667" => :el_capitan
sha256 "cb9cd891f6d513bb6f4f064622a36a2a69ea3b945b023ea683411d53c8273233" => :yosemite
end
def install
system "make", "install", "prefix=#{prefix}"
end
test do
system "#{bin}/di"
end
end
| 33 | 93 | 0.781291 |
7ae09880c80b64d073d9f744bbab8cd8916de1c6 | 2,002 | class Mawk < Formula
desc "Interpreter for the AWK Programming Language"
homepage "https://invisible-island.net/mawk/"
url "https://invisible-mirror.net/archives/mawk/mawk-1.3.4-20200120.tgz"
sha256 "7fd4cd1e1fae9290fe089171181bbc6291dfd9bca939ca804f0ddb851c8b8237"
license "GPL-2.0"
livecheck do
url "https://invisible-mirror.net/archives/mawk/?C=M&O=D"
regex(/href=.*?mawk[._-]v?(\d+(?:\.\d+)+(?:-\d+)?)\.t/i)
end
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "e89f98de9fc8f169163166448a4e0850f844e07bbff01c91d7b2b8ae248968f5"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "506eea9d68d5300cd74b57f42cde86b21f405f644bf5ca61ec993fbb629ced01"
sha256 cellar: :any_skip_relocation, monterey: "5487bc82c7a29d0dde02e2b0a2d7b32e4be7480269a8963043420e24a967ef63"
sha256 cellar: :any_skip_relocation, big_sur: "a669698248dacc35f2d82547a846e9ba3fd47dc56c8176c407f73cb24156c775"
sha256 cellar: :any_skip_relocation, catalina: "03f9aa87a079b35b6f93813e4016e85d102c578d8b65f2f967b0b7c5c5d869ad"
sha256 cellar: :any_skip_relocation, mojave: "802b3592430ca644c6590acad265f45ac892fe47fb37732e678afac13f8cf1f0"
sha256 cellar: :any_skip_relocation, high_sierra: "d113f78e1c20c8bf86fcf5ce083e206aeca58ee857e7d0a3acb0158d2b01fb45"
sha256 cellar: :any_skip_relocation, x86_64_linux: "e6fade81fd45be1fea56283969f7ae1c8973c18e750c7a7240c2be0d9399a37b"
end
def install
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--prefix=#{prefix}",
"--disable-silent-rules",
"--with-readline=/usr/lib",
"--mandir=#{man}"
system "make", "install"
end
test do
mawk_expr = '/^mawk / {printf("%s-%s", $2, $3)}'
ver_out = shell_output("#{bin}/mawk -W version 2>&1 | #{bin}/mawk '#{mawk_expr}'")
assert_equal version.to_s, ver_out
end
end
| 50.05 | 123 | 0.706294 |
5dacb7b8b26573432fe2697ace63832eab9ccbc0 | 194 | class Vehicle::Car < ActiveRecord::Base
has_many :doors, :class_name => 'Vehicle::Door', :dependent => :destroy
has_one :engine, :class_name => 'Vehicle::Engine', :dependent => :destroy
end
| 38.8 | 75 | 0.701031 |
ffc70e656db581bd0ec5ce04017d7ab91ffe9154 | 907 | ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
require 'rails/test_help'
require "minitest/reporters"
Minitest::Reporters.use!
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
include ApplicationHelper
# Add more helper methods to be used by all tests here...
# Returns true if a test user is logged in.
def is_logged_in?
!session[:user_id].nil?
end
# Log in as a particular user.
def log_in_as(user)
session[:user_id] = user.id
end
end
class ActionDispatch::IntegrationTest
# Log in as a particular user.
def log_in_as(user, password: 'password', remember_me: '1')
post login_path, params: { session: { email: user.email,
password: password,
remember_me: remember_me } }
end
end | 28.34375 | 82 | 0.657111 |
1c02debd71a4af8cae86710e03fdb02bc206d7e5 | 726 | require_relative 'base'
module Capistrano::ZomatoDingtalk::Messaging
class Markdown < Base
def initialize(info)
@info = info || {}
end
def markdown_load(_action)
"# food@work:#{application} [#{branch}](#{release_path})\r\n\r\n**#{release_details[:name]}**\n\n###{release_details[:notes]}"
end
################################################################################
def markdown(action)
method = "message_for_#{action}"
respond_to?(method) && send(method)
end
def build_hash(action)
{
msgtype: 'markdown',
markdown: {
title: release_details[:name],
text: markdown_load(action)
}
}
end
end
end
| 23.419355 | 132 | 0.523416 |
795cc81a69c758af748aa95ae773ca61ded88426 | 322 | require 'test_helper'
class HomeControllerTest < ActionController::TestCase
test "should get index" do
get :index
assert_response :success
end
test "should get board" do
get :board
assert_response :success
end
test "should get donors" do
get :donors
assert_response :success
end
end
| 16.947368 | 53 | 0.71118 |
e2acae3e5f39e95236425cee21a569fa65f286dd | 7,647 | And(/^I tap on the "(.*?)" button$/) do |element|
case element.downcase
when 'hide keyboard'
ReusableFunction.hide_keyboard_option
when 'maybe later'
on(SignUpScreen).tap_maybe_later_btn
when 'add chat'
on(DMInboxScreen).tap_add_chat_btn
when 'see more'
on(StreamScreen).tap_see_more_btn
when 'done'
on(GlobalScreenElements).tap_done_btn
ReusableFunction.wait_for(15)
when 'action done'
on(GlobalScreenElements).tap_action_done_btn
when 'action next'
on(GlobalScreenElements).tap_action_next_btn
when 'send code'
on(GlobalScreenElements).tap_continue_btn
ReusableFunction.wait_for(10)
when 'continue'
on(GlobalScreenElements).tap_continue_btn
when 'edit profile'
step 'the "Find Out Who You Know on B/R" social promo is "shown"'
on(MyBRScreen).tap_mybr_edit_profile_btn
ReusableFunction.wait_for(10)
when 'invite'
ReusableFunction.wait_for(2)
begin
btn = find_element(:xpath, "//android.widget.Button[@text='Connect Contacts']")
ele = find_element(:xpath, "//android.widget.TextView[@text='Connect with your Squad']")
btn.click if ele.displayed?
rescue StandardError
on(FindFriendsScreen).tap_invite_btn
end
else
ReusableFunction.wait_for(10)
on(GlobalScreenElements).tap_general_button(element)
end
step 'the "Find Out Who You Know on B/R" social promo is "shown"'
end
And(/^I verify the "(.*?)" button$/) do |ele|
on(GlobalScreenElements).verify_btn_exist(ele)
end
Then(/^User should get "(.*?)" text status displayed$/) do |txt_status|
ReusableFunction.wait_for(3)
puts on(GlobalScreenElements).get_text_status
unless txt_status.eql?(on(GlobalScreenElements).get_text_status)
raise("Element #{txt_status} is not displayed.")
end
end
Then(/^I choose a "(.*?)" username for my account$/) do |username_status|
case username_status
when 'valid', 'new'
on(GlobalScreenElements).set_username_txtfield(ReusableFunction.generate_username)
when 'existing'
on(GlobalScreenElements).set_username_txtfield(TestData.use_data('credentials', 'registered_username'))
ReusableFunction.wait_for(2)
hide_keyboard
end
end
Then(/^I close the keyboard$/) do
hide_keyboard
end
# This is an Applitools Test
Then(/^I am redirected to the "(.*?)" screen$/) do |screen|
sleep 5
if ENV['PLATFORM_VERSION'] == '7.0' && ENV['DEVICE_NAME'] == 'Android GoogleAPI Emulator'
puts 'Running Android 7.0' # FIXME: Fails selenium connection (500) when running android7.0
else
MobileDriver.snap_eyes("Verify #{screen} Screen")
end
end
Then(/^User should get "(.*?)" text summary displayed$/) do |txt_summary|
# Returns only last 4 of string - Mainly used for phone number validation
num_str = txt_summary
last_four = num_str[-4..-1]
begin
# Used for verifying text summary if phone number
on(GlobalScreenElements).verify_text_summary(last_four)
rescue StandardError
# Used for verifying text summary if text content
on(GlobalScreenElements).verify_text_summary(txt_summary)
end
end
And(/^I tap on the save button$/) do
on(GlobalScreenElements).tap_save_btn
end
Then(/^the textview "(.*?)" is displayed$/) do |textview|
sleep 7
on(GlobalScreenElements).verify_textview_exist(textview)
end
Then(/^the textview "(.*?)" is not displayed$/) do |textview|
unless on(GlobalScreenElements).verify_textview_exist_tf(textview) == false; break; end
end
Then(/^the button "(.*?)" is displayed$/) do |button|
on(GlobalScreenElements).verify_btn_exist(button)
end
And(/^I verify the "(.*?)" button disabled$/) do |bttn|
on(GlobalScreenElements).verify_btn_disabled(bttn)
end
When(/^I tap on "(.*?)" textview$/) do |textview|
ReusableFunction.wait_for(7)
begin
unless on(GlobalScreenElements).verify_textview_exist(textview)
ReusableFunction.scroll_up
end
on(GlobalScreenElements).tap_textview(textview)
rescue StandardError
# Mentions upcase affect Android 7, 8
if on(GlobalScreenElements).verify_textview_exist(textview.upcase)
on(GlobalScreenElements).tap_textview(textview.upcase)
end
end
ReusableFunction.wait_for(7)
end
Then(/^I tap on the navigate back button$/) do
on(GlobalScreenElements).tap_navigate_up_btn
ReusableFunction.wait_for(5)
end
Then(/^I tap on the Close button$/) do
on(GlobalScreenElements).tap_close_tab_btn
ReusableFunction.wait_for(5)
end
And(/^I "(.*?)" the alert permission$/) do |option|
ReusableFunction.wait_for(3)
case option
when 'allow'
on(GlobalScreenElements).tap_allow_permission
when 'deny'
on(GlobalScreenElements).tap_deny_permission
end
end
Then(/^I scroll to "(.*?)"$/) do |text|
begin
ReusableFunction.scroll_to(text)
rescue StandardError
3.times { ReusableFunction.scroll_up }
end
end
And(/^I tap into the "(.*?)" textfield$/) do |textfield|
case textfield
when 'comment'
begin
on(CommentScreen).tap_comment_txtfield
rescue StandardError
ReusableFunction.scroll_up
on(CommentScreen).tap_comment_txtfield
end
end
end
And(/^I navigate back using device back button$/) do
back
sleep 5
end
# Taps on Checked Textview - PopUp Alert text1 Element
And(/^I tap on "(.*?)" from checked textview$/) do |txt|
find_element(:xpath, "//android.widget.CheckedTextView[@text='#{txt}']").click
end
# This is an Applitools Test
Then(/^the "(.*?)" screen is displayed$/) do |screen_name|
ReusableFunction.wait_for(7)
if on(GlobalScreenElements).verify_toolbar_title_exist? && on(GlobalScreenElements).get_toolbar_title == 'Notifications'
MobileDriver.snap_eyes('Verify Notification Screen')
on(GlobalScreenElements).tap_done_btn
end
MobileDriver.snap_eyes("Verify #{screen_name} Screen")
end
# This is an Applitools Test
Then(/^the "(.*?)" scores screen is displayed$/) do |sport|
if on(ScoresScreen).verify_scores_no_game
MobileDriver.snap_eyes("Verify No Games - #{sport} Today Screen")
else
begin
if !on(ScoresScreen).verify_seeall_standing_link_exist
MobileDriver.snap_eyes("Verify #{sport} Scores Screen")
elsif on(ScoresScreen).get_seeall_standing_link_txt == 'See All'
MobileDriver.snap_eyes("Verify #{sport} with SEE ALL Scores Screen")
elsif on(ScoresScreen).get_seeall_standing_link_txt == 'Standings'
MobileDriver.snap_eyes("Verify #{sport} with STANDINGS Scores Screen")
else
MobileDriver.snap_eyes("Verify #{sport} with STANDINGS Scores Screen")
end
rescue StandardError
puts 'No games yet'
end
end
end
And(/^I pull to refresh the stream$/) do
sleep 3
Appium::TouchAction.new.swipe(start_x: 619,
start_y: 356,
end_x: 640,
end_y: 1523).perform
end
Then(/^I print the page source$/) do
# for debug purpose
puts get_source
end
Then(/^I scroll down "(.*?)" time$/) do |x|
x.to_i.times {
Appium::TouchAction.new.swipe(start_x: 500,
start_y: 1400,
end_x: 500,
end_y: 400,
duration: 600).perform }
end
And(/^I tap on a GIF image$/) do
# This locator uses a class element finder
gifs = find_elements(:id, 'com.bleacherreport.android.teamstream:id/gif_image')
gifs[1].click
end
And(/^I add dodgeball team from my br$/) do
step 'I tap on the "my br" icon tab'
step 'I tap on the add button from my teams'
step 'I am redirected to choose my team'
sleep 10
step 'the "*New* Video Posts 📽" social promo is "shown"'
end | 30.959514 | 122 | 0.701582 |
acbe4ca0f86dad833de835660cf9ddff9ccf2480 | 1,330 | require 'test_helper'
class UsersLoginTest < ActionDispatch::IntegrationTest
def setup
@user = users(:chase)
end
test "login with invalid information followed by logout" do
get login_path
post login_path, params: { session: { email: @user.email,
password: 'password' } }
assert is_logged_in?
assert_redirected_to @user
follow_redirect!
assert_template 'users/show'
assert_select "a[href=?]", login_path, count: 0
assert_select "a[href=?]", logout_path
assert_select "a[href=?]", user_path(@user)
delete logout_path
assert_not is_logged_in?
assert_redirected_to root_url
# Simulate a user clicking logout in a second window.
delete logout_path
follow_redirect!
assert_select "a[href=?]", login_path
assert_select "a[href=?]", logout_path, count: 0
assert_select "a[href=?]", user_path(@user), count: 0
end
test "login with remembering" do
log_in_as(@user, remember_me: '1')
assert_not_empty cookies['remember_token']
end
test "login without remembering" do
# log in to set the cookie
log_in_as(@user, remember_me: '1')
# log in again and verify that the cookie is deleted
log_in_as(@user, remember_me: '0')
assert_empty cookies['remember_token']
end
end
| 30.227273 | 67 | 0.675188 |
bfd466be86f79353dbab99cbe6f1cff8acc73c8c | 4,096 | require 'rails_helper'
require 'tariff_synchronizer'
describe TariffSynchronizer::BaseUpdate do
include BankHolidaysHelper
before do
stub_holidays_gem_between_call
end
describe "#file_path" do
before do
allow(TariffSynchronizer).to receive(:root_path).and_return("data")
end
context "whe Chief Update" do
it "returns the concatenated path of where the file is" do
chief_update = build(:chief_update, filename: "hola_mundo.txt")
expect(chief_update.file_path).to eq("data/chief/hola_mundo.txt")
end
end
context "whe Taric Update" do
it "returns the concatenated path of where the file is" do
taric_update = build(:taric_update, filename: "hola_mundo.txt")
expect(taric_update.file_path).to eq("data/taric/hola_mundo.txt")
end
end
end
describe '.latest_applied_of_both_kinds' do
it "Makes the right sql query" do
expected_sql = %{SELECT DISTINCT ON ("update_type") "tariff_updates".* FROM "tariff_updates" WHERE ("state" = 'A') ORDER BY "update_type", "issue_date" DESC}
result = TariffSynchronizer::BaseUpdate.latest_applied_of_both_kinds.sql
expect(result).to eq(expected_sql)
end
it "returns only one record for each update_type" do
create_list :chief_update, 2, :applied
create_list :taric_update, 2, :applied
result = TariffSynchronizer::BaseUpdate.latest_applied_of_both_kinds.all
expect(result.size).to eq(2)
end
it "return only the most recen one of each update_type" do
date = Date.new(2016, 2, 6)
create :chief_update, :applied, issue_date: date
create :chief_update, :applied, issue_date: date - 1
result = TariffSynchronizer::BaseUpdate.latest_applied_of_both_kinds.all
expect(result.size).to eq(1)
expect(result.first.issue_date).to eq(date)
end
end
describe ".sync" do
it "Calls the download method for each date since the last issue_date to the current date" do
update = create :chief_update, :missing, issue_date: 1.day.ago
expect(TariffSynchronizer::ChiefUpdate).to receive(:download).with(update.issue_date)
expect(TariffSynchronizer::ChiefUpdate).to receive(:download).with(Date.current)
TariffSynchronizer::ChiefUpdate.sync
end
it "logs and send email about several missing updates in a row" do
create :chief_update, :missing, issue_date: 1.day.ago
create :chief_update, :missing, issue_date: 2.days.ago
create :chief_update, :missing, issue_date: 3.days.ago
allow(TariffSynchronizer::ChiefUpdate).to receive(:download)
tariff_synchronizer_logger_listener
TariffSynchronizer::ChiefUpdate.sync
expect(@logger.logged(:warn).size).to eq(1)
expect(@logger.logged(:warn).last).to eq("Missing 3 updates in a row for CHIEF")
expect(ActionMailer::Base.deliveries).to_not be_empty
email = ActionMailer::Base.deliveries.last
expect(email.subject).to include("Missing 3 CHIEF updates in a row")
expect(email.encoded).to include("Trade Tariff found 3 CHIEF updates in a row to be missing")
end
end
describe '#last_updates_are_missing?' do
context 'with weekends' do
before do
travel_to Date.parse('21-05-2017')
end
after do
travel_back
end
let!(:chief_update1) { create :chief_update, :missing, example_date: Date.current }
let!(:chief_update2) { create :chief_update, example_date: Date.yesterday }
it 'should return false' do
expect(described_class.send(:last_updates_are_missing?)).to be_falsey
end
end
context 'without weekends' do
before do
travel_to Date.parse('17-05-2017')
end
after do
travel_back
end
let!(:chief_update1) { create :chief_update, :missing, example_date: Date.current }
let!(:chief_update2) { create :chief_update, example_date: Date.yesterday }
it 'should return true' do
expect(described_class.send(:last_updates_are_missing?)).to be_truthy
end
end
end
end
| 34.711864 | 163 | 0.69873 |
ed689c790a3b33f01c61c456521c08ce6cab1afe | 552 | require File.expand_path(File.dirname(__FILE__) + "/spec_helper")
describe "simple cases:" do
before(:each) do
@sm = Statemachine::Statemachine.new
@sm.context = self
@count = 0
@proc = Proc.new {@count = @count + 1}
end
it "reset" do
Statemachine.build(@sm) { |s| s.trans :start, :blah, :end, @proc }
@sm.process_event(:blah)
@sm.reset
@sm.state.should equal(:start)
end
it "no proc in transition" do
Statemachine.build(@sm) { |s| s.trans :on, :flip, :off }
@sm.flip
end
end
| 20.444444 | 70 | 0.597826 |
d58dc63263d661b3935e296c0ee53e537642df61 | 1,455 | #!ruby
require 'yaml'
require_relative 'lib/bayonetta'
vertex_type = Hash::new { |hash, key| hash[key] = [] }
if File.exist?("vertex_type_database.yaml")
vertex_type.update YAML::load_file("vertex_type_database.yaml")
else
end
wmb_block = lambda { |name, f, fname|
begin
f.rewind
w = Bayonetta::WMBFile::load(f)
rescue
warn "could not open #{name} in #{fname}!"
next
end
vertex_type[[w.header.u_b, w.header.vertex_ex_data_size, w.header.vertex_ex_data]].push("#{fname}/#{name}")
}
if File::directory?(ARGV[0])
dats = Dir.glob("#{ARGV[0]}/**/*.dat")
dats.each { |path|
File::open(path, "rb") { |f|
begin
d = Bayonetta::DATFile::new(f)
rescue
warn "could not open #{path}!"
next
end
wmbs = d.each.collect.select { |name, df|
File.extname(name) == ".wmb"
}
scrs = d.each.collect.select { |name, df|
File.extname(name) == ".scr"
}
wmbs.each { |name, f|
wmb_block.call(name, f, path)
}
scrs.each { |name, sf|
begin
scr = Bayonetta::SCRFile::new(sf)
rescue
warn "could not open #{name}!"
next
end
scr.each_model.each_with_index { |f, i|
wmb_block.call(i, f, "#{path}/#{name}")
}
}
}
}
else
raise "Invalid directory #{ARGV[0]}!"
end
File::open("vertex_type_database.yaml", "w") { |f|
f.write YAML::dump( vertex_type )
}
| 23.852459 | 109 | 0.566323 |
1c70ff71cbb72f9c6cde08956ebfee9ae4d9a36a | 546 | # frozen_string_literal: true
require_dependency 'claims_api/json_marshal'
require_dependency 'claims_api/concerns/file_data'
module ClaimsApi
class SupportingDocument < ApplicationRecord
include FileData
belongs_to :auto_established_claim
validates :auto_established_claim_id, presence: true
alias_attribute :tracked_item_id, :id
def evss_claim_id
auto_established_claim.evss_id
end
def uploader
@uploader ||= ClaimsApi::SupportingDocumentUploader.new(auto_established_claim.id)
end
end
end
| 22.75 | 88 | 0.783883 |
e24c30627ccd847bf4c80bb18cd018e54df15579 | 1,952 | class Abyss < Formula
desc "Genome sequence assembler for short reads"
homepage "http://www.bcgsc.ca/platform/bioinfo/software/abyss"
url "https://github.com/bcgsc/abyss/releases/download/2.0.2/abyss-2.0.2.tar.gz"
sha256 "d87b76edeac3a6fb48f24a1d63f243d8278a324c9a5eb29027b640f7089422df"
revision 3
bottle do
cellar :any
sha256 "60bcabf8bd9ac360375dcdd6d0e1d91948afaa75a927db046451d56c5f98a9fc" => :high_sierra
sha256 "e9b510c1c7493d0e1cfe375f1b93ef8bd01b39530092fc90832fe8328e0bf96e" => :sierra
sha256 "89ba22f587e19cc562ae25ba3c5986fcc16b113df704268b01bd354feb55269f" => :el_capitan
sha256 "2636a8581593be78ccf31710792dbfabf5a50e05521f9742556d7c2cfff9185a" => :x86_64_linux
end
head do
url "https://github.com/bcgsc/abyss.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "multimarkdown" => :build
end
depends_on "boost" => :build
depends_on "google-sparsehash" => :build
depends_on "gcc"
depends_on "open-mpi"
fails_with :clang # no OpenMP support
resource("testdata") do
url "http://www.bcgsc.ca/platform/bioinfo/software/abyss/releases/1.3.4/test-data.tar.gz"
sha256 "28f8592203daf2d7c3b90887f9344ea54fda39451464a306ef0226224e5f4f0e"
end
def install
system "./autogen.sh" if build.head?
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}",
"--enable-maxk=128"
system "make", "install"
end
test do
testpath.install resource("testdata")
if OS.mac? || which("column")
system "#{bin}/abyss-pe", "k=25", "name=ts", "in=reads1.fastq reads2.fastq"
else
# Fix error: abyss-tabtomd: column: not found
system "#{bin}/abyss-pe", "unitigs", "scaffolds", "k=25", "name=ts", "in=reads1.fastq reads2.fastq"
end
system "#{bin}/abyss-fac", "ts-unitigs.fa"
end
end
| 34.857143 | 105 | 0.692111 |
b99af7352347c4cd475d6faf45425070711d14f1 | 2,923 | require "rails_helper"
RSpec.describe "/admin/volunteers", type: :request do
before(:each) do
sign_in create(:user, role: :admin)
end
let(:valid_attributes) do
attributes_for(:user)
end
let(:invalid_attributes) do
attributes_for(:user, email: "")
end
describe "GET /index" do
context "with format csv" do
it "generates the csv file" do
travel_to(Date.new(2021, 10, 14)) do
volunteer1 = create(:volunteer, first_name: "Zion", last_name: "Vandervort", email: "[email protected]", status: :inactive)
create(:support_ticket, requestor: volunteer1)
create(:support_ticket, requestor: volunteer1)
volunteer2 = create(:volunteer, first_name: "Sutton", last_name: "Faddel", email: "[email protected]")
create(:survey_response, volunteer: volunteer2, meeting_duration: build(:meeting_duration))
create(:survey_response, volunteer: volunteer2, meeting_duration: build(:meeting_duration))
create(:survey_response, volunteer: volunteer2, meeting_duration: nil)
create(:support_ticket, requestor: volunteer2)
get admin_volunteers_url, params: {format: :csv}
expect(response.header["Content-Type"]).to include "text/csv"
expect(response.headers["Content-Disposition"]).to include "attachment; filename=\"volunteers-2021-10-14.csv\""
expect(response.body).to eq <<~CSV
"Name","Email","Phone","Status","Last Seeen","Total Surveys Completed","Total Support Tickets Created"
"Zion Vandervort","[email protected]","","inactive","","0","2"
"Sutton Faddel","[email protected]","","active","2021-10-14 00:00:00 UTC","2","1"
CSV
end
end
end
end
describe "POST /create" do
context "with valid parameters" do
it "creates a new Volunteer" do
expect do
post admin_volunteers_path, params: {user: valid_attributes}
end.to change(User, :count).by(1)
end
it "redirects to the created volunteer" do
post admin_volunteers_url, params: {user: valid_attributes}
expect(response).to redirect_to(admin_volunteers_url)
end
end
context "with invalid parameters" do
it "does not create a new volunteer" do
expect do
post admin_volunteers_url, params: {user: invalid_attributes}
end.to change(User, :count).by(0)
end
it "renders a successful response" do
post admin_volunteers_url, params: {user: invalid_attributes}
expect(response).to be_successful
end
end
context "with invalid parameters" do
it "renders a successful response" do
volunteer = User.create! valid_attributes
patch admin_volunteer_url(volunteer), params: {user: invalid_attributes}
expect(response).to be_successful
end
end
end
end
| 35.646341 | 139 | 0.660965 |
61bed8d46b2ccad72d996fd3399940958caed141 | 4,242 | # encoding: utf-8
require File.expand_path('../../spec_helper.rb', __FILE__)
require 'frank/publish/ftptls'
describe Frank::Publish::FTPTLS do
let(:publisher) do
Frank::Publish::FTPTLS.new(Frank.publish) do |ftp|
ftp.username = 'my_username'
ftp.password = 'my_password'
ftp.hostname = 'ftp.example.com'
ftp.local_path = '/local/path'
ftp.remote_path = '/remote/path'
end
end
before(:all) do
Frank.bootstrap(File.join(File.dirname(__FILE__), 'template'))
end
describe '#initialize' do
it 'should set the correct values' do
publisher.username.should == 'my_username'
publisher.password.should == 'my_password'
publisher.hostname.should == 'ftp.example.com'
publisher.port.should == 21
publisher.local_path.should == '/local/path'
publisher.remote_path.should == 'remote/path'
end
it 'should remove any preceeding tilde and slash from the path' do
publisher = Frank::Publish::FTPTLS.new(Frank.publish) do |ftp|
ftp.remote_path = '~/my_backups/path'
end
publisher.remote_path.should == 'my_backups/path'
end
context 'when setting configuration defaults' do
end # context 'when setting configuration defaults'
end # describe '#initialize'
describe '#connection' do
let(:connection) { mock }
it 'should yield a connection to the remote server' do
Net::FTPTLS.expects(:open).with(
'ftp.example.com', 'my_username', 'my_password'
).yields(connection)
connection.expects(:passive=).with(true)
publisher.send(:connection) do |ftp|
ftp.should be(connection)
end
end
it 'should set the Net::FTP_PORT constant' do
publisher.port = 40
Net::FTPTLS.expects(:const_defined?).with(:FTP_PORT).returns(true)
Net::FTPTLS.expects(:send).with(:remove_const, :FTP_PORT)
Net::FTPTLS.expects(:send).with(:const_set, :FTP_PORT, 40)
Net::FTPTLS.expects(:open)
publisher.send(:connection)
end
end # describe '#connection'
describe '#transfer!' do
let(:connection) { mock }
let(:package) { mock }
let(:files) { ["file1", "file2", "subdir1/file3", "subdir2/file4"] }
let(:dirs) { ["subdir1", "subdir2"] }
let(:s) { sequence '' }
before do
publisher.stubs(:connection).yields(connection)
publisher.stubs(:files_to_transfer).returns(files)
publisher.stubs(:directories).returns(dirs)
end
it 'should transfer the files' do
# connection.expects(:chdir).in_sequence(s).with('remote/path')
#publisher.expects(:directories).in_sequence(s)
publisher.expects(:create_remote_path).in_sequence(s).with('remote/path/subdir1', connection)
publisher.expects(:create_remote_path).in_sequence(s).with('remote/path/subdir2', connection)
connection.expects(:put).in_sequence(s).with(
File.join('/local/path', 'file1'),
File.join('remote/path', 'file1')
)
connection.expects(:put).in_sequence(s).with(
File.join('/local/path', 'file2'),
File.join('remote/path', 'file2')
)
connection.expects(:put).in_sequence(s).with(
File.join('/local/path', 'subdir1/file3'),
File.join('remote/path', 'subdir1/file3')
)
connection.expects(:put).in_sequence(s).with(
File.join('/local/path', 'subdir2/file4'),
File.join('remote/path', 'subdir2/file4')
)
publisher.send(:transfer!)
end
end # describe '#transfer!'
describe '#create_remote_path' do
let(:connection) { mock }
let(:remote_path) { 'remote/folder/another_folder' }
let(:s) { sequence '' }
context 'while properly creating remote directories one by one' do
it 'should rescue any FTPPermErrors and continue' do
connection.expects(:mkdir).in_sequence(s).
with("remote").raises(Net::FTPPermError)
connection.expects(:mkdir).in_sequence(s).
with("remote/folder")
connection.expects(:mkdir).in_sequence(s).
with("remote/folder/another_folder")
expect do
publisher.send(:create_remote_path, remote_path, connection)
end.not_to raise_error
end
end
end
end
| 29.458333 | 99 | 0.647808 |
f7f839d66eb06d6da9b11ccb42739d3005f0610b | 1,226 | #
# MMMLoadable. Part of MMMTemple.
# Copyright (C) 2015-2020 MediaMonks. All rights reserved.
#
Pod::Spec.new do |s|
s.name = "MMMLoadable"
s.version = "1.5.4"
s.summary = "A simple model for async calculations"
s.description = "#{s.summary}."
s.homepage = "https://github.com/mediamonks/#{s.name}"
s.license = "MIT"
s.authors = "MediaMonks"
s.source = { :git => "https://github.com/mediamonks/#{s.name}.git", :tag => s.version.to_s }
s.ios.deployment_target = '11.0'
s.watchos.deployment_target = '3.0'
s.subspec 'ObjC' do |ss|
ss.source_files = [ "Sources/#{s.name}ObjC/*.{h,m}" ]
ss.dependency 'MMMCommonCore/ObjC'
ss.dependency 'MMMLog/ObjC'
ss.dependency 'MMMObservables/ObjC'
end
s.swift_versions = '4.2'
s.static_framework = true
s.pod_target_xcconfig = {
"DEFINES_MODULE" => "YES"
}
s.subspec 'Swift' do |ss|
ss.source_files = [ "Sources/#{s.name}/*.swift" ]
ss.dependency "#{s.name}/ObjC"
ss.dependency 'MMMCommonCore'
ss.dependency 'MMMLog'
ss.dependency 'MMMObservables'
end
s.test_spec 'Tests' do |ss|
ss.ios.deployment_target = '11.0'
ss.source_files = "Tests/*.{m,swift}"
end
s.default_subspec = 'ObjC', 'Swift'
end
| 26.085106 | 94 | 0.647635 |
bbd687b81e54c093b7636f6b6c9a6b077e723b90 | 1,763 | require "test_helper"
class UserTest < ActiveSupport::TestCase
def setup
@user = User.new(name: "Example User", email: "[email protected]",
password: "foobar", password_confirmation: "foobar")
end
test "should be valid" do
assert @user.valid?
end
test "name should be present" do
@user.name = ""
assert_not @user.valid?
end
test "email should be present" do
@user.email = " "
assert_not @user.valid?
end
test "name should not be too long" do
@user.name = "a" * 51
assert_not @user.valid?
end
test "email should not be too long" do
@user.email = "a" * 244 + "@example.com"
assert_not @user.valid?
end
test "email validation should reject invalid addresses" do
invalid_addresses = %w(user@example,com user_at_foo.org user.name@example.
foo@bar_baz.com foo@bar+baz.com)
invalid_addresses.each do |invalid_address|
@user.email = invalid_address
assert_not @user.valid?, "#{invalid_address.inspect} should be invalid"
end
end
test "email addresses should be unique" do
duplicate_user = @user.dup
duplicate_user.email = @user.email.upcase
@user.save
assert_not duplicate_user.valid?
end
test "email addresses should be saved as lower-case" do
mixed_case_email = "[email protected]"
@user.email = mixed_case_email
@user.save
assert_equal mixed_case_email.downcase, @user.reload.email
end
test "password should be present (nonblank)" do
@user.password = @user.password_confirmation = " " * 6
assert_not @user.valid?
end
test "password should have a minimum length" do
@user.password = @user.password_confirmation = "a" * 5
assert_not @user.valid?
end
end
| 26.712121 | 78 | 0.669314 |
e20a64e8f7a6f53fe4c5207b86e1ea0cffa51d94 | 3,184 | require 'sinatra'
require 'sinatra/contrib'
get '/' do
<<-EOHTML
<a href="/link">Link</a>
<a href="/form">Form</a>
<a href="/cookie">Cookie</a>
<a href="/link-template">Link template</a>
EOHTML
end
get '/link' do
<<-EOHTML
<a href="/link/straight#/?input=default">Link</a>
EOHTML
end
get '/link/straight' do
<<-EOHTML
<html>
<script>
function getQueryVariable(variable) {
var query = window.location.hash.split('?')[1];
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
}
</script>
<body>
<div id="container">
</div>
<script>
document.getElementById("container").innerHTML = getQueryVariable('input');
</script>
</body>
</html>
EOHTML
end
get '/link-template' do
<<-EOHTML
<a href="/link-template/straight#|input|default">Link</a>
EOHTML
end
get '/link-template/straight' do
<<-EOHTML
<html>
<script>
function getQueryVariable(variable) {
var splits = decodeURI(window.location.hash).split('|');
return splits[splits.indexOf( variable ) + 1];
}
</script>
<body>
<div id="container">
</div>
<script>
document.getElementById('container').innerHTML = getQueryVariable('input');
</script>
</body>
</html>
EOHTML
end
get '/form' do
<<-EOHTML
<a href="/form/straight">Form</a>
EOHTML
end
get '/form/straight' do
<<-EOHTML
<script>
function handleSubmit() {
document.getElementById("container").innerHTML =
document.getElementById("my-input").value;
}
</script>
<div id="container">
</div>
<form action="javascript:handleSubmit()">
<input id='my-input' value='default' />
</form>
EOHTML
end
get '/cookie' do
headers 'Set-Cookie' => 'input=value'
<<-EOHTML
<a href="/cookie/straight">Form</a>
EOHTML
end
get '/cookie/straight' do
<<-EOHTML
<body>
<div id='container'>
</div>
<script>
function getCookie( cname ) {
var name = cname + '=';
var ca = document.cookie.split(';');
for( var i = 0; i < ca.length; i++ ) {
var c = ca[i].trim();
if( c.indexOf( name ) == 0 ) {
return c.substring( name.length, c.length )
}
}
return '';
}
document.getElementById('container').innerHTML = getCookie('input');
</script>
</body>
EOHTML
end
| 23.761194 | 91 | 0.459485 |
ff4dae9e51cb508da370a744bb467709bb8eee42 | 1,322 | ActiveRecord::ConnectionAdapters::SchemaStatements.module_eval do
def initialize_schema_information_with_plugins
initialize_schema_information_without_plugins
begin
execute "CREATE TABLE #{Desert::PluginMigrations::Migrator.schema_info_table_name} (plugin_name #{type_to_sql(:string)}, version #{type_to_sql(:integer)})"
rescue ActiveRecord::StatementInvalid
# Schema has been initialized
end
end
alias_method_chain :initialize_schema_information, :plugins
def dump_schema_information_with_plugins
schema_information = []
dump = dump_schema_information_without_plugins
schema_information << dump if dump
begin
plugins = ActiveRecord::Base.connection.select_all("SELECT * FROM #{Desert::PluginMigrations::Migrator.schema_info_table_name}")
plugins.each do |plugin|
if (version = plugin['version'].to_i) > 0
plugin_name = ActiveRecord::Base.quote_value(plugin['plugin_name'])
schema_information << "INSERT INTO #{Desert::PluginMigrations::Migrator.schema_info_table_name} (plugin_name, version) VALUES (#{plugin_name}, #{version})"
end
end
rescue ActiveRecord::StatementInvalid
# No Schema Info
end
schema_information.join(";\n")
end
alias_method_chain :dump_schema_information, :plugins
end | 38.882353 | 165 | 0.747352 |
acc26652a6bc234417821c7911434eb876c812bb | 5,247 | require 'puppet'
require 'spec_helper'
require 'puppet_spec/compiler'
require 'unit/parser/methods/shared'
describe 'the collect method' do
include PuppetSpec::Compiler
before :each do
Puppet[:parser] = "future"
end
context "using future parser" do
context "in Ruby style should be callable as" do
it 'collect on an array (multiplying each value by 2)' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [1,2,3]
$a.collect {|$x| $x*2}.foreach {|$v|
file { "/file_$v": ensure => present }
}
MANIFEST
catalog.resource(:file, "/file_2")['ensure'].should == 'present'
catalog.resource(:file, "/file_4")['ensure'].should == 'present'
catalog.resource(:file, "/file_6")['ensure'].should == 'present'
end
it 'collect on a hash selecting keys' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = {'a'=>1,'b'=>2,'c'=>3}
$a.collect {|$x| $x[0]}.foreach {|$k|
file { "/file_$k": ensure => present }
}
MANIFEST
catalog.resource(:file, "/file_a")['ensure'].should == 'present'
catalog.resource(:file, "/file_b")['ensure'].should == 'present'
catalog.resource(:file, "/file_c")['ensure'].should == 'present'
end
it 'foreach on a hash selecting value' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = {'a'=>1,'b'=>2,'c'=>3}
$a.collect {|$x| $x[1]}.foreach {|$k|
file { "/file_$k": ensure => present }
}
MANIFEST
catalog.resource(:file, "/file_1")['ensure'].should == 'present'
catalog.resource(:file, "/file_2")['ensure'].should == 'present'
catalog.resource(:file, "/file_3")['ensure'].should == 'present'
end
end
context "handles data type corner cases" do
it "collect gets values that are false" do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [false,false]
$a.collect |$x| { $x }.each |$i, $v| {
file { "/file_$i.$v": ensure => present }
}
MANIFEST
catalog.resource(:file, "/file_0.false")['ensure'].should == 'present'
catalog.resource(:file, "/file_1.false")['ensure'].should == 'present'
end
it "collect gets values that are nil" do
Puppet::Parser::Functions.newfunction(:nil_array, :type => :rvalue) do |args|
[nil]
end
catalog = compile_to_catalog(<<-MANIFEST)
$a = nil_array()
$a.collect |$x| { $x }.each |$i, $v| {
file { "/file_$i.$v": ensure => present }
}
MANIFEST
catalog.resource(:file, "/file_0.")['ensure'].should == 'present'
end
it "collect gets values that are undef" do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [$does_not_exist]
$a.collect |$x = "something"| { $x }.each |$i, $v| {
file { "/file_$i.$v": ensure => present }
}
MANIFEST
catalog.resource(:file, "/file_0.")['ensure'].should == 'present'
end
end
context "in Java style should be callable as" do
shared_examples_for 'java style' do
it 'collect on an array (multiplying each value by 2)' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [1,2,3]
$a.collect |$x| #{farr}{ $x*2}.foreach |$v| #{farr}{
file { "/file_$v": ensure => present }
}
MANIFEST
catalog.resource(:file, "/file_2")['ensure'].should == 'present'
catalog.resource(:file, "/file_4")['ensure'].should == 'present'
catalog.resource(:file, "/file_6")['ensure'].should == 'present'
end
it 'collect on a hash selecting keys' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = {'a'=>1,'b'=>2,'c'=>3}
$a.collect |$x| #{farr}{ $x[0]}.foreach |$k| #{farr}{
file { "/file_$k": ensure => present }
}
MANIFEST
catalog.resource(:file, "/file_a")['ensure'].should == 'present'
catalog.resource(:file, "/file_b")['ensure'].should == 'present'
catalog.resource(:file, "/file_c")['ensure'].should == 'present'
end
it 'foreach on a hash selecting value' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = {'a'=>1,'b'=>2,'c'=>3}
$a.collect |$x| #{farr} {$x[1]}.foreach |$k|#{farr}{
file { "/file_$k": ensure => present }
}
MANIFEST
catalog.resource(:file, "/file_1")['ensure'].should == 'present'
catalog.resource(:file, "/file_2")['ensure'].should == 'present'
catalog.resource(:file, "/file_3")['ensure'].should == 'present'
end
end
describe 'without fat arrow' do
it_should_behave_like 'java style' do
let(:farr) { '' }
end
end
describe 'with fat arrow' do
it_should_behave_like 'java style' do
let(:farr) { '=>' }
end
end
end
end
it_should_behave_like 'all iterative functions argument checks', 'collect'
it_should_behave_like 'all iterative functions hash handling', 'collect'
end
| 34.071429 | 85 | 0.541262 |
1a16840543015bb4b1c2e748226455c21979b002 | 3,904 | # frozen_string_literal: true
require 'rails_helper'
# rubocop:disable Metrics/BlockLength
RSpec.describe Api::V1::PresentationsController, type: :controller do
let!(:demo) { create(:demo) }
let!(:slide_one) { create(:slide, :web, demo: demo) }
let(:json_body) { JSON.parse(response.body) }
let(:now) { Time.now }
describe 'POST #create' do
context 'with demo' do
let(:params) do
{ demo_id: demo.id }
end
it 'creates a presentation for the demo' do
expect { post :create, params: params }.to change { Presentation.count }.by(1)
end
context 'when presentation is created' do
let(:presentation) { demo.reload.presentations.last }
before do
post :create, params: params
end
it 'assigns presentation to actual demo' do
expect(presentation.id).to eq(json_body['id'])
end
it 'start_at is assigned' do
expect(presentation.start_at).not_to be_nil
end
it 'active slide is the first one' do
expect(presentation.active_slide_id).to eq(demo.slides.first.id)
end
it 'presented slides has first slide' do
expect(presentation.presented_slides.length).to eq(1)
end
it 'presented slides has start at and correct slide id' do
slides = presentation.presented_slides
expect(slides.first['id']).to eq(demo.slides.first.id)
expect(slides.first['start_at']).not_to be_nil
expect(slides.first['end_at']).to be_nil
end
end
end
end
describe 'PATCH #update' do
let!(:presentation) { create(:presentation, start_at: now, demo: demo) }
let(:params) { { id: presentation.id } }
before do
patch :update, params: params
end
context 'when stopping presentation, updating end time' do
let(:params) do
{
id: presentation.id,
presentation: {
end_at: true
}
}
end
it 'assigns an end_date' do
expect(presentation.reload.end_at).not_to be_nil
end
it 'returns amount of time' do
expect(json_body['time_spent']).not_to be_nil
expect(json_body['time_spent']).to eq('less than a minute')
end
end
context 'when updating active_slide' do
let(:slide_two) { create(:slide, :html, demo: demo) }
let(:params) do
{
id: presentation.id,
presentation: {
active_slide_id: slide_two.id
}
}
end
it 'active slide is changed' do
expect(presentation.reload.active_slide_id).to eq(slide_two.id)
end
it 'previous presented slide has end_time' do
slides = presentation.reload.presented_slides
first_slide = slides.select { |s| s['id'] == slide_one.id }.first
expect(first_slide['end_at']).not_to be_nil
expect(first_slide['time_spent']).not_to be_nil
end
it 'the next presented slide has start_at time' do
slides = presentation.reload.presented_slides
first_slide = slides.select { |s| s['id'] == slide_two.id }.first
expect(first_slide).not_to be_nil
expect(first_slide['start_at']).not_to be_nil
end
end
end
describe 'GET #show' do
let!(:presentation) { create(:presentation, start_at: now, demo: demo) }
let(:params) do
{
id: presentation.id
}
end
before do
get :show, params: params
end
it 'returns payload' do
expect(response).to be_successful
expect(json_body).not_to be_nil
end
context 'when there is no presentation http 404' do
let(:params) { { id: '3232' } }
it 'returns empty payload' do
expect(response).to be_successful
expect(json_body).to be_nil
end
end
end
end
# rubocop:enable Metrics/BlockLength
| 26.739726 | 86 | 0.613986 |
7af38706dedf3e01cef3cae2ce3ee052f239d4c5 | 329 | require_relative 'version'
module SugarRefinery
module StringOp
refine String do
def -(rem)
gsub( Regexp === rem ? rem : rem.to_s, '' )
end
def ^(pos)
pos = pos.to_i
if pos >= 0
self[pos..-1]
else
self[0...pos]
end
end
end
end
end
| 15.666667 | 51 | 0.483283 |
879390541afad6fe87d8ad31654a719e73bb1ea6 | 484 | require 'securerandom'
require 'base64'
require 'fluent/plugin/filter'
module Fluent::Plugin
class ElasticsearchGenidFilter < Filter
Fluent::Plugin.register_filter('elasticsearch_genid', self)
config_param :hash_id_key, :string, :default => '_hash'
def initialize
super
end
def configure(conf)
super
end
def filter(tag, time, record)
record[@hash_id_key] = Base64.strict_encode64(SecureRandom.uuid)
record
end
end
end
| 18.615385 | 70 | 0.696281 |
1dd1d63bdbc8ecb9e0f8209d4a52a8f3f0530698 | 148 | def fizzbuzz(int)
if int % 3 == 0 && int % 5 == 0
"FizzBuzz"
elsif int % 3 == 0
"Fizz"
elsif int % 5 == 0
"Buzz"
else
end
end
| 13.454545 | 33 | 0.486486 |
5d8a90d3d5b79688d8aae8920547b89d1db7005a | 1,432 | class Dcd < Formula
desc "Auto-complete program for the D programming language"
homepage "https://github.com/dlang-community/DCD"
url "https://github.com/dlang-community/DCD.git",
tag: "v0.13.4",
revision: "8dce131a8ec715382a104feed52d08a1aacdc960"
license "GPL-3.0-or-later"
head "https://github.com/dlang-community/dcd.git"
bottle do
sha256 cellar: :any_skip_relocation, big_sur: "3f78982cca3087697d53cf0e240dfcd8d601f9b25d80f01ad6ff237a1604ea16"
sha256 cellar: :any_skip_relocation, catalina: "4a77f9bb6025a0ea9c30372dad8bb548226100f81391340a39cdde29e9a9ae13"
sha256 cellar: :any_skip_relocation, mojave: "a6ad4603f6ca68b68be9ca7716875f38a537c3dea00f15dcfa8b4f0edbe9dc07"
sha256 cellar: :any_skip_relocation, x86_64_linux: "8708b3f07677556e9cc2214ca7aa8350615445a00d103c4107b4396236caced0" # linuxbrew-core
end
depends_on "dmd" => :build
def install
system "make"
bin.install "bin/dcd-client", "bin/dcd-server"
end
test do
port = free_port
# spawn a server, using a non-default port to avoid
# clashes with pre-existing dcd-server instances
server = fork do
exec "#{bin}/dcd-server", "-p", port.to_s
end
# Give it generous time to load
sleep 0.5
# query the server from a client
system "#{bin}/dcd-client", "-q", "-p", port.to_s
ensure
Process.kill "TERM", server
Process.wait server
end
end
| 34.926829 | 138 | 0.724162 |
03cbb6c58c7f0ab44cc84755db658f94d5de86bd | 1,595 | # frozen_string_literal: true
# The following comments fill some of the gaps in Solargraph's understanding of
# Rails apps. Since they're all in YARD, they get mapped in Solargraph but
# ignored at runtime.
#
# You can put this file anywhere in the project, as long as it gets included in
# the workspace maps. It's recommended that you keep it in a standalone file
# instead of pasting it into an existing one.
#
# @!parse
# class ActionController::Base
# include ActionController::MimeResponds
# include ActionController::Redirecting
# include ActionController::StrongParameters
# include AbstractController::Rendering
# extend ActiveSupport::Callbacks::ClassMethods
# extend AbstractController::Callbacks::ClassMethods
# end
# class ActiveRecord::Base
# extend ActiveRecord::QueryMethods
# extend ActiveRecord::FinderMethods
# extend ActiveRecord::Associations::ClassMethods
# extend ActiveRecord::Inheritance::ClassMethods
# include ActiveRecord::Persistence
# end
# @!override ActiveRecord::FinderMethods#find
# @overload find(id)
# @param id [Integer]
# @return [self]
# @overload find(list)
# @param list [Array]
# @return [Array<self>]
# @overload find(*args)
# @return [Array<self>]
# @return [self, Array<self>]
# @!override ActiveRecord::QueryMethods#where
# @overload where(str)
# @param str [String]
# @return [Class<self>]
# @overload where(list)
# @param list [Array]
# @return [Class<self>]
# @overload where(**options)
# @param options [Hash]
# @return [Class<self>]
| 33.93617 | 79 | 0.705956 |
1afeab17741b3ffaf78d6ddbe31a0058ad038d5b | 2,533 | # == Schema Information
#
# Table name: images
#
# id :integer not null, primary key
# caption :string(255)
# location :string(255)
# credit :string(255)
# original_file_name :string(255)
# original_content_type :string(255)
# original_file_size :integer
# original_updated_at :datetime
# created_at :datetime not null
# updated_at :datetime not null
# photographer_id :integer
#
require_dependency 'staff'
class Image < ActiveRecord::Base
Attributions = [
'? / The Chronicle',
'? / Chronicle File Photo',
'Photo Illustration by ?',
'Chronicle Graphic by ?',
]
File.open(Rails.root.join("config", "image_styles.yml")) do |file|
Image::Styles = YAML::load(file)
end
def self.styles
sizes = []
Image::Styles.each do |type, info|
sizes << [type, info['width'], info['height']]
info['sizes'].each do |width|
height = (width * info['height'] / info['width'].to_f).round
sizes << [type, width, height]
end
end
styles = sizes.map do |type, width, height|
["#{type}_#{width}x".to_sym, "#{width}x#{height}#"]
end
Hash[styles]
end
attr_accessible :attribution, :caption, :date, :location, :original, :credit,
:photographer_id
# Used in crop! method
attr_reader :crop_style, :crop_x, :crop_y, :crop_w, :crop_h
has_attached_file :original, styles: self.styles,
processors: [:cropper, :paperclip_optimizer]
process_in_background :original
default_value_for(:date) { Date.today }
default_value_for :attribution, Attributions[0]
validates :original, attachment_presence: true
validates :date, presence: true
has_many :articles
has_many :blog_posts, class_name: "Blog::Post"
has_many :posts
has_many :pages
has_many :staff, foreign_key: :headshot_id
belongs_to :photographer, class_name: "Staff"
self.per_page = 30
def crop!(style, x, y, w, h)
@crop_style, @crop_x, @crop_y, @crop_w, @crop_h = style, x, y, w, h
reprocess_style!(style)
end
def reprocess_style!(style)
info = Image::Styles[style]
styles = ([info['width']] + info['sizes']).map do |width|
"#{style}_#{width}x"
end
original.reprocess_without_delay!(*styles)
end
###
# Helper methods for rendering JSON
###
def thumbnail_url
original.url(:rectangle_183x)
end
end
# Necessary to avoid autoload namespacing conflict
require_dependency 'gallery/image'
| 26.663158 | 79 | 0.641532 |
b94cede1bdf4774fddba0a7d63ed829fbe84d5ca | 1,698 | class Zeek < Formula
desc "Network security monitor"
homepage "https://www.zeek.org"
url "https://github.com/zeek/zeek.git",
tag: "v4.0.0",
revision: "7b5263139e9909757c38dfca4c99abebf958df67"
license "BSD-3-Clause"
head "https://github.com/zeek/zeek.git"
bottle do
sha256 arm64_big_sur: "81402ea8773037c8e0a2230240309f12f6ea3814533e87caf15e92c6bb7e4b25"
sha256 big_sur: "dc97e1b05ee465a35da2cfd7fd8c3ff3bd8a229f57934f32e95d053021e73bd1"
sha256 catalina: "1113a1c88e878f05d17050b11e43b5d3db7debb3f2122d260040611fa99b332a"
sha256 mojave: "f6eae52e1144e2245654b36cf4bd668e75a385547c29d7039246fe1f4152bd62"
end
depends_on "bison" => :build
depends_on "cmake" => :build
depends_on "swig" => :build
depends_on "caf"
depends_on "geoip"
depends_on macos: :mojave
depends_on "[email protected]"
depends_on "[email protected]"
uses_from_macos "flex"
uses_from_macos "libpcap"
def install
mkdir "build" do
system "cmake", "..", *std_cmake_args,
"-DBROKER_DISABLE_TESTS=on",
"-DBUILD_SHARED_LIBS=on",
"-DINSTALL_AUX_TOOLS=on",
"-DINSTALL_ZEEKCTL=on",
"-DCAF_ROOT=#{Formula["caf"].opt_prefix}",
"-DOPENSSL_ROOT_DIR=#{Formula["[email protected]"].opt_prefix}",
"-DZEEK_ETC_INSTALL_DIR=#{etc}",
"-DZEEK_LOCAL_STATE_DIR=#{var}"
system "make", "install"
end
end
test do
assert_match "version #{version}", shell_output("#{bin}/zeek --version")
assert_match "ARP packet analyzer", shell_output("#{bin}/zeek --print-plugins")
end
end
| 34.653061 | 92 | 0.647821 |
62584b39cc1092c048e9d1f5e10ef91d34000301 | 504 | # frozen_string_literal: true
require 'bundler/setup'
require 'rubybrainz'
require 'vcr'
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
VCR.configure do |c|
c.cassette_library_dir = 'spec/cassettes'
c.hook_into :webmock
end
| 21.913043 | 66 | 0.753968 |
f8b897f48479527184bdefa291b60a2a167af892 | 790 | class Api::V1::SessionsController < ApplicationController
include CurrentUserConcern
def create
user = User.find_by(email: params['user']['email'])
if user.present? && user.authenticate(params['user']['password'])
session[:user_id] = user.id
render json: {
status: :created,
logged_in: true,
user: user,
favorites: user.trips
}
else
render json: { message: 'Wrong email or password.' }, status: :unprocessable_entity
end
end
def logged_in
if @current_user
render json: @current_user, serializer: UserSerializer
else
render json: {
logged_in: false
}
end
end
def logout
reset_session
render json: {
status: 200,
logged_out: true
}
end
end
| 20.789474 | 89 | 0.616456 |
6aa264d766625f7df48b8281854a6ecb9a01ee3d | 5,935 | module ActiveRecord
module ConnectionAdapters
module PostgreSQL
module DatabaseStatements
def explain(arel, binds = [])
sql = "EXPLAIN #{to_sql(arel, binds)}"
PostgreSQL::ExplainPrettyPrinter.new.pp(exec_query(sql, 'EXPLAIN', binds))
end
def select_value(arel, name = nil, binds = [])
arel, binds = binds_from_relation arel, binds
sql = to_sql(arel, binds)
execute_and_clear(sql, name, binds) do |result|
result.getvalue(0, 0) if result.ntuples > 0 && result.nfields > 0
end
end
def select_values(arel, name = nil, binds = [])
arel, binds = binds_from_relation arel, binds
sql = to_sql(arel, binds)
execute_and_clear(sql, name, binds) do |result|
if result.nfields > 0
result.column_values(0)
else
[]
end
end
end
# Executes a SELECT query and returns an array of rows. Each row is an
# array of field values.
def select_rows(sql, name = nil, binds = [])
execute_and_clear(sql, name, binds) do |result|
result.values
end
end
# The internal PostgreSQL identifier of the money data type.
MONEY_COLUMN_TYPE_OID = 790 #:nodoc:
# The internal PostgreSQL identifier of the BYTEA data type.
BYTEA_COLUMN_TYPE_OID = 17 #:nodoc:
# create a 2D array representing the result set
def result_as_array(res) #:nodoc:
# check if we have any binary column and if they need escaping
ftypes = Array.new(res.nfields) do |i|
[i, res.ftype(i)]
end
rows = res.values
return rows unless ftypes.any? { |_, x|
x == BYTEA_COLUMN_TYPE_OID || x == MONEY_COLUMN_TYPE_OID
}
typehash = ftypes.group_by { |_, type| type }
binaries = typehash[BYTEA_COLUMN_TYPE_OID] || []
monies = typehash[MONEY_COLUMN_TYPE_OID] || []
rows.each do |row|
# unescape string passed BYTEA field (OID == 17)
binaries.each do |index, _|
row[index] = unescape_bytea(row[index])
end
# If this is a money type column and there are any currency symbols,
# then strip them off. Indeed it would be prettier to do this in
# PostgreSQLColumn.string_to_decimal but would break form input
# fields that call value_before_type_cast.
monies.each do |index, _|
data = row[index]
# Because money output is formatted according to the locale, there are two
# cases to consider (note the decimal separators):
# (1) $12,345,678.12
# (2) $12.345.678,12
case data
when /^-?\D+[\d,]+\.\d{2}$/ # (1)
data.gsub!(/[^-\d.]/, '')
when /^-?\D+[\d.]+,\d{2}$/ # (2)
data.gsub!(/[^-\d,]/, '').sub!(/,/, '.')
end
end
end
end
# Queries the database and returns the results in an Array-like object
def query(sql, name = nil) #:nodoc:
log(sql, name) do
result_as_array @connection.async_exec(sql)
end
end
# Executes an SQL statement, returning a PGresult object on success
# or raising a PGError exception otherwise.
# Note: the PGresult object is manually memory managed; if you don't
# need it specifically, you many want consider the exec_query wrapper.
def execute(sql, name = nil)
log(sql, name) do
@connection.async_exec(sql)
end
end
def exec_query(sql, name = 'SQL', binds = [], prepare: false)
execute_and_clear(sql, name, binds, prepare: prepare) do |result|
types = {}
fields = result.fields
fields.each_with_index do |fname, i|
ftype = result.ftype i
fmod = result.fmod i
types[fname] = get_oid_type(ftype, fmod, fname)
end
ActiveRecord::Result.new(fields, result.values, types)
end
end
def exec_delete(sql, name = 'SQL', binds = [])
execute_and_clear(sql, name, binds) {|result| result.cmd_tuples }
end
alias :exec_update :exec_delete
def sql_for_insert(sql, pk, id_value, sequence_name, binds) # :nodoc:
unless pk
# Extract the table from the insert sql. Yuck.
table_ref = extract_table_ref_from_insert_sql(sql)
pk = primary_key(table_ref) if table_ref
end
if pk && use_insert_returning?
sql = "#{sql} RETURNING #{quote_column_name(pk)}"
end
super
end
def exec_insert(sql, name, binds, pk = nil, sequence_name = nil)
val = exec_query(sql, name, binds)
if !use_insert_returning? && pk
unless sequence_name
table_ref = extract_table_ref_from_insert_sql(sql)
sequence_name = default_sequence_name(table_ref, pk)
return val unless sequence_name
end
last_insert_id_result(sequence_name)
else
val
end
end
# Begins a transaction.
def begin_db_transaction
execute "BEGIN"
end
def begin_isolated_db_transaction(isolation)
begin_db_transaction
execute "SET TRANSACTION ISOLATION LEVEL #{transaction_isolation_levels.fetch(isolation)}"
end
# Commits a transaction.
def commit_db_transaction
execute "COMMIT"
end
# Aborts a transaction.
def exec_rollback_db_transaction
execute "ROLLBACK"
end
end
end
end
end
| 34.707602 | 100 | 0.560573 |
915fccb626194fb61307872d948005b9c7ca5205 | 639 | require 'rubygems'
require 'rack'
module Rack
class Exceptional
def initialize(app, api_key = nil)
@app = app
if api_key.nil?
exceptional_config = "config/exceptional.yml"
::Exceptional::Config.load(exceptional_config)
else
::Exceptional.configure(api_key)
::Exceptional::Config.enabled = true
::Exceptional.logger.info "Enabling Exceptional for Rack"
end
end
def call(env)
status, headers, body = @app.call(env)
rescue Exception => e
::Exceptional::Catcher.handle_with_rack(e, env, Rack::Request.new(env))
raise(e)
end
end
end
| 22.821429 | 77 | 0.638498 |
bf7be639c82d3b783860ace9998c9b1d704ad461 | 1,812 | require 'rubygems/test_case'
require 'rubygems/commands/which_command'
class TestGemCommandsWhichCommand < Gem::TestCase
def setup
super
Gem::Specification.reset
@cmd = Gem::Commands::WhichCommand.new
end
def test_execute
util_foo_bar
@cmd.handle_options %w[foo_bar]
use_ui @ui do
@cmd.execute
end
assert_equal "#{@foo_bar.full_gem_path}/lib/foo_bar.rb\n", @ui.output
assert_equal '', @ui.error
end
def test_execute_directory
@cmd.handle_options %w[directory]
use_ui @ui do
assert_raises Gem::MockGemUi::TermError do
@cmd.execute
end
end
assert_equal '', @ui.output
assert_match %r%Can.t find ruby library file or shared library directory\n%,
@ui.error
end
def test_execute_one_missing
# TODO: this test fails in isolation
util_foo_bar
@cmd.handle_options %w[foo_bar missinglib]
use_ui @ui do
@cmd.execute
end
assert_equal "#{@foo_bar.full_gem_path}/lib/foo_bar.rb\n", @ui.output
assert_match %r%Can.t find ruby library file or shared library missinglib\n%,
@ui.error
end
def test_execute_missing
@cmd.handle_options %w[missinglib]
use_ui @ui do
assert_raises Gem::MockGemUi::TermError do
@cmd.execute
end
end
assert_equal '', @ui.output
assert_match %r%Can.t find ruby library file or shared library missinglib\n%,
@ui.error
end
def util_foo_bar
files = %w[lib/foo_bar.rb lib/directory/baz.rb Rakefile]
@foo_bar = quick_spec 'foo_bar' do |gem|
gem.files = files
end
files.each do |file|
filename = File.join(@foo_bar.full_gem_path, file)
FileUtils.mkdir_p File.dirname filename
FileUtils.touch filename
end
end
end
| 21.571429 | 81 | 0.663907 |
bf33bcbc33b65b1dedd749b568a2d75ec1d76782 | 275 | # encoding: UTF-8
require 'rack/head'
require 'merb-core/rack/middleware'
module Merb
module Rack
# Merbified Rack::Head
#
# @see Merb::Rack::DeferrableMiddleware
class Head < ::Rack::Head
include Merb::Rack::DeferrableMiddleware
end
end
end
| 16.176471 | 46 | 0.672727 |
1d17f7ed25760b71ea0c9160942c9d884382eae3 | 5,618 | module Hobo
module Dryml
class DrymlSyntaxError < RuntimeError; end
class DrymlException < Exception
def initialize(message, path=nil, line_num=nil)
if path && line_num
super(message + " -- at #{path}:#{line_num}")
else
super(message)
end
end
end
class AttributeExtensionString < String;
def drop_prefix; self[2..-1]; end
end
TagDef = Struct.new "TagDef", :name, :attrs, :proc
RESERVED_WORDS = %w{if for while do class else elsif unless case when module in}
EMPTY_PAGE = "[tag-page]"
APPLICATION_TAGLIB = { :src => "taglibs/application" }
CORE_TAGLIB = { :src => "core", :plugin => "hobo" }
DEFAULT_IMPORTS = (if defined?(ApplicationHelper)
[Hobo::HoboHelper, ApplicationHelper]
else
[Hobo::HoboHelper]
end)
@renderer_classes = {}
@tag_page_renderer_classes = {}
class << self
attr_accessor :last_if
def clear_cache
@renderer_classes = {}
@tag_page_renderer_classes = {}
end
def render_tag(view, tag, options={})
renderer = empty_page_renderer(view)
renderer.render_tag(tag, options)
end
def empty_page_renderer(view)
controller_name = view.controller.class.name.underscore.sub(/_controller$/, "")
page_renderer(view, [], "#{controller_name}/#{EMPTY_PAGE}")
end
def page_renderer(view, local_names=[], page=nil)
if RAILS_ENV == "development"
clear_cache
Taglib.clear_cache
end
page ||= view.instance_variable_get('@hobo_template_path')
prepare_view!(view)
included_taglibs = ([subsite_taglib(page)] + controller_taglibs(view.controller.class)).compact
if page.ends_with?(EMPTY_PAGE)
# DELETE ME: controller_class = controller_class_for(page)
controller_class = view.controller.class
@tag_page_renderer_classes[controller_class.name] ||=
make_renderer_class("", page, local_names, DEFAULT_IMPORTS, included_taglibs)
@tag_page_renderer_classes[controller_class.name].new(page, view)
else
template_path = "app/views/" + page + ".dryml"
src_file = File.join(RAILS_ROOT, template_path)
mtime = File.mtime(src_file)
renderer_class = @renderer_classes[page]
# do we need to recompile?
if (!renderer_class or # nothing cached?
(local_names - renderer_class.compiled_local_names).any? or # any new local names?
renderer_class.load_time < mtime) # cache out of date?
renderer_class = make_renderer_class(File.read(src_file), template_path, local_names,
DEFAULT_IMPORTS, included_taglibs)
renderer_class.load_time = mtime
@renderer_classes[page] = renderer_class
end
renderer_class.new(page, view)
end
end
# TODO: Delete this - not needed (use view.controller.class)
def controller_class_for(page)
controller, view = Controller.controller_and_view_for(page)
"#{controller.camelize}Controller".constantize
end
def controller_taglibs(controller_class)
(controller_class.respond_to?(:included_taglibs) && controller_class.included_taglibs) || []
end
def subsite_taglib(page)
parts = page.split("/")
if parts.length == 3
subsite = parts.first
{ :src => "taglibs/#{subsite}" } if File.exists?("#{RAILS_ROOT}/app/views/taglibs/#{subsite}.dryml")
end
end
def prepare_view!(view)
# Not sure why this isn't done for me...
# There's probably a button to press round here somewhere
for var in %w(@flash @cookies @action_name @_session @_request @request_origin
@template @request @ignore_missing_templates @_headers @variables_added
@_flash @response @template_class
@_cookies @before_filter_chain_aborted @url
@_response @template_root @headers @_params @params @session)
unless @view.instance_variables.include?(var)
view.instance_variable_set(var, view.controller.instance_variable_get(var))
end
end
end
def make_renderer_class(template_src, template_path, locals, imports, included_taglibs=[])
renderer_class = Class.new(TemplateEnvironment)
compile_renderer_class(renderer_class, template_src, template_path, locals, imports, included_taglibs)
renderer_class
end
def compile_renderer_class(renderer_class, template_src, template_path, locals, imports, included_taglibs=[])
template = Template.new(template_src, renderer_class, template_path)
imports.each {|m| template.import_module(m)}
taglibs = [CORE_TAGLIB, APPLICATION_TAGLIB] + included_taglibs
# the sum of all the names we've seen so far - eventually we'll be ready for all of 'em
all_local_names = renderer_class.compiled_local_names | locals
template.compile(all_local_names, taglibs)
end
def unreserve(word)
word = word.to_s
if RESERVED_WORDS.include?(word)
word + "_"
else
word
end
end
end
end
end
| 33.843373 | 115 | 0.61036 |
f781a3976b7bc8fd5c9cd5c0c243635e7d441699 | 534 | class UserMailer < ApplicationMailer
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.user_mailer.account_activation.subject
#
def account_activation(user)
@user = user
mail to: user.email, subject: "Account activation"
end
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.user_mailer.password_reset.subject
#
def password_reset
@greeting = "Hi"
mail to: "[email protected]"
end
end
| 22.25 | 65 | 0.696629 |
919561cb06da9efb6ceccab072c58fd5a80a75bd | 144 | # frozen_string_literal: true
require 'solidus_core'
require 'solidus_support'
require 'solidus_demo1/version'
require 'solidus_demo1/engine'
| 18 | 31 | 0.826389 |
61975fca009a383c12154d824d8d806b1745ea21 | 211 | # frozen_string_literal: true
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../config/environment', __dir__)
require 'rails/test_help'
module ActiveSupport
class TestCase
fixtures :all
end
end
| 17.583333 | 58 | 0.744076 |
394a9116f5ca7963a42bafc8167369b9dfcd9f94 | 52 | module NormalizedProperties
VERSION = "1.0.0"
end
| 13 | 27 | 0.75 |
4a977e3558d43f7cd2131748bb0e829d4c990a00 | 390 | # frozen_string_literal: true
require_relative './page_size_for_helper'
module Pagination
module TotalPagesForHelper
include Pagination::PageSizeForHelper
def pagination_total_pages_for(set)
total_set_size = set.instructions.dig(:paginate, :count)
return 1 if total_set_size.zero?
(total_set_size.to_f / pagination_page_size_for(set)).ceil
end
end
end
| 22.941176 | 64 | 0.764103 |
ff4228c9b99629de4932c08a014010988e5bc6af | 9,761 | require 'spec_helper'
# user GET /users/:username/
# user_groups GET /users/:username/groups(.:format)
# user_projects GET /users/:username/projects(.:format)
# user_contributed_projects GET /users/:username/contributed(.:format)
# user_snippets GET /users/:username/snippets(.:format)
# user_calendar GET /users/:username/calendar(.:format)
# user_calendar_activities GET /users/:username/calendar_activities(.:format)
describe UsersController, "routing" do
it "to #show" do
allow_any_instance_of(::Constraints::UserUrlConstrainer).to receive(:matches?).and_return(true)
expect(get("/User")).to route_to('users#show', username: 'User')
end
it "to #groups" do
expect(get("/users/User/groups")).to route_to('users#groups', username: 'User')
end
it "to #projects" do
expect(get("/users/User/projects")).to route_to('users#projects', username: 'User')
end
it "to #contributed" do
expect(get("/users/User/contributed")).to route_to('users#contributed', username: 'User')
end
it "to #snippets" do
expect(get("/users/User/snippets")).to route_to('users#snippets', username: 'User')
end
it "to #calendar" do
expect(get("/users/User/calendar")).to route_to('users#calendar', username: 'User')
end
it "to #calendar_activities" do
expect(get("/users/User/calendar_activities")).to route_to('users#calendar_activities', username: 'User')
end
end
# search GET /search(.:format) search#show
describe SearchController, "routing" do
it "to #show" do
expect(get("/search")).to route_to('search#show')
end
end
# gitlab_api /api API::API
# /:path Grack
describe "Mounted Apps", "routing" do
it "to API" do
expect(get("/api/issues")).to be_routable
end
it "to Grack" do
expect(get("/gitlab/gitlabhq.git")).to be_routable
end
end
# snippets GET /snippets(.:format) snippets#index
# POST /snippets(.:format) snippets#create
# new_snippet GET /snippets/new(.:format) snippets#new
# edit_snippet GET /snippets/:id/edit(.:format) snippets#edit
# snippet GET /snippets/:id(.:format) snippets#show
# PUT /snippets/:id(.:format) snippets#update
# DELETE /snippets/:id(.:format) snippets#destroy
describe SnippetsController, "routing" do
it "to #raw" do
expect(get("/snippets/1/raw")).to route_to('snippets#raw', id: '1')
end
it "to #index" do
expect(get("/snippets")).to route_to('snippets#index')
end
it "to #create" do
expect(post("/snippets")).to route_to('snippets#create')
end
it "to #new" do
expect(get("/snippets/new")).to route_to('snippets#new')
end
it "to #edit" do
expect(get("/snippets/1/edit")).to route_to('snippets#edit', id: '1')
end
it "to #show" do
expect(get("/snippets/1")).to route_to('snippets#show', id: '1')
end
it "to #update" do
expect(put("/snippets/1")).to route_to('snippets#update', id: '1')
end
it "to #destroy" do
expect(delete("/snippets/1")).to route_to('snippets#destroy', id: '1')
end
end
# help GET /help(.:format) help#index
# help_page GET /help/*path(.:format) help#show
# help_shortcuts GET /help/shortcuts(.:format) help#shortcuts
# help_ui GET /help/ui(.:format) help#ui
describe HelpController, "routing" do
it "to #index" do
expect(get("/help")).to route_to('help#index')
end
it 'to #show' do
path = '/help/user/markdown.md'
expect(get(path)).to route_to('help#show',
path: 'user/markdown',
format: 'md')
path = '/help/workflow/protected_branches/protected_branches1.png'
expect(get(path)).to route_to('help#show',
path: 'workflow/protected_branches/protected_branches1',
format: 'png')
path = '/help/ui'
expect(get(path)).to route_to('help#ui')
end
end
# profile_account GET /profile/account(.:format) profile#account
# profile_history GET /profile/history(.:format) profile#history
# profile_password PUT /profile/password(.:format) profile#password_update
# profile_token GET /profile/token(.:format) profile#token
# profile GET /profile(.:format) profile#show
# profile_update PUT /profile/update(.:format) profile#update
describe ProfilesController, "routing" do
it "to #account" do
expect(get("/profile/account")).to route_to('profiles/accounts#show')
end
it "to #audit_log" do
expect(get("/profile/audit_log")).to route_to('profiles#audit_log')
end
it "to #reset_feed_token" do
expect(put("/profile/reset_feed_token")).to route_to('profiles#reset_feed_token')
end
it "to #show" do
expect(get("/profile")).to route_to('profiles#show')
end
end
# profile_preferences GET /profile/preferences(.:format) profiles/preferences#show
# PATCH /profile/preferences(.:format) profiles/preferences#update
# PUT /profile/preferences(.:format) profiles/preferences#update
describe Profiles::PreferencesController, 'routing' do
it 'to #show' do
expect(get('/profile/preferences')).to route_to('profiles/preferences#show')
end
it 'to #update' do
expect(put('/profile/preferences')).to route_to('profiles/preferences#update')
expect(patch('/profile/preferences')).to route_to('profiles/preferences#update')
end
end
# keys GET /keys(.:format) keys#index
# POST /keys(.:format) keys#create
# edit_key GET /keys/:id/edit(.:format) keys#edit
# key GET /keys/:id(.:format) keys#show
# PUT /keys/:id(.:format) keys#update
# DELETE /keys/:id(.:format) keys#destroy
describe Profiles::KeysController, "routing" do
it "to #index" do
expect(get("/profile/keys")).to route_to('profiles/keys#index')
end
it "to #create" do
expect(post("/profile/keys")).to route_to('profiles/keys#create')
end
it "to #show" do
expect(get("/profile/keys/1")).to route_to('profiles/keys#show', id: '1')
end
it "to #destroy" do
expect(delete("/profile/keys/1")).to route_to('profiles/keys#destroy', id: '1')
end
# get all the ssh-keys of a user
it "to #get_keys" do
allow_any_instance_of(::Constraints::UserUrlConstrainer).to receive(:matches?).and_return(true)
expect(get("/foo.keys")).to route_to('profiles/keys#get_keys', username: 'foo')
end
end
# emails GET /emails(.:format) emails#index
# POST /keys(.:format) emails#create
# DELETE /keys/:id(.:format) keys#destroy
describe Profiles::EmailsController, "routing" do
it "to #index" do
expect(get("/profile/emails")).to route_to('profiles/emails#index')
end
it "to #create" do
expect(post("/profile/emails")).to route_to('profiles/emails#create')
end
it "to #destroy" do
expect(delete("/profile/emails/1")).to route_to('profiles/emails#destroy', id: '1')
end
end
# profile_avatar DELETE /profile/avatar(.:format) profiles/avatars#destroy
describe Profiles::AvatarsController, "routing" do
it "to #destroy" do
expect(delete("/profile/avatar")).to route_to('profiles/avatars#destroy')
end
end
# dashboard GET /dashboard(.:format) dashboard#show
# dashboard_issues GET /dashboard/issues(.:format) dashboard#issues
# dashboard_merge_requests GET /dashboard/merge_requests(.:format) dashboard#merge_requests
describe DashboardController, "routing" do
it "to #index" do
expect(get("/dashboard")).to route_to('dashboard/projects#index')
end
it "to #issues" do
expect(get("/dashboard/issues.html")).to route_to('dashboard#issues', format: 'html')
end
it "to #calendar_issues" do
expect(get("/dashboard/issues.ics")).to route_to('dashboard#issues_calendar', format: 'ics')
end
it "to #merge_requests" do
expect(get("/dashboard/merge_requests")).to route_to('dashboard#merge_requests')
end
end
# root / root#show
describe RootController, 'routing' do
it 'to #index' do
expect(get('/')).to route_to('root#index')
end
end
describe "Authentication", "routing" do
it "GET /users/sign_in" do
expect(get("/users/sign_in")).to route_to('sessions#new')
end
it "POST /users/sign_in" do
expect(post("/users/sign_in")).to route_to('sessions#create')
end
# sign_out with GET instead of DELETE facilitates ad-hoc single-sign-out processes
# (https://gitlab.com/gitlab-org/gitlab-ce/issues/39708)
it "GET /users/sign_out" do
expect(get("/users/sign_out")).to route_to('sessions#destroy')
end
it "POST /users/password" do
expect(post("/users/password")).to route_to('passwords#create')
end
it "GET /users/password/new" do
expect(get("/users/password/new")).to route_to('passwords#new')
end
it "GET /users/password/edit" do
expect(get("/users/password/edit")).to route_to('passwords#edit')
end
it "PUT /users/password" do
expect(put("/users/password")).to route_to('passwords#update')
end
end
describe HealthCheckController, 'routing' do
it 'to #index' do
expect(get('/health_check')).to route_to('health_check#index')
end
it 'also supports passing checks in the url' do
expect(get('/health_check/email')).to route_to('health_check#index', checks: 'email')
end
end
| 33.775087 | 109 | 0.637025 |
1a6771cc1464353f43fef4c4ec47bffa7d046499 | 1,326 | # 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::Cosmosdb::Mgmt::V2020_03_01
module Models
#
# Cosmos DB resource auto-upgrade policy
#
class AutoUpgradePolicyResource
include MsRestAzure
# @return [ThroughputPolicyResource] Represents throughput policy which
# service must adhere to for auto-upgrade
attr_accessor :throughput_policy
#
# Mapper for AutoUpgradePolicyResource class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'AutoUpgradePolicyResource',
type: {
name: 'Composite',
class_name: 'AutoUpgradePolicyResource',
model_properties: {
throughput_policy: {
client_side_validation: true,
required: false,
serialized_name: 'throughputPolicy',
type: {
name: 'Composite',
class_name: 'ThroughputPolicyResource'
}
}
}
}
}
end
end
end
end
| 27.061224 | 77 | 0.588235 |
877837dd9b1af0e11bdbe5820e44cf14fe95aaa7 | 1,436 | # frozen_string_literal: true
require 'test_helper'
class HollabackTest < Minitest::Test
def test_version
refute_nil ::Hollaback::VERSION
end
def test_hollaback
stdout, = capture_io { sequence.call(Callbacker.new('Kevin')) }
assert_equal %w[hello before main after goodbye-Kevin], stdout.split("\n")
stdout, = capture_io { sequence.call(Callbacker.new('Meaghan')) }
assert_equal %w[hello before main after goodbye-Meaghan], stdout.split("\n")
end
def test_no_callbacks
chain = Hollaback::Chain.new
sequence = chain.compile { puts 'main' }
stdout, = capture_io { sequence.call(Callbacker.new('Jon')) }
assert_equal "main\n", stdout
end
def test_raises_on_invalid_arg
chain = Hollaback::Chain.new
chain.before Object.new
assert_raises ArgumentError do
chain.compile { puts 'main' }
end
end
def test_allows_calling_without_context
counter = 0
chain = Hollaback::Chain.new
chain.before { counter += 1 }
chain.after { counter += 1 }
chain.compile { counter += 1 }.call
assert_equal 3, counter
end
private
def sequence
@sequence ||=
begin
chain = Hollaback::Chain.new
chain.before :say_hello
chain.before { say { 'before' } }
chain.after { say { 'after' } }
chain.after(:say_goodbye)
chain.around(:say)
chain.compile { puts 'main' }
end
end
end
| 22.092308 | 80 | 0.6539 |
26072bcca0648378d66113e0f6c9e2709ad1cb6d | 122 | class AddUrlToPortfolios < ActiveRecord::Migration[5.2]
def change
add_column :portfolios, :url, :string
end
end
| 20.333333 | 55 | 0.737705 |
ac106a16db6cbb6e46d41a8cdd799d58684bfd51 | 564 | cask "hubstaff" do
version "1.6.1,3510"
sha256 "5c655cb34d4a173a7b888795c6c4618cc89707d13531c63544533e5e0ece1c75"
url "https://app.hubstaff.com/download/#{version.after_comma}-mac-os-x-#{version.before_comma.dots_to_hyphens}-release"
name "Hubstaff"
desc "Work time tracker"
homepage "https://hubstaff.com/"
livecheck do
url "https://app.hubstaff.com/appcast.xml"
strategy :sparkle do |item|
"#{item.short_version.split("-").first},#{item.url[%r{/(\d+)-mac-os-x-(?:\d(?:-\d+)*)-release}i, 1]}"
end
end
app "Hubstaff.app"
end
| 29.684211 | 121 | 0.687943 |
266e04c73a7ae63b7b3a740da6c94f75506147bd | 159 | namespace :grant do
namespace :db_privs do
task :run, [:force] => :environment do |t, params|
Util::DbManager.new.grant_db_privs
end
end
end
| 19.875 | 54 | 0.666667 |
38c751fdda5c23c8a5322db7bc2ace036e56b88a | 2,616 | module MiniTest
module Chef
module Lookup
# Load the test suites.
#
# If the option "path" is specified we use it to load the tests from it.
# The option can be a string or an array of paths.
# Otherwise we load the tests according to the recipes seen.
#
def require_test_suites(options_path)
paths = options_path || seen_recipes_paths
Array(paths).each do |path|
Dir.glob(path).each {|test_suite| require test_suite}
end
end
# Collect test paths based in the recipes ran.
#
# It loads the tests based in the name of the cookbook and the name of the recipe.
# The tests must be under the cookbooks directory.
#
# Examples:
#
# If the seen recipes includes the recipe "foo" we try to load tests from:
#
# cookbooks/foo/tests/default_test.rb
# cookbooks/foo/tests/default/*_test.rb
#
# cookbooks/foo/specs/default_spec.rb
# cookbooks/foo/specs/default/*_spec.rb
#
# If the seen recipes includes the recipe "foo::install" we try to load tests from:
#
# cookbooks/foo/tests/install_test.rb
# cookbooks/foo/tests/install/*_test.rb
#
# cookbooks/foo/specs/install_spec.rb
# cookbooks/foo/specs/install/*_spec.rb
#
def seen_recipes_paths
run_status.node.run_state[:seen_recipes].keys.map do |recipe_name|
cookbook_name, recipe_short_name = ::Chef::Recipe.parse_recipe_name(recipe_name)
base_path = ::Chef::Config[:cookbook_path]
cookbook_paths = lookup_cookbook(base_path, cookbook_name)
cookbook_paths.map do |path|
file_test_pattern = "%s/tests/%s_test.rb" % [path, recipe_short_name]
dir_test_pattern = "%s/tests/%s/*_test.rb" % [path, recipe_short_name]
file_spec_pattern = "%s/specs/%s_spec.rb" % [path, recipe_short_name]
dir_spec_pattern = "%s/specs/%s/*_spec.rb" % [path, recipe_short_name]
[file_test_pattern, dir_test_pattern, file_spec_pattern, dir_spec_pattern]
end.flatten
end.flatten
end
# Internal - look for the right path to the cookbook given one or
# several base paths.
#
# Path: String or Array representing the recipes base paths.
# Name: Name of the cookbook
#
# Returns paths founded for the speficied cookbook.
def lookup_cookbook(path, name)
path_expr = Array(path).join(',')
Dir.glob("{%s}/%s" % [path_expr, name])
end
end
end
end
| 35.351351 | 90 | 0.629205 |
4a3939df31f95a60be420bd4bd6f6d348af795e3 | 747 | require 'beaker-rspec'
require 'beaker-puppet'
require 'beaker/puppet_install_helper'
require 'beaker/module_install_helper'
run_puppet_install_helper unless ENV['BEAKER_provision'] == 'no'
RSpec.configure do |c|
# Project root
proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..'))
# Readable test descriptions
c.formatter = :documentation
# Configure all nodes in nodeset
c.before :suite do
# Install module and dependencies
puppet_module_install(:source => proj_root, :module_name => 'sumo')
# Will likely need stdlib in the future, just uncomment this
hosts.each do |host|
on host, puppet('module', 'install', 'puppetlabs-stdlib'), { :acceptable_exit_codes => [0,1] }
end
end
end | 29.88 | 100 | 0.720214 |
28810022374fffd9f4261561bac85856350847ae | 12,167 | require "cli/ui"
module Script
module UI
module ErrorHandler
def self.display(failed_op:, cause_of_error:, help_suggestion:)
$stderr.puts(CLI::UI.fmt(ShopifyCLI::Context.message("script.error.generic")))
full_msg = failed_op ? failed_op.dup : ""
full_msg << " #{cause_of_error}" if cause_of_error
full_msg << " #{help_suggestion}" if help_suggestion
$stderr.puts(CLI::UI.fmt(full_msg.strip))
end
def self.display_and_raise(failed_op: nil, cause_of_error: nil, help_suggestion: nil)
display(failed_op: failed_op, cause_of_error: cause_of_error, help_suggestion: help_suggestion)
raise(ShopifyCLI::AbortSilent)
end
def self.pretty_print_and_raise(e, failed_op: nil)
messages = error_messages(e)
raise e if messages.nil?
display_and_raise(failed_op: failed_op, **messages)
end
def self.error_messages(e)
case e
when Errno::EACCES
{
cause_of_error: ShopifyCLI::Context.message("script.error.eacces_cause"),
help_suggestion: ShopifyCLI::Context.message("script.error.eacces_help"),
}
when Errno::ENOSPC
{
cause_of_error: ShopifyCLI::Context.message("script.error.enospc_cause"),
help_suggestion: ShopifyCLI::Context.message("script.error.enospc_help"),
}
when ShopifyCLI::IdentityAuth::Error
{
cause_of_error: ShopifyCLI::Context.message("script.error.oauth_cause"),
help_suggestion: ShopifyCLI::Context.message("script.error.oauth_help"),
}
when Layers::Infrastructure::Errors::InvalidContextError
{
cause_of_error: ShopifyCLI::Context.message("script.error.invalid_context_cause"),
help_suggestion: ShopifyCLI::Context.message("script.error.invalid_context_help"),
}
when Layers::Infrastructure::Errors::InvalidLanguageError
{
cause_of_error: ShopifyCLI::Context.message("script.error.invalid_language_cause", e.language),
help_suggestion: ShopifyCLI::Context.message(
"script.error.invalid_language_help",
Script::Layers::Application::ExtensionPoints.languages(type: e.extension_point_type).join(", ")
),
}
when Errors::InvalidScriptNameError
{
cause_of_error: ShopifyCLI::Context.message("script.error.invalid_script_name_cause"),
help_suggestion: ShopifyCLI::Context.message("script.error.invalid_script_name_help"),
}
when Errors::NoExistingAppsError
{
cause_of_error: ShopifyCLI::Context.message("script.error.no_existing_apps_cause"),
help_suggestion: ShopifyCLI::Context.message("script.error.no_existing_apps_help"),
}
when Errors::NoExistingOrganizationsError
{
cause_of_error: ShopifyCLI::Context.message("script.error.no_existing_orgs_cause"),
help_suggestion: ShopifyCLI::Context.message("script.error.no_existing_orgs_help"),
}
when Layers::Infrastructure::Errors::ScriptProjectAlreadyExistsError
{
cause_of_error: ShopifyCLI::Context.message("script.error.project_exists_cause"),
help_suggestion: ShopifyCLI::Context.message("script.error.project_exists_help"),
}
when Layers::Infrastructure::Errors::DeprecatedEPError
{
cause_of_error: ShopifyCLI::Context.message("script.error.deprecated_ep", e.ep),
help_suggestion: ShopifyCLI::Context.message("script.error.deprecated_ep_cause"),
}
when Layers::Domain::Errors::InvalidExtensionPointError
{
cause_of_error: ShopifyCLI::Context.message("script.error.invalid_extension_cause", e.type),
help_suggestion: ShopifyCLI::Context.message(
"script.error.invalid_extension_help",
Script::Layers::Application::ExtensionPoints.available_types.join(", ")
),
}
when Layers::Domain::Errors::ScriptNotFoundError
{
cause_of_error: ShopifyCLI::Context.message(
"script.error.script_not_found_cause",
e.script_name,
e.extension_point_type
),
}
when Layers::Domain::Errors::MetadataValidationError
{
cause_of_error: ShopifyCLI::Context.message("script.error.metadata_validation_cause"),
help_suggestion: ShopifyCLI::Context.message("script.error.metadata_validation_help"),
}
when Layers::Domain::Errors::MetadataNotFoundError
{
cause_of_error: ShopifyCLI::Context.message("script.error.metadata_not_found_cause"),
help_suggestion: ShopifyCLI::Context.message("script.error.metadata_not_found_help"),
}
when Layers::Domain::Errors::MissingScriptJsonFieldError
{
cause_of_error: ShopifyCLI::Context.message("script.error.missing_script_json_field_cause", e.field),
help_suggestion: ShopifyCLI::Context.message("script.error.missing_script_json_field_help"),
}
when Layers::Domain::Errors::InvalidScriptJsonDefinitionError
{
cause_of_error: ShopifyCLI::Context.message("script.error.invalid_script_json_definition_cause"),
help_suggestion: ShopifyCLI::Context.message("script.error.invalid_script_json_definition_help"),
}
when Layers::Domain::Errors::NoScriptJsonFile
{
cause_of_error: ShopifyCLI::Context.message("script.error.no_script_json_file_cause"),
help_suggestion: ShopifyCLI::Context.message("script.error.no_script_json_file_help"),
}
when Layers::Infrastructure::Errors::BuildError
{
cause_of_error: ShopifyCLI::Context.message("script.error.build_error_cause"),
help_suggestion: ShopifyCLI::Context.message("script.error.build_error_help"),
}
when Layers::Infrastructure::Errors::ScriptJsonSyntaxError
{
cause_of_error: ShopifyCLI::Context.message("script.error.configuration_syntax_error_cause"),
help_suggestion: ShopifyCLI::Context.message("script.error.configuration_syntax_error_help"),
}
when Layers::Infrastructure::Errors::ScriptJsonMissingKeysError
{
cause_of_error: ShopifyCLI::Context.message(
"script.error.configuration_missing_keys_error_cause",
missing_keys: e.missing_keys
),
help_suggestion: ShopifyCLI::Context.message("script.error.configuration_missing_keys_error_help"),
}
when Layers::Infrastructure::Errors::ScriptJsonInvalidValueError
{
cause_of_error: ShopifyCLI::Context.message(
"script.error.configuration_invalid_value_error_cause",
valid_input_modes: e.valid_input_modes
),
help_suggestion: ShopifyCLI::Context.message("script.error.configuration_invalid_value_error_help"),
}
when Layers::Infrastructure::Errors::ScriptJsonFieldsMissingKeysError
{
cause_of_error: ShopifyCLI::Context.message(
"script.error.configuration_schema_field_missing_keys_error_cause",
missing_keys: e.missing_keys
),
help_suggestion: ShopifyCLI::Context.message(
"script.error.configuration_definition_schema_field_missing_keys_error_help"
),
}
when Layers::Infrastructure::Errors::ScriptJsonFieldsInvalidValueError
{
cause_of_error: ShopifyCLI::Context.message(
"script.error.configuration_schema_field_invalid_value_error_cause",
valid_types: e.valid_types
),
help_suggestion: ShopifyCLI::Context.message(
"script.error.configuration_schema_field_invalid_value_error_help"
),
}
when Layers::Infrastructure::Errors::DependencyInstallError
{
cause_of_error: ShopifyCLI::Context.message("script.error.dependency_install_cause"),
help_suggestion: ShopifyCLI::Context.message("script.error.dependency_install_help"),
}
when Layers::Infrastructure::Errors::EmptyResponseError
{
cause_of_error: ShopifyCLI::Context.message("script.error.failed_api_request_cause"),
help_suggestion: ShopifyCLI::Context.message("script.error.failed_api_request_help"),
}
when Layers::Infrastructure::Errors::ForbiddenError
{
cause_of_error: ShopifyCLI::Context.message("script.error.forbidden_error_cause"),
}
when Layers::Infrastructure::Errors::GraphqlError
{
cause_of_error: ShopifyCLI::Context.message(
"script.error.graphql_error_cause", JSON.pretty_generate(e.errors)
),
help_suggestion: ShopifyCLI::Context.message("script.error.graphql_error_help"),
}
when Layers::Infrastructure::Errors::SystemCallFailureError
{
cause_of_error: ShopifyCLI::Context
.message("script.error.system_call_failure_cause", cmd: e.cmd),
help_suggestion: ShopifyCLI::Context.message("script.error.system_call_failure_help", out: e.out),
}
when Layers::Infrastructure::Errors::ScriptRepushError
{
cause_of_error: ShopifyCLI::Context.message("script.error.script_repush_cause"),
help_suggestion: ShopifyCLI::Context.message("script.error.script_repush_help"),
}
when Layers::Infrastructure::Errors::BuildScriptNotFoundError
{
cause_of_error: ShopifyCLI::Context.message("script.error.build_script_not_found"),
help_suggestion: ShopifyCLI::Context.message("script.error.build_script_suggestion"),
}
when Layers::Infrastructure::Errors::InvalidBuildScriptError
{
cause_of_error: ShopifyCLI::Context.message("script.error.invalid_build_script"),
help_suggestion: ShopifyCLI::Context.message("script.error.build_script_suggestion"),
}
when Layers::Infrastructure::Errors::WebAssemblyBinaryNotFoundError
{
cause_of_error: ShopifyCLI::Context.message("script.error.web_assembly_binary_not_found"),
help_suggestion: ShopifyCLI::Context.message("script.error.web_assembly_binary_not_found_suggestion"),
}
when Layers::Infrastructure::Errors::ProjectConfigNotFoundError
{
cause_of_error: ShopifyCLI::Context.message("script.error.project_config_not_found"),
}
when Layers::Infrastructure::Errors::InvalidProjectConfigError
{
cause_of_error: ShopifyCLI::Context.message("script.error.invalid_project_config"),
}
when Layers::Infrastructure::Errors::ScriptUploadError
{
cause_of_error: ShopifyCLI::Context.message("script.error.script_upload_cause"),
help_suggestion: ShopifyCLI::Context.message("script.error.script_upload_help"),
}
when Layers::Infrastructure::Errors::APILibraryNotFoundError
{
cause_of_error: ShopifyCLI::Context
.message("script.error.api_library_not_found_cause", library_name: e.library_name),
help_suggestion: ShopifyCLI::Context.message("script.error.api_library_not_found_help"),
}
when Layers::Infrastructure::Errors::LanguageLibraryForAPINotFoundError
{
cause_of_error: ShopifyCLI::Context
.message(
"script.error.language_library_for_api_not_found_cause",
language: e.language,
api: e.api
),
help_suggestion: ShopifyCLI::Context.message("script.error.language_library_for_api_not_found_help"),
}
end
end
end
end
end
| 49.060484 | 114 | 0.659324 |
6a90a176e8a258472b84a3b6bce3a56d6db3a808 | 292 | cask "font-esteban" do
version :latest
sha256 :no_check
url "https://github.com/google/fonts/raw/main/ofl/esteban/Esteban-Regular.ttf",
verified: "github.com/google/fonts/"
name "Esteban"
homepage "https://fonts.google.com/specimen/Esteban"
font "Esteban-Regular.ttf"
end
| 24.333333 | 81 | 0.722603 |
1c0da51cd621b4cfca3df6a3b9dc3c0d21fffa94 | 6,245 | require 'rails_helper'
# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to specify the controller code that
# was generated by Rails when you ran the scaffold generator.
#
# It assumes that the implementation code is generated by the rails scaffold
# generator. If you are using any extension libraries to generate different
# controller code, this generated spec may or may not pass.
#
# It only uses APIs available in rails and/or rspec-rails. There are a number
# of tools you can use to make these specs even more expressive, but we're
# sticking to rails and rspec-rails APIs to keep things simple and stable.
#
# Compared to earlier versions of this generator, there is very limited use of
# stubs and message expectations in this spec. Stubs are only used when there
# is no simpler way to get a handle on the object needed for the example.
# Message expectations are only used when there is no simpler way to specify
# that an instance is receiving a specific message.
RSpec.describe AppointmentsController, type: :controller do
# This should return the minimal set of attributes required to create a valid
# Appointment. As you add validations to Appointment, be sure to
# adjust the attributes here as well.
let(:valid_attributes) {
skip("Add a hash of attributes valid for your model")
}
let(:invalid_attributes) {
skip("Add a hash of attributes invalid for your model")
}
# This should return the minimal set of values that should be in the session
# in order to pass any filters (e.g. authentication) defined in
# AppointmentsController. Be sure to keep this updated too.
let(:valid_session) { {} }
describe "GET #index" do
it "assigns all appointments as @appointments" do
appointment = Appointment.create! valid_attributes
get :index, params: {}, session: valid_session
expect(assigns(:appointments)).to eq([appointment])
end
end
describe "GET #show" do
it "assigns the requested appointment as @appointment" do
appointment = Appointment.create! valid_attributes
get :show, params: {id: appointment.to_param}, session: valid_session
expect(assigns(:appointment)).to eq(appointment)
end
end
describe "GET #new" do
it "assigns a new appointment as @appointment" do
get :new, params: {}, session: valid_session
expect(assigns(:appointment)).to be_a_new(Appointment)
end
end
describe "GET #edit" do
it "assigns the requested appointment as @appointment" do
appointment = Appointment.create! valid_attributes
get :edit, params: {id: appointment.to_param}, session: valid_session
expect(assigns(:appointment)).to eq(appointment)
end
end
describe "POST #create" do
context "with valid params" do
it "creates a new Appointment" do
expect {
post :create, params: {appointment: valid_attributes}, session: valid_session
}.to change(Appointment, :count).by(1)
end
it "assigns a newly created appointment as @appointment" do
post :create, params: {appointment: valid_attributes}, session: valid_session
expect(assigns(:appointment)).to be_a(Appointment)
expect(assigns(:appointment)).to be_persisted
end
it "redirects to the created appointment" do
post :create, params: {appointment: valid_attributes}, session: valid_session
expect(response).to redirect_to(Appointment.last)
end
end
context "with invalid params" do
it "assigns a newly created but unsaved appointment as @appointment" do
post :create, params: {appointment: invalid_attributes}, session: valid_session
expect(assigns(:appointment)).to be_a_new(Appointment)
end
it "re-renders the 'new' template" do
post :create, params: {appointment: invalid_attributes}, session: valid_session
expect(response).to render_template("new")
end
end
end
describe "PUT #update" do
context "with valid params" do
let(:new_attributes) {
skip("Add a hash of attributes valid for your model")
}
it "updates the requested appointment" do
appointment = Appointment.create! valid_attributes
put :update, params: {id: appointment.to_param, appointment: new_attributes}, session: valid_session
appointment.reload
skip("Add assertions for updated state")
end
it "assigns the requested appointment as @appointment" do
appointment = Appointment.create! valid_attributes
put :update, params: {id: appointment.to_param, appointment: valid_attributes}, session: valid_session
expect(assigns(:appointment)).to eq(appointment)
end
it "redirects to the appointment" do
appointment = Appointment.create! valid_attributes
put :update, params: {id: appointment.to_param, appointment: valid_attributes}, session: valid_session
expect(response).to redirect_to(appointment)
end
end
context "with invalid params" do
it "assigns the appointment as @appointment" do
appointment = Appointment.create! valid_attributes
put :update, params: {id: appointment.to_param, appointment: invalid_attributes}, session: valid_session
expect(assigns(:appointment)).to eq(appointment)
end
it "re-renders the 'edit' template" do
appointment = Appointment.create! valid_attributes
put :update, params: {id: appointment.to_param, appointment: invalid_attributes}, session: valid_session
expect(response).to render_template("edit")
end
end
end
describe "DELETE #destroy" do
it "destroys the requested appointment" do
appointment = Appointment.create! valid_attributes
expect {
delete :destroy, params: {id: appointment.to_param}, session: valid_session
}.to change(Appointment, :count).by(-1)
end
it "redirects to the appointments list" do
appointment = Appointment.create! valid_attributes
delete :destroy, params: {id: appointment.to_param}, session: valid_session
expect(response).to redirect_to(appointments_url)
end
end
end
| 39.03125 | 112 | 0.711289 |
6ad502a65b32bd1030bacdd448bd272c1e811f1f | 8,249 | require 'spec_helper'
require 'serverspec_extended_types/http_get'
describe 'Serverspec::Type.bitlbee' do
it 'instantiates the class with the correct parameters' do
expect(Serverspec::Type::Bitlbee).to receive(:new).with(1, 'mynick', 'mypass', false)
bitlbee(1, 'mynick', 'mypass')
end
it 'returns the new object' do
expect(Serverspec::Type::Bitlbee).to receive(:new).and_return("foo")
expect(bitlbee(1, 'foo', 'bar')).to eq "foo"
end
end
describe 'Serverspec::Type::Bitlbee' do
context '#initialize' do
it 'sets instance variables' do
stub_const('ENV', ENV.to_hash.merge('TARGET_HOST' => 'myhost'))
x = bitlbee(1, 'foo', 'bar')
expect(x.instance_variable_get(:@port)).to eq 1
expect(x.instance_variable_get(:@host)).to eq 'myhost'
expect(x.instance_variable_get(:@nick)).to eq 'foo'
expect(x.instance_variable_get(:@password)).to eq 'bar'
expect(x.instance_variable_get(:@connected_status)).to eq false
expect(x.instance_variable_get(:@version_str)).to eq ''
expect(x.instance_variable_get(:@timed_out_status)).to eq false
expect(x.instance_variable_get(:@started)).to eq false
expect(x.instance_variable_get(:@use_ssl)).to eq false
end
it 'sets use_ssl instance variable' do
stub_const('ENV', ENV.to_hash.merge('TARGET_HOST' => 'myhost'))
x = bitlbee(1, 'foo', 'bar', use_ssl=true)
expect(x.instance_variable_get(:@use_ssl)).to eq true
end
end
context 'start' do
it 'calls connect_ssl if use_ssl=true' do
x = bitlbee(1, 'foo', 'bar', use_ssl=true)
expect(x).to receive(:connect_ssl).once
expect(x).to_not receive(:connect)
x.start
expect(x.instance_variable_get(:@timed_out_status)).to eq false
expect(x.instance_variable_get(:@connected_status)).to eq false
expect(x.instance_variable_get(:@started)).to eq true
end
it 'calls connect if use_ssl=false' do
x = bitlbee(1, 'foo', 'bar')
expect(x).to receive(:connect).once
expect(x).to_not receive(:connect_ssl)
x.start
expect(x.instance_variable_get(:@timed_out_status)).to eq false
expect(x.instance_variable_get(:@connected_status)).to eq false
expect(x.instance_variable_get(:@started)).to eq true
end
it 'runs with a timeout' do
x = bitlbee(1, 'foo', 'bar')
expect(Timeout).to receive(:timeout).with(10)
x.start
expect(x.instance_variable_get(:@timed_out_status)).to eq false
expect(x.instance_variable_get(:@connected_status)).to eq false
expect(x.instance_variable_get(:@started)).to eq true
expect(x.timed_out?).to eq false
end
it 'sets timed_out_status on timeout' do
x = bitlbee(1, 'foo', 'bar')
expect(Timeout).to receive(:timeout).with(10).and_raise(Timeout::Error)
x.start
expect(x.instance_variable_get(:@timed_out_status)).to eq true
expect(x.instance_variable_get(:@connected_status)).to eq false
expect(x.instance_variable_get(:@started)).to eq true
expect(x.timed_out?).to eq true
expect(x.connectable?).to eq false
end
it 'sets connected_status on ECONNREFUSED' do
x = bitlbee(1, 'foo', 'bar')
expect(x).to receive(:connect).and_raise(Errno::ECONNREFUSED)
x.start
expect(x.instance_variable_get(:@timed_out_status)).to eq false
expect(x.instance_variable_get(:@connected_status)).to eq false
expect(x.instance_variable_get(:@started)).to eq true
expect(x.timed_out?).to eq false
expect(x.connectable?).to eq false
end
end
context '#connect_ssl' do
it 'calls communicate' do
stub_const('ENV', ENV.to_hash.merge('TARGET_HOST' => 'myhost'))
sock_dbl = double
expect(TCPSocket).to receive(:open).with('myhost', 1).and_return(sock_dbl)
sslctx_dbl = double
expect(OpenSSL::SSL::SSLContext).to receive(:new).and_return(sslctx_dbl)
expect(sslctx_dbl).to receive(:set_params).with(verify_mode: OpenSSL::SSL::VERIFY_NONE).ordered
sslsock_dbl = double
expect(sslsock_dbl).to receive(:sync_close=).ordered.with(true)
expect(sslsock_dbl).to receive(:connect).ordered
expect(sslsock_dbl).to receive(:puts).ordered.with("communicate")
expect(sslsock_dbl).to receive(:puts).ordered.with("QUIT :\"outta here\"\n")
expect(sslsock_dbl).to receive(:close).ordered
expect(OpenSSL::SSL::SSLSocket).to receive(:new).with(sock_dbl, sslctx_dbl).and_return(sslsock_dbl)
# expect_any_instance_of(Serverspec::Type::Bitlbee).to receive(:communicate)
x = bitlbee(1, 'foo', 'bar')
allow(x).to receive(:communicate) do
x.instance_variable_get(:@socket).puts("communicate")
end
x.connect_ssl
expect(x.instance_variable_get(:@socket)).to eq sslsock_dbl
end
end
context '#connect' do
it 'calls communicate' do
stub_const('ENV', ENV.to_hash.merge('TARGET_HOST' => 'myhost'))
sock_dbl = double
expect(TCPSocket).to receive(:open).with('myhost', 1).and_return(sock_dbl)
expect(sock_dbl).to receive(:puts).ordered.with("communicate")
expect(sock_dbl).to receive(:puts).ordered.with("QUIT :\"outta here\"\n")
expect(sock_dbl).to receive(:close).ordered
x = bitlbee(1, 'foo', 'bar')
allow(x).to receive(:communicate) do
x.instance_variable_get(:@socket).puts("communicate")
end
x.connect
expect(x.instance_variable_get(:@socket)).to eq sock_dbl
end
end
context '#communicate' do
it 'logs in' do
x = bitlbee(1, 'foo', 'bar')
sock = double
x.instance_variable_set(:@socket, sock)
x.instance_variable_set(:@started, true)
expect(sock).to receive(:puts).ordered.with("PASS bar\n")
expect(sock).to receive(:puts).ordered.with("NICK foo\n")
expect(sock).to receive(:puts).ordered.with("USER foo foo servername :TestUser\n")
expect(sock).to receive(:readpartial).ordered.with(1024).and_return("Welcome to the foo")
expect(sock).to receive(:puts).ordered.with("MODE foo +i\n")
expect(sock).to receive(:readpartial).ordered.with(1024).and_return("If you've never something something")
expect(sock).to receive(:puts).ordered.with("PRIVMSG &bitlbee :identify bar\n")
expect(sock).to receive(:readpartial).ordered.with(1024).and_return("PING servername")
expect(sock).to receive(:puts).ordered.with(":servername PONG servername :servername\n")
expect(sock).to receive(:readpartial).ordered.with(1024).and_return("MODE foo :\+i")
expect(sock).to receive(:puts).ordered.with("PRIVMSG root :\001VERSION\001\n")
expect(sock).to receive(:readpartial).ordered.with(1024).and_return("foo bar baz blam\n")
expect(sock).to receive(:readpartial).ordered.with(1024).and_return("VERSION x.y.z\n")
x.communicate
expect(x.instance_variable_get(:@connected_status)).to eq true
expect(x.version).to eq 'x.y.z'
expect(x.connectable?).to eq true
expect(x.timed_out?).to eq false
end
end
context '#timed_out?' do
it 'calls start if not started' do
x = bitlbee(1, 'foo', 'bar')
expect(x).to receive(:start).once
expect(x.timed_out?).to eq false
end
it 'doesnt call start if started' do
x = bitlbee(1, 'foo', 'bar')
x.instance_variable_set(:@started, true)
expect(x).to_not receive(:start)
expect(x.timed_out?).to eq false
end
end
context '#connectable?' do
it 'calls start if not started' do
x = bitlbee(1, 'foo', 'bar')
expect(x).to receive(:start).once
expect(x.connectable?).to eq false
end
it 'doesnt call start if started' do
x = bitlbee(1, 'foo', 'bar')
x.instance_variable_set(:@started, true)
expect(x).to_not receive(:start)
expect(x.connectable?).to eq false
end
end
context '#version?' do
it 'calls start if not started' do
x = bitlbee(1, 'foo', 'bar')
expect(x).to receive(:start).once
expect(x.version).to eq ""
end
it 'doesnt call start if started' do
x = bitlbee(1, 'foo', 'bar')
x.instance_variable_set(:@started, true)
expect(x).to_not receive(:start)
expect(x.version).to eq ""
end
end
end
| 43.415789 | 112 | 0.670384 |
393aa18cb46f128f28e3b9d3bfae08fac00bd2b2 | 783 | room(:station_charlie) do
self.exit_north = :food_farm
self.destination = :station_delta
self.desc = <<-DESC
I am standing on a metallic platform in a large dome. A brightly lit
sign above the walkway says TRAVEL-TUBE STATION CHARLIE. A walkway
leads NORTH.
DESC
self.short_desc = "Charlie Station."
self.script_enter_car = <<-SCRIPT
puts "You enter the travel-tube car"
# TODO
SCRIPT
item(:lever, 'lever') do
self.presence = "Lever"
self.script_pull = <<-SCRIPT
puts "Whoosh! A travel-car arrives."
puts "The door opens"
get_root.move(:tube_car, parent, false)
SCRIPT
end
item(:rail_tracks, 'tracks', 'rail-tracks') do
self.desc = "OUCH! Your hair stands on end!"
self.presence = "Rail-tracks"
end
end | 29 | 72 | 0.67433 |
1870b7d53e5fd5953b4a016182145743562f9c73 | 265 | class CreateCourseLevels < ActiveRecord::Migration
def change
create_table :course_levels do |t|
t.references :course
t.string :title
t.text :description
t.text :question
t.text :answer
t.timestamps
end
end
end
| 17.666667 | 50 | 0.641509 |
d5abdc5f4e2cd14590cda4b037f92ca8da23013c | 908 | 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 Comunidadmexico
class Application < Rails::Application
config.generators do |g|
g.test_framework :rspec,
fixtures: true,
view_specs: false,
helper_specs: false,
routing_specs: false,
controller_specs: false,
request_specs: false
g.fixture_replacement :factory_bot, dir: "spec/factories"
end
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
end
end
| 29.290323 | 82 | 0.719163 |
7aa0a3485fb67e8d81fac7a5b87e8eac4b49be38 | 2,445 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Gitlab::JobWaiter do
describe '.notify' do
it 'pushes the jid to the named queue' do
key = 'gitlab:job_waiter:foo'
jid = 1
redis = double('redis')
expect(Gitlab::Redis::SharedState).to receive(:with).and_yield(redis)
expect(redis).to receive(:lpush).with(key, jid)
described_class.notify(key, jid)
end
end
describe '#wait' do
let(:waiter) { described_class.new(2) }
it 'returns when all jobs have been completed' do
described_class.notify(waiter.key, 'a')
described_class.notify(waiter.key, 'b')
result = nil
expect { Timeout.timeout(1) { result = waiter.wait(2) } }.not_to raise_error
expect(result).to contain_exactly('a', 'b')
end
it 'times out if not all jobs complete' do
described_class.notify(waiter.key, 'a')
result = nil
expect { Timeout.timeout(2) { result = waiter.wait(1) } }.not_to raise_error
expect(result).to contain_exactly('a')
end
context 'when a label is provided' do
let(:waiter) { described_class.new(2, worker_label: 'Foo') }
let(:started_total) { double(:started_total) }
let(:timeouts_total) { double(:timeouts_total) }
before do
allow(Gitlab::Metrics).to receive(:counter)
.with(described_class::STARTED_METRIC, anything)
.and_return(started_total)
allow(Gitlab::Metrics).to receive(:counter)
.with(described_class::TIMEOUTS_METRIC, anything)
.and_return(timeouts_total)
end
it 'increments just job_waiter_started_total when all jobs complete' do
expect(started_total).to receive(:increment).with(worker: 'Foo')
expect(timeouts_total).not_to receive(:increment)
described_class.notify(waiter.key, 'a')
described_class.notify(waiter.key, 'b')
expect { Timeout.timeout(1) { waiter.wait(2) } }.not_to raise_error
end
it 'increments job_waiter_started_total and job_waiter_timeouts_total when it times out' do
expect(started_total).to receive(:increment).with(worker: 'Foo')
expect(timeouts_total).to receive(:increment).with(worker: 'Foo')
expect { Timeout.timeout(2) { waiter.wait(1) } }.not_to raise_error
end
end
end
end
| 32.6 | 97 | 0.633129 |
e20f30e5dc2b3b90a8aec006fc4d5cf2a514fb8f | 2,565 | require 'capybara'
require 'capybara/poltergeist'
require 'fastimage'
require 'credentials_manager/password_manager'
require 'phantomjs/poltergeist'
# Import all the actions
require 'deliver/itunes_connect/itunes_connect_submission'
require 'deliver/itunes_connect/itunes_connect_reader'
require 'deliver/itunes_connect/itunes_connect_helper'
require 'deliver/itunes_connect/itunes_connect_new_version'
require 'deliver/itunes_connect/itunes_connect_login'
require 'deliver/itunes_connect/itunes_connect_app_icon'
require 'deliver/itunes_connect/itunes_connect_app_rating'
require 'deliver/itunes_connect/itunes_connect_additional'
module Deliver
# Everything that can't be achived using the {Deliver::ItunesTransporter}
# will be scripted using the iTunesConnect frontend.
#
# Every method you call here, might take a time
class ItunesConnect
# This error occurs only if there is something wrong with the given login data
class ItunesConnectLoginError < StandardError
end
# This error can occur for many reaons. It is
# usually raised when a UI element could not be found
class ItunesConnectGeneralError < StandardError
end
include Capybara::DSL
ITUNESCONNECT_URL = "https://itunesconnect.apple.com/"
APP_DETAILS_URL = "https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/[[app_id]]"
BUTTON_STRING_NEW_VERSION = "New Version"
BUTTON_STRING_SUBMIT_FOR_REVIEW = "Submit for Review"
BUTTON_ADD_NEW_BUILD = 'Click + to add a build before you submit your app.'
WAITING_FOR_REVIEW = "Waiting For Review"
PROCESSING_TEXT = "Processing"
def initialize
super
return if Helper.is_test?
DependencyChecker.check_dependencies
Capybara.run_server = false
Capybara.default_driver = :poltergeist
Capybara.javascript_driver = :poltergeist
Capybara.current_driver = :poltergeist
Capybara.app_host = ITUNESCONNECT_URL
# Since Apple has some SSL errors, we have to configure the client properly:
# https://github.com/ariya/phantomjs/issues/11239
Capybara.register_driver :poltergeist do |a|
conf = ['--debug=no', '--ignore-ssl-errors=yes', '--ssl-protocol=TLSv1']
Capybara::Poltergeist::Driver.new(a, {
phantomjs: Phantomjs.path,
phantomjs_options: conf,
phantomjs_logger: File.open("/tmp/poltergeist_log.txt", "a"),
js_errors: false
})
end
page.driver.headers = { "Accept-Language" => "en" }
login
end
end
end
| 34.2 | 105 | 0.735673 |
4a20e3e2a648c5cdc660858c61c6da0d3895b802 | 976 | cask '[email protected]' do
version '2017.1.0p1,2f459b492f3c'
sha256 :no_check
url "https://download.unity3d.com/download_unity/2f459b492f3c/MacExampleProjectInstaller/Examples.pkg"
name 'Example Project'
homepage 'https://unity3d.com/unity/'
pkg 'Examples.pkg'
depends_on cask: '[email protected]'
preflight do
if File.exist? "/Applications/Unity"
FileUtils.move "/Applications/Unity", "/Applications/Unity.temp"
end
if File.exist? "/Applications/Unity-2017.1.0p1"
FileUtils.move "/Applications/Unity-2017.1.0p1", '/Applications/Unity'
end
end
postflight do
if File.exist? '/Applications/Unity'
FileUtils.move '/Applications/Unity', "/Applications/Unity-2017.1.0p1"
end
if File.exist? '/Applications/Unity.temp'
FileUtils.move '/Applications/Unity.temp', '/Applications/Unity'
end
end
uninstall quit: 'com.unity3d.UnityEditor5.x',
delete: '/Users/Shared/Unity'
end
| 27.111111 | 104 | 0.697746 |
1a940d00182744c1cfede8943f2373d3e28ce6e1 | 114 | module OmniAuth
module UserAgent
end
end
require "omniauth/version"
require "omniauth/strategies/useragent"
| 12.666667 | 39 | 0.798246 |
21076384eea0b4ebc41674510cb5b70355458bec | 2,066 | class UwWebResource < ActiveResource::Base
class << self
attr_accessor :caller_class
# Attaches our cert, key, and CA file based on the config options in web_services.yml.
def ssl_options
check_cert_paths!
@ssl_options ||= {
:cert => OpenSSL::X509::Certificate.new(File.open("#{Rails.root}/config/certs/#{config_options[:cert]}")),
:key => OpenSSL::PKey::RSA.new(File.open("#{Rails.root}/config/certs/#{config_options[:key]}")),
:ca_file => "#{Rails.root}/config/certs/#{config_options[:ca_file]}",
:verify_mode => OpenSSL::SSL::VERIFY_PEER
}
end
# All configuration options are stored in RAILS_ROOT/config/web_services.yml. This allows us to use different
# hosts, certs, etc. in different Rails environments.
def config_options
@config_options ||= Rails.application.config_for(:web_services).symbolize_keys
end
def headers
{ "x-uw-act-as" => 'expo' }
end
def sws_log(msg, time = nil)
message = " \e[4;33;1m#{self.class.to_s} Fetch"
message << " (#{'%.1f' % (time*1000)}ms)" if time
message << "\e[0m #{msg}"
Rails.logger.info message
end
end
self.prefix = "https://#{UwWebResource.config_options[:host]}/student/#{Rails.application.config_for(:constants)["sws_version"]}"
protected
# Raises an error if the cert, key, or CA file does not exist.
def self.check_cert_paths!
raise ActiveResource::SSLError, "Could not find cert file" unless File.exist?("#{Rails.root}/config/certs/#{config_options[:cert]}")
raise ActiveResource::SSLError, "Could not find key file" unless File.exist?("#{Rails.root}/config/certs/#{config_options[:key]}")
raise ActiveResource::SSLError, "Could not find CA file" unless File.exist?("#{Rails.root}/config/certs/#{config_options[:ca_file]}")
return true
rescue => e
puts Rails.logger.warn "[WARN] ActiveResource::SSLError: #{e.message}\n #{e.backtrace.try(:first)}"
return false
end
end | 37.563636 | 137 | 0.649564 |
f8cacae79a27976f31a82e89cbac9255f3360808 | 3,696 | ENV["RAILS_ENV"] = 'test'
RAILS_ENV = 'test'
BASE_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '../../'))
require 'fileutils'
require 'spec'
require File.join(BASE_ROOT, 'spec/matchers/generator_matchers')
require File.join(BASE_ROOT, 'lib/plugins/string_extensions/lib/string_extensions')
unless defined?(::GENERATOR_SUPPORT_LOADED) && ::GENERATOR_SUPPORT_LOADED
# this is so we can require ActiveSupport
$:.unshift File.join(BASE_ROOT, 'vendor/rails/activesupport/lib')
# This is so the initializer and Rails::Generator is properly found
$:.unshift File.join(BASE_ROOT, 'vendor/rails/railties/lib')
require 'active_support'
# Mock out what we need from AR::Base
module ActiveRecord
class Base
class << self
attr_accessor :pluralize_table_names, :timestamped_migrations
end
self.pluralize_table_names = true
self.timestamped_migrations = true
end
module ConnectionAdapters
class Column
attr_reader :name, :default, :type, :limit, :null, :sql_type, :precision, :scale
def initialize(name, default, sql_type = nil)
@name = name
@default = default
@type = @sql_type = sql_type
end
def human_name
@name.humanize
end
end
end
end
# Mock up necessities from ActionView
module ActionView
module Helpers
module ActionRecordHelper; end
class InstanceTag; end
end
end
# Set RAILS_ROOT appropriately fixture generation
tmp_dir = File.expand_path(File.join(File.dirname(__FILE__), "../fixtures/tmp"))
$stdout << "#{tmp_dir}\n\n"
FileUtils.mkdir_p tmp_dir
if defined? RADIANT_ROOT
RADIANT_ROOT.replace tmp_dir
else
RADIANT_ROOT = tmp_dir
end
if defined? RAILS_ROOT
RAILS_ROOT.replace tmp_dir
else
RAILS_ROOT = tmp_dir
end
require 'initializer'
# Mocks out the configuration
module Rails
def self.configuration
Rails::Configuration.new
end
end
require 'rails_generator'
share_as :AllGenerators do
include FileUtils
before(:all) do
ActiveRecord::Base.pluralize_table_names = true
mkdir_p "#{RADIANT_ROOT}/app"
mkdir_p "#{RADIANT_ROOT}/config"
mkdir_p "#{RADIANT_ROOT}/db"
mkdir_p "#{RADIANT_ROOT}/vendor/generators"
mkdir_p "#{RADIANT_ROOT}/vendor/extensions"
File.open("#{RADIANT_ROOT}/config/routes.rb", 'w') do |f|
f << "ActionController::Routing::Routes.draw do |map|\n\nend"
end
end
after(:all) do
%w(app db config vendor).each do |dir|
rm_rf File.join(RADIANT_ROOT, dir)
end
end
# Instantiates the Generator.
def build_generator(name, params)
Rails::Generator::Base.instance(name, params)
end
# Runs the +create+ command (like the command line does).
def run_generator(name, params)
silence_generator do
build_generator(name, params).command(:create).invoke!
end
end
# Silences the logger temporarily and returns the output as a String.
def silence_generator
logger_original = Rails::Generator::Base.logger
myout = StringIO.new
Rails::Generator::Base.logger = Rails::Generator::SimpleLogger.new(myout)
yield if block_given?
Rails::Generator::Base.logger = logger_original
myout.string
end
end
share_as :AllExtensionGenerators do
before(:all) do
cp_r File.join(BASE_ROOT, 'spec/fixtures/example_extension'), File.join(RADIANT_ROOT, 'vendor/extensions/example')
end
end
GENERATOR_SUPPORT_LOADED = true
end
Spec::Runner.configure do |config|
config.include(Spec::Matchers::GeneratorMatchers)
end
| 26.589928 | 120 | 0.684524 |
012c775c16b6987531ceb0970a0d97130a560a25 | 1,449 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 's3_html/version'
Gem::Specification.new do |spec|
spec.name = "s3_html"
spec.version = S3Html::VERSION
spec.authors = ["altantur"]
spec.email = ["[email protected]"]
spec.summary = %q{TODO: Write a short summary, because Rubygems requires one.}
spec.description = %q{TODO: Write a longer description or delete this line.}
spec.homepage = "TODO: Put your gem's website or public repo URL here."
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
# to allow pushing to a single host or delete this section to allow pushing to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
else
raise "RubyGems 2.0 or newer is required to protect against " \
"public gem pushes."
end
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.13"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.0"
end
| 39.162162 | 96 | 0.668047 |
337895e0fbcafa1e52dbe7e871dce9a187ec57c2 | 23,841 | # ==========================================
# CMock Project - Automatic Mock Generation for C
# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams
# [Released under MIT License. Please refer to license.txt for details]
# ==========================================
require File.expand_path(File.dirname(__FILE__)) + "/../test_helper"
require File.expand_path(File.dirname(__FILE__)) + '/../../lib/cmock_generator_utils'
describe CMockGeneratorUtils, "Verify CMockGeneratorUtils Module" do
before do
create_mocks :config, :unity_helper, :unity_helper
@config.expect :when_ptr, :compare_ptr
@config.expect :enforce_strict_ordering, false
@config.expect :plugins, []
@config.expect :plugins, []
@config.expect :plugins, []
@config.expect :plugins, []
@config.expect :plugins, []
@config.expect :plugins, []
@config.expect :treat_as, {'int' => 'INT','short' => 'INT16','long' => 'INT','char' => 'INT8','const char*' => 'STRING'}
@cmock_generator_utils_simple = CMockGeneratorUtils.new(@config, {:unity_helper => @unity_helper})
@config.expect :when_ptr, :smart
@config.expect :enforce_strict_ordering, true
@config.expect :plugins, [:array, :cexception, :return_thru_ptr, :ignore_arg, :ignore]
@config.expect :plugins, [:array, :cexception, :return_thru_ptr, :ignore_arg, :ignore]
@config.expect :plugins, [:array, :cexception, :return_thru_ptr, :ignore_arg, :ignore]
@config.expect :plugins, [:array, :cexception, :return_thru_ptr, :ignore_arg, :ignore]
@config.expect :plugins, [:array, :cexception, :return_thru_ptr, :ignore_arg, :ignore]
@config.expect :plugins, [:array, :cexception, :return_thru_ptr, :ignore_arg, :ignore]
@config.expect :treat_as, {'int' => 'INT','short' => 'INT16','long' => 'INT','char' => 'INT8','uint32_t' => 'HEX32','const char*' => 'STRING'}
@cmock_generator_utils_complex = CMockGeneratorUtils.new(@config, {:unity_helper => @unity_helper, :A=>1, :B=>2})
end
after do
end
it "have set up internal accessors correctly on init" do
assert_equal(false, @cmock_generator_utils_simple.arrays)
assert_equal(false, @cmock_generator_utils_simple.cexception)
end
it "have set up internal accessors correctly on init, complete with passed helpers" do
assert_equal(true, @cmock_generator_utils_complex.arrays)
assert_equal(true, @cmock_generator_utils_complex.cexception)
end
it "detect pointers and strings" do
assert_equal(false, @cmock_generator_utils_simple.ptr_or_str?('int'))
assert_equal(true, @cmock_generator_utils_simple.ptr_or_str?('int*'))
assert_equal(true, @cmock_generator_utils_simple.ptr_or_str?('char*'))
end
it "add code for a base expectation with no plugins" do
expected =
" CMOCK_MEM_INDEX_TYPE cmock_guts_index = CMock_Guts_MemNew(sizeof(CMOCK_Apple_CALL_INSTANCE));\n" +
" CMOCK_Apple_CALL_INSTANCE* cmock_call_instance = (CMOCK_Apple_CALL_INSTANCE*)CMock_Guts_GetAddressFor(cmock_guts_index);\n" +
" UNITY_TEST_ASSERT_NOT_NULL(cmock_call_instance, cmock_line, CMockStringOutOfMemory);\n" +
" memset(cmock_call_instance, 0, sizeof(*cmock_call_instance));\n" +
" Mock.Apple_CallInstance = CMock_Guts_MemChain(Mock.Apple_CallInstance, cmock_guts_index);\n" +
" cmock_call_instance->LineNumber = cmock_line;\n"
output = @cmock_generator_utils_simple.code_add_base_expectation("Apple")
assert_equal(expected, output)
end
it "add code for a base expectation with all plugins" do
expected =
" CMOCK_MEM_INDEX_TYPE cmock_guts_index = CMock_Guts_MemNew(sizeof(CMOCK_Apple_CALL_INSTANCE));\n" +
" CMOCK_Apple_CALL_INSTANCE* cmock_call_instance = (CMOCK_Apple_CALL_INSTANCE*)CMock_Guts_GetAddressFor(cmock_guts_index);\n" +
" UNITY_TEST_ASSERT_NOT_NULL(cmock_call_instance, cmock_line, CMockStringOutOfMemory);\n" +
" memset(cmock_call_instance, 0, sizeof(*cmock_call_instance));\n" +
" Mock.Apple_CallInstance = CMock_Guts_MemChain(Mock.Apple_CallInstance, cmock_guts_index);\n" +
" Mock.Apple_IgnoreBool = (int)0;\n" +
" cmock_call_instance->LineNumber = cmock_line;\n" +
" cmock_call_instance->CallOrder = ++GlobalExpectCount;\n" +
" cmock_call_instance->ExceptionToThrow = CEXCEPTION_NONE;\n"
output = @cmock_generator_utils_complex.code_add_base_expectation("Apple", true)
assert_equal(expected, output)
end
it "add code for a base expectation with all plugins and ordering not supported" do
expected =
" CMOCK_MEM_INDEX_TYPE cmock_guts_index = CMock_Guts_MemNew(sizeof(CMOCK_Apple_CALL_INSTANCE));\n" +
" CMOCK_Apple_CALL_INSTANCE* cmock_call_instance = (CMOCK_Apple_CALL_INSTANCE*)CMock_Guts_GetAddressFor(cmock_guts_index);\n" +
" UNITY_TEST_ASSERT_NOT_NULL(cmock_call_instance, cmock_line, CMockStringOutOfMemory);\n" +
" memset(cmock_call_instance, 0, sizeof(*cmock_call_instance));\n" +
" Mock.Apple_CallInstance = CMock_Guts_MemChain(Mock.Apple_CallInstance, cmock_guts_index);\n" +
" Mock.Apple_IgnoreBool = (int)0;\n" +
" cmock_call_instance->LineNumber = cmock_line;\n" +
" cmock_call_instance->ExceptionToThrow = CEXCEPTION_NONE;\n"
output = @cmock_generator_utils_complex.code_add_base_expectation("Apple", false)
assert_equal(expected, output)
end
it "add argument expectations for values when no array plugin" do
arg1 = { :name => "Orange", :const? => false, :type => 'int', :ptr? => false }
expected1 = " cmock_call_instance->Expected_Orange = Orange;\n"
arg2 = { :name => "Lemon", :const? => true, :type => 'const char*', :ptr? => false }
expected2 = " cmock_call_instance->Expected_Lemon = Lemon;\n"
arg3 = { :name => "Kiwi", :const? => false, :type => 'KIWI_T*', :ptr? => true }
expected3 = " cmock_call_instance->Expected_Kiwi = Kiwi;\n"
arg4 = { :name => "Lime", :const? => false, :type => 'LIME_T', :ptr? => false }
expected4 = " memcpy((void*)(&cmock_call_instance->Expected_Lime), (void*)(&Lime),\n" +
" sizeof(LIME_T[sizeof(Lime) == sizeof(LIME_T) ? 1 : -1])); /* add LIME_T to :treat_as_array if this causes an error */\n"
assert_equal(expected1, @cmock_generator_utils_simple.code_add_an_arg_expectation(arg1))
assert_equal(expected2, @cmock_generator_utils_simple.code_add_an_arg_expectation(arg2))
assert_equal(expected3, @cmock_generator_utils_simple.code_add_an_arg_expectation(arg3))
assert_equal(expected4, @cmock_generator_utils_simple.code_add_an_arg_expectation(arg4))
end
it "add argument expectations for values when array plugin enabled" do
arg1 = { :name => "Orange", :const? => false, :type => 'int', :ptr? => false }
expected1 = " cmock_call_instance->Expected_Orange = Orange;\n" +
" cmock_call_instance->IgnoreArg_Orange = 0;\n"
arg2 = { :name => "Lemon", :const? => true, :type => 'const char*', :ptr? => false }
expected2 = " cmock_call_instance->Expected_Lemon = Lemon;\n" +
" cmock_call_instance->Expected_Lemon_Depth = Lemon_Depth;\n" +
" cmock_call_instance->IgnoreArg_Lemon = 0;\n"
arg3 = { :name => "Kiwi", :const? => false, :type => 'KIWI_T*', :ptr? => true }
expected3 = " cmock_call_instance->Expected_Kiwi = Kiwi;\n" +
" cmock_call_instance->Expected_Kiwi_Depth = Kiwi_Depth;\n" +
" cmock_call_instance->IgnoreArg_Kiwi = 0;\n" +
" cmock_call_instance->ReturnThruPtr_Kiwi_Used = 0;\n"
arg4 = { :name => "Lime", :const? => false, :type => 'LIME_T', :ptr? => false }
expected4 = " memcpy((void*)(&cmock_call_instance->Expected_Lime), (void*)(&Lime),\n" +
" sizeof(LIME_T[sizeof(Lime) == sizeof(LIME_T) ? 1 : -1])); /* add LIME_T to :treat_as_array if this causes an error */\n" +
" cmock_call_instance->IgnoreArg_Lime = 0;\n"
assert_equal(expected1, @cmock_generator_utils_complex.code_add_an_arg_expectation(arg1))
assert_equal(expected2, @cmock_generator_utils_complex.code_add_an_arg_expectation(arg2, 'Lemon_Depth'))
assert_equal(expected3, @cmock_generator_utils_complex.code_add_an_arg_expectation(arg3, 'Lemon_Depth'))
assert_equal(expected4, @cmock_generator_utils_complex.code_add_an_arg_expectation(arg4))
end
it 'not have an argument loader when the function has no arguments' do
function = { :name => "Melon", :args_string => "void" }
assert_equal("", @cmock_generator_utils_complex.code_add_argument_loader(function))
end
it 'create an argument loader when the function has arguments' do
function = { :name => "Melon",
:args_string => "stuff",
:args => [test_arg[:int_ptr], test_arg[:mytype], test_arg[:string]]
}
expected = "void CMockExpectParameters_Melon(CMOCK_Melon_CALL_INSTANCE* cmock_call_instance, stuff);\n" +
"void CMockExpectParameters_Melon(CMOCK_Melon_CALL_INSTANCE* cmock_call_instance, stuff)\n{\n" +
" cmock_call_instance->Expected_MyIntPtr = MyIntPtr;\n" +
" memcpy((void*)(&cmock_call_instance->Expected_MyMyType), (void*)(&MyMyType),\n" +
" sizeof(MY_TYPE[sizeof(MyMyType) == sizeof(MY_TYPE) ? 1 : -1])); /* add MY_TYPE to :treat_as_array if this causes an error */\n" +
" cmock_call_instance->Expected_MyStr = MyStr;\n" +
"}\n\n"
assert_equal(expected, @cmock_generator_utils_simple.code_add_argument_loader(function))
end
it 'create an argument loader when the function has arguments supporting arrays' do
function = { :name => "Melon",
:args_string => "stuff",
:args => [test_arg[:int_ptr], test_arg[:mytype], test_arg[:string]]
}
expected = "void CMockExpectParameters_Melon(CMOCK_Melon_CALL_INSTANCE* cmock_call_instance, int* MyIntPtr, int MyIntPtr_Depth, const MY_TYPE MyMyType, const char* MyStr);\n" +
"void CMockExpectParameters_Melon(CMOCK_Melon_CALL_INSTANCE* cmock_call_instance, int* MyIntPtr, int MyIntPtr_Depth, const MY_TYPE MyMyType, const char* MyStr)\n{\n" +
" cmock_call_instance->Expected_MyIntPtr = MyIntPtr;\n" +
" cmock_call_instance->Expected_MyIntPtr_Depth = MyIntPtr_Depth;\n" +
" cmock_call_instance->IgnoreArg_MyIntPtr = 0;\n" +
" cmock_call_instance->ReturnThruPtr_MyIntPtr_Used = 0;\n" +
" memcpy((void*)(&cmock_call_instance->Expected_MyMyType), (void*)(&MyMyType),\n" +
" sizeof(MY_TYPE[sizeof(MyMyType) == sizeof(MY_TYPE) ? 1 : -1])); /* add MY_TYPE to :treat_as_array if this causes an error */\n" +
" cmock_call_instance->IgnoreArg_MyMyType = 0;\n" +
" cmock_call_instance->Expected_MyStr = MyStr;\n" +
" cmock_call_instance->IgnoreArg_MyStr = 0;\n" +
"}\n\n"
assert_equal(expected, @cmock_generator_utils_complex.code_add_argument_loader(function))
end
it 'create an argument loader when the function has pointer arguments supporting arrays' do
function = { :name => "Melon",
:args_string => "stuff",
:args => [test_arg[:const_ptr], test_arg[:double_ptr]]
}
expected = "void CMockExpectParameters_Melon(CMOCK_Melon_CALL_INSTANCE* cmock_call_instance, int* const MyConstPtr, int MyConstPtr_Depth, int const** MyDoublePtr, int MyDoublePtr_Depth);\n" +
"void CMockExpectParameters_Melon(CMOCK_Melon_CALL_INSTANCE* cmock_call_instance, int* const MyConstPtr, int MyConstPtr_Depth, int const** MyDoublePtr, int MyDoublePtr_Depth)\n{\n" +
" cmock_call_instance->Expected_MyConstPtr = MyConstPtr;\n" +
" cmock_call_instance->Expected_MyConstPtr_Depth = MyConstPtr_Depth;\n" +
" cmock_call_instance->IgnoreArg_MyConstPtr = 0;\n" +
" cmock_call_instance->ReturnThruPtr_MyConstPtr_Used = 0;\n" +
" cmock_call_instance->Expected_MyDoublePtr = MyDoublePtr;\n" +
" cmock_call_instance->Expected_MyDoublePtr_Depth = MyDoublePtr_Depth;\n" +
" cmock_call_instance->IgnoreArg_MyDoublePtr = 0;\n" +
"}\n\n"
assert_equal(expected, @cmock_generator_utils_complex.code_add_argument_loader(function))
end
it "not call argument loader if there are no arguments to actually use for this function" do
function = { :name => "Pineapple", :args_string => "void" }
assert_equal("", @cmock_generator_utils_complex.code_call_argument_loader(function))
end
it 'call an argument loader when the function has arguments' do
function = { :name => "Pineapple",
:args_string => "stuff",
:args => [test_arg[:int_ptr], test_arg[:mytype], test_arg[:string]]
}
expected = " CMockExpectParameters_Pineapple(cmock_call_instance, MyIntPtr, MyMyType, MyStr);\n"
assert_equal(expected, @cmock_generator_utils_simple.code_call_argument_loader(function))
end
it 'call an argument loader when the function has arguments with arrays' do
function = { :name => "Pineapple",
:args_string => "stuff",
:args => [test_arg[:int_ptr], test_arg[:mytype], test_arg[:string]]
}
expected = " CMockExpectParameters_Pineapple(cmock_call_instance, MyIntPtr, 1, MyMyType, MyStr);\n"
assert_equal(expected, @cmock_generator_utils_complex.code_call_argument_loader(function))
end
it 'handle a simple assert when requested' do
function = { :name => 'Pear' }
arg = test_arg[:int]
expected = " {\n" +
" UNITY_SET_DETAILS(CMockString_Pear,CMockString_MyInt);\n" +
" UNITY_TEST_ASSERT_EQUAL_INT(cmock_call_instance->Expected_MyInt, MyInt, cmock_line, CMockStringMismatch);\n" +
" }\n"
@unity_helper.expect :nil?, false
@unity_helper.expect :get_helper, ['UNITY_TEST_ASSERT_EQUAL_INT', ''], ['int']
assert_equal(expected, @cmock_generator_utils_simple.code_verify_an_arg_expectation(function, arg))
end
it 'handle a pointer comparison when configured to do so' do
function = { :name => 'Pear' }
arg = test_arg[:int_ptr]
expected = " {\n" +
" UNITY_SET_DETAILS(CMockString_Pear,CMockString_MyIntPtr);\n" +
" UNITY_TEST_ASSERT_EQUAL_PTR(cmock_call_instance->Expected_MyIntPtr, MyIntPtr, cmock_line, CMockStringMismatch);\n" +
" }\n"
assert_equal(expected, @cmock_generator_utils_simple.code_verify_an_arg_expectation(function, arg))
end
it 'handle const char as string compares ' do
function = { :name => 'Pear' }
arg = test_arg[:string]
expected = " {\n" +
" UNITY_SET_DETAILS(CMockString_Pear,CMockString_MyStr);\n" +
" UNITY_TEST_ASSERT_EQUAL_STRING(cmock_call_instance->Expected_MyStr, MyStr, cmock_line, CMockStringMismatch);\n" +
" }\n"
@unity_helper.expect :nil?, false
@unity_helper.expect :get_helper, ['UNITY_TEST_ASSERT_EQUAL_STRING',''], ['const char*']
assert_equal(expected, @cmock_generator_utils_simple.code_verify_an_arg_expectation(function, arg))
end
it 'handle custom types as memory compares when we have no better way to do it' do
function = { :name => 'Pear' }
arg = test_arg[:mytype]
expected = " {\n" +
" UNITY_SET_DETAILS(CMockString_Pear,CMockString_MyMyType);\n" +
" UNITY_TEST_ASSERT_EQUAL_MEMORY((void*)(&cmock_call_instance->Expected_MyMyType), (void*)(&MyMyType), sizeof(MY_TYPE), cmock_line, CMockStringMismatch);\n" +
" }\n"
@unity_helper.expect :nil?, false
@unity_helper.expect :get_helper, ['UNITY_TEST_ASSERT_EQUAL_MEMORY','&'], ['MY_TYPE']
assert_equal(expected, @cmock_generator_utils_simple.code_verify_an_arg_expectation(function, arg))
end
it 'handle custom types with custom handlers when available, even if they do not support the extra message' do
function = { :name => 'Pear' }
arg = test_arg[:mytype]
expected = " {\n" +
" UNITY_SET_DETAILS(CMockString_Pear,CMockString_MyMyType);\n" +
" UNITY_TEST_ASSERT_EQUAL_MY_TYPE(cmock_call_instance->Expected_MyMyType, MyMyType, cmock_line, CMockStringMismatch);\n" +
" }\n"
@unity_helper.expect :nil?, false
@unity_helper.expect :get_helper, ['UNITY_TEST_ASSERT_EQUAL_MY_TYPE',''], ['MY_TYPE']
assert_equal(expected, @cmock_generator_utils_simple.code_verify_an_arg_expectation(function, arg))
end
it 'handle pointers to custom types with array handlers, even if the array extension is turned off' do
function = { :name => 'Pear' }
arg = test_arg[:mytype]
expected = " {\n" +
" UNITY_SET_DETAILS(CMockString_Pear,CMockString_MyMyType);\n" +
" UNITY_TEST_ASSERT_EQUAL_MY_TYPE_ARRAY(&cmock_call_instance->Expected_MyMyType, &MyMyType, 1, cmock_line, CMockStringMismatch);\n" +
" }\n"
@unity_helper.expect :nil?, false
@unity_helper.expect :get_helper, ['UNITY_TEST_ASSERT_EQUAL_MY_TYPE_ARRAY','&'], ['MY_TYPE']
assert_equal(expected, @cmock_generator_utils_simple.code_verify_an_arg_expectation(function, arg))
end
it 'handle a simple assert when requested with array plugin enabled' do
function = { :name => 'Pear' }
arg = test_arg[:int]
expected = " if (!cmock_call_instance->IgnoreArg_MyInt)\n" +
" {\n" +
" UNITY_SET_DETAILS(CMockString_Pear,CMockString_MyInt);\n" +
" UNITY_TEST_ASSERT_EQUAL_INT(cmock_call_instance->Expected_MyInt, MyInt, cmock_line, CMockStringMismatch);\n" +
" }\n"
@unity_helper.expect :nil?, false
@unity_helper.expect :get_helper, ['UNITY_TEST_ASSERT_EQUAL_INT',''], ['int']
assert_equal(expected, @cmock_generator_utils_complex.code_verify_an_arg_expectation(function, arg))
end
it 'handle an array comparison with array plugin enabled' do
function = { :name => 'Pear' }
arg = test_arg[:int_ptr]
expected = " if (!cmock_call_instance->IgnoreArg_MyIntPtr)\n" +
" {\n" +
" UNITY_SET_DETAILS(CMockString_Pear,CMockString_MyIntPtr);\n" +
" if (cmock_call_instance->Expected_MyIntPtr == NULL)\n" +
" { UNITY_TEST_ASSERT_NULL(MyIntPtr, cmock_line, CMockStringExpNULL); }\n" +
" else if (cmock_call_instance->Expected_MyIntPtr_Depth == 0)\n" +
" { UNITY_TEST_ASSERT_EQUAL_PTR(cmock_call_instance->Expected_MyIntPtr, MyIntPtr, cmock_line, CMockStringMismatch); }\n" +
" else\n" +
" { UNITY_TEST_ASSERT_EQUAL_INT_ARRAY(cmock_call_instance->Expected_MyIntPtr, MyIntPtr, cmock_call_instance->Expected_MyIntPtr_Depth, cmock_line, CMockStringMismatch); }\n" +
" }\n"
@unity_helper.expect :nil?, false
@unity_helper.expect :get_helper, ['UNITY_TEST_ASSERT_EQUAL_INT_ARRAY',''], ['int*']
assert_equal(expected, @cmock_generator_utils_complex.code_verify_an_arg_expectation(function, arg))
end
it 'handle const char as string compares with array plugin enabled' do
function = { :name => 'Pear' }
arg = test_arg[:string]
expected = " if (!cmock_call_instance->IgnoreArg_MyStr)\n" +
" {\n" +
" UNITY_SET_DETAILS(CMockString_Pear,CMockString_MyStr);\n" +
" UNITY_TEST_ASSERT_EQUAL_STRING(cmock_call_instance->Expected_MyStr, MyStr, cmock_line, CMockStringMismatch);\n" +
" }\n"
@unity_helper.expect :nil?, false
@unity_helper.expect :get_helper, ['UNITY_TEST_ASSERT_EQUAL_STRING',''], ['const char*']
assert_equal(expected, @cmock_generator_utils_complex.code_verify_an_arg_expectation(function, arg))
end
it 'handle custom types as memory compares when we have no better way to do it with array plugin enabled' do
function = { :name => 'Pear' }
arg = test_arg[:mytype]
expected = " if (!cmock_call_instance->IgnoreArg_MyMyType)\n" +
" {\n" +
" UNITY_SET_DETAILS(CMockString_Pear,CMockString_MyMyType);\n" +
" if (cmock_call_instance->Expected_MyMyType == NULL)\n" +
" { UNITY_TEST_ASSERT_NULL(MyMyType, cmock_line, CMockStringExpNULL); }\n" +
" else\n" +
" { UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY((void*)(cmock_call_instance->Expected_MyMyType), (void*)(MyMyType), sizeof(MY_TYPE), 1, cmock_line, CMockStringMismatch); }\n" +
" }\n"
@unity_helper.expect :nil?, false
@unity_helper.expect :get_helper, ['UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY', ''], ['MY_TYPE']
assert_equal(expected, @cmock_generator_utils_complex.code_verify_an_arg_expectation(function, arg))
end
it 'handle custom types with custom handlers when available, even if they do not support the extra message with array plugin enabled' do
function = { :name => 'Pear' }
arg = test_arg[:mytype]
expected = " if (!cmock_call_instance->IgnoreArg_MyMyType)\n" +
" {\n" +
" UNITY_SET_DETAILS(CMockString_Pear,CMockString_MyMyType);\n" +
" UNITY_TEST_ASSERT_EQUAL_MY_TYPE(cmock_call_instance->Expected_MyMyType, MyMyType, cmock_line, CMockStringMismatch);\n" +
" }\n"
@unity_helper.expect :nil?, false
@unity_helper.expect :get_helper, ['UNITY_TEST_ASSERT_EQUAL_MY_TYPE', ''], ['MY_TYPE']
assert_equal(expected, @cmock_generator_utils_complex.code_verify_an_arg_expectation(function, arg))
end
it 'handle custom types with array handlers when array plugin is enabled' do
function = { :name => 'Pear' }
arg = test_arg[:mytype_ptr]
expected = " if (!cmock_call_instance->IgnoreArg_MyMyTypePtr)\n" +
" {\n" +
" UNITY_SET_DETAILS(CMockString_Pear,CMockString_MyMyTypePtr);\n" +
" if (cmock_call_instance->Expected_MyMyTypePtr == NULL)\n" +
" { UNITY_TEST_ASSERT_NULL(MyMyTypePtr, cmock_line, CMockStringExpNULL); }\n" +
" else if (cmock_call_instance->Expected_MyMyTypePtr_Depth == 0)\n" +
" { UNITY_TEST_ASSERT_EQUAL_PTR(cmock_call_instance->Expected_MyMyTypePtr, MyMyTypePtr, cmock_line, CMockStringMismatch); }\n" +
" else\n" +
" { UNITY_TEST_ASSERT_EQUAL_MY_TYPE_ARRAY(cmock_call_instance->Expected_MyMyTypePtr, MyMyTypePtr, cmock_call_instance->Expected_MyMyTypePtr_Depth, cmock_line, CMockStringMismatch); }\n" +
" }\n"
@unity_helper.expect :nil?, false
@unity_helper.expect :get_helper, ['UNITY_TEST_ASSERT_EQUAL_MY_TYPE_ARRAY', ''], ['MY_TYPE*']
assert_equal(expected, @cmock_generator_utils_complex.code_verify_an_arg_expectation(function, arg))
end
it 'handle custom types with array handlers when array plugin is enabled for non-array types' do
function = { :name => 'Pear' }
arg = test_arg[:mytype]
expected = " if (!cmock_call_instance->IgnoreArg_MyMyType)\n" +
" {\n" +
" UNITY_SET_DETAILS(CMockString_Pear,CMockString_MyMyType);\n" +
" UNITY_TEST_ASSERT_EQUAL_MY_TYPE_ARRAY(&cmock_call_instance->Expected_MyMyType, &MyMyType, 1, cmock_line, CMockStringMismatch);\n" +
" }\n"
@unity_helper.expect :nil?, false
@unity_helper.expect :get_helper, ['UNITY_TEST_ASSERT_EQUAL_MY_TYPE_ARRAY', '&'], ['MY_TYPE']
assert_equal(expected, @cmock_generator_utils_complex.code_verify_an_arg_expectation(function, arg))
end
end
| 59.30597 | 207 | 0.676104 |
e8aecc3a4a2f28dcc383a9fe849bdcdc521c9eb9 | 154 | class AddHelpPageCountToGame < ActiveRecord::Migration
def change
add_column :games, :help_pages_count, :integer, default: 0, null: false
end
end
| 25.666667 | 75 | 0.766234 |
bba4f4de8c43a67866bbd78379f8575632146645 | 733 | require 'test_helper'
class BlogCategoriesControllerTest < ActionController::TestCase
test "should get index" do
get :index
assert_response :success
end
test "should get show" do
get :show
assert_response :success
end
test "should get new" do
get :new
assert_response :success
end
test "should get create" do
get :create
assert_response :success
end
test "should get edit" do
get :edit
assert_response :success
end
test "should get update" do
get :update
assert_response :success
end
test "should get manage" do
get :manage
assert_response :success
end
test "should get destroy" do
get :destroy
assert_response :success
end
end
| 16.288889 | 63 | 0.687585 |
03afc2b2953701a1868780c899e78f2bed8ff263 | 5,950 | # -*- encoding: utf-8 -*-
class Library < ActiveRecord::Base
attr_accessible :name, :display_name, :short_display_name, :zip_code, :street,
:locality, :region, :telephone_number_1, :telephone_number_2, :fax_number,
:note, :call_number_rows, :call_number_delimiter, :library_group_id,
:country_id, :opening_hour, :isil, :position, :agent_id
include MasterModel
default_scope :order => 'libraries.position'
#scope :real, where('id != 1')
scope :real, where('1 = 1')
has_many :shelves, :order => 'shelves.position'
belongs_to :library_group, :validate => true
has_many :events, :include => :event_category
#belongs_to :holding_agent, :polymorphic => true, :validate => true
belongs_to :agent #, :validate => true
has_many :inter_library_loans, :foreign_key => 'to_library_id'
has_many :inter_library_loans, :foreign_key => 'from_library_id'
has_many :users
belongs_to :country
# has_many :budgets
has_many :statistics
has_many :library_reports
extend FriendlyId
friendly_id :name
geocoded_by :address
#enju_calil_library
has_paper_trail
searchable do
text :name, :display_name, :note, :address
time :created_at
time :updated_at
integer :position
end
#validates_associated :library_group, :holding_agent
validates_associated :library_group, :agent
validates_presence_of :short_display_name, :library_group, :agent
validates_uniqueness_of :short_display_name, :case_sensitive => false
validates :display_name, :uniqueness => true
validates :name, :format => {:with => /^[a-z][0-9a-z]{2,254}$/}
before_validation :set_agent, :on => :create
#before_save :set_calil_neighborhood_library
after_validation :geocode, :if => :address_changed?
after_create :create_shelf
after_save :clear_all_cache
after_destroy :clear_all_cache
# ManifestationsController#index の manifestation をキャッシュしているため
# 図書館更新時は manifestation.updated_at を更新する
after_update :touch_manifestation, :if => lambda{ self.display_name_changed?}
def touch_manifestation
ActiveRecord::Base.connection.update_sql("update manifestations set updated_at = current_timestamp where id in (select manifestation_id from items where shelf_id in (select id from shelves where library_id = #{self.id}))")
end
paginates_per 10
def self.all_cache
if Rails.env == 'production'
Rails.cache.fetch('library_all'){Library.all}
else
Library.all
end
end
def in_process_shelf
self.shelves.find_by_open_access(9)
end
def article_shelf
self.shelves.find_by_open_access(10)
end
def excludescope_shelf_ids
self.shelves.collect {|c| c.id}
end
def clear_all_cache
Rails.cache.delete('library_all')
end
def set_agent
self.agent = Agent.new(
:full_name => self.name
)
end
def create_shelf
#Shelf.create!(:name => "#{self.name}_default", :library => self)
shelf_name = self.name
@shelf_default = Shelf.new(:name => "#{shelf_name}_default", :library_id => self.id)
@shelf_in_process = Shelf.new(:name => "#{shelf_name}_in_process", :display_name => I18n.t('activerecord.attributes.shelf.in_process'), :open_access => 9,:library_id => self.id)
@shelf_default.save!
@shelf_in_process.save!
end
def closed?(date)
return false if events.blank?
events.closing_days.each do |c|
return true if c.start_at.beginning_of_day <= date.beginning_of_day && c.end_at.end_of_day >= date.beginning_of_day
end
false
end
def web?
return true if self.id == 1
false
end
def self.web
Library.find(1) rescue nil
end
def address(locale = I18n.locale)
case locale.to_sym
when :ja
"#{self.region.to_s.localize(locale)}#{self.locality.to_s.localize(locale)}#{self.street.to_s.localize(locale)}"
else
"#{self.street.to_s.localize(locale)} #{self.locality.to_s.localize(locale)} #{self.region.to_s.localize(locale)}"
end
rescue
nil
end
def destroy?
#return false unless self.shelves.empty? && self.users.empty? && self.events.empty? && self.budgets.empty?
# return false unless self.shelves.size == 1 && self.shelves[0].open_access == 9 && self.shelves[0].items.empty? && self.users.empty? && self.events.empty? && self.budgets.empty?
return false unless self.shelves.size == 1 && self.shelves[0].open_access == 9 && self.shelves[0].items.empty? && self.users.empty? && self.events.empty?
return false if self.id == 1
return true
end
def address_changed?
return true if region_changed? or locality_changed? or street_changed?
false
end
end
# == Schema Information
#
# Table name: libraries
#
# id :integer not null, primary key
# agent_id :integer
# agent_type :string(255)
# name :string(255) not null
# display_name :text
# short_display_name :string(255) not null
# zip_code :string(255)
# street :text
# locality :text
# region :text
# telephone_number_1 :string(255)
# telephone_number_2 :string(255)
# fax_number :string(255)
# note :text
# call_number_rows :integer default(1), not null
# call_number_delimiter :string(255) default("|"), not null
# library_group_id :integer default(1), not null
# users_count :integer default(0), not null
# position :integer
# country_id :integer
# created_at :datetime
# updated_at :datetime
# deleted_at :datetime
# opening_hour :text
# latitude :float
# longitude :float
# calil_systemid :string(255)
# calil_neighborhood_systemid :text
#
| 33.615819 | 226 | 0.658824 |
ab05b476522068e5f7634d84602873a02873132e | 2,839 | require 'glib2'
require 'gnomevfs.so'
module GnomeVFS
class FileInfo
alias setuid? suid?
alias setgid? sgid?
def <=>(other)
unless other.is_a?(FileInfo)
nil
else
mtime <=> other.mtime
end
end
include Comparable
end
class File
class <<self
def foreach(uri, *args, &block)
open(uri, *args){|f| f.each(&block) }
end
def read(uri, length=nil, offset=nil)
if offset.nil? or offset==0
open(uri, OpenMode::READ){|f|
f.read(length)
}
else
open(uri, OpenMode::READ | OpenMode::RANDOM){|f|
f.seek(offset)
f.read(length)
}
end
end
def readlines(uri, *args)
open(uri){|f| f.readlines(*args) }
end
def readlink(uri)
lstat(uri).symlink_to
end
def utime(atime, mtime, *rest)
info = FileInfo.new
info.set_utime(atime, mtime)
rest.each{|item|
File.set_file_info(item, info, FileInfo::SET_TIME)
}
rest.length
end
def exists?(uri)
unless uri.is_a?(GnomeVFS::URI)
uri = GnomeVFS::URI.new(uri)
end
uri.exists?
end
alias exist? exists?
def ftype(uri) lstat(uri).ftype end
def file?(uri) lstat(uri).file? end
def directory?(uri) lstat(uri).directory? end
def symlink?(uri) lstat(uri).symlink? end
def chardev?(uri) lstat(uri).chardev? end
def blockdev?(uri) lstat(uri).blockdev? end
def socket?(uri) lstat(uri).socket? end
def pipe?(uri) lstat(uri).pipe? end
def size?(uri) stat(uri).size? end
def zero?(uri) stat(uri).zero? end
def readable?(uri) stat(uri).readable? end
def writable?(uri) stat(uri).writable? end
def executable?(uri) stat(uri).executable? end
def readable_real?(uri) stat(uri).readable_real? end
def writable_real?(uri) stat(uri).writable_real? end
def executable_real?(uri) stat(uri).executable_real? end
def owned?(uri) stat(uri).owned? end
def grpowned?(uri) stat(uri).grpowned? end
def sticky?(uri) stat(uri).sticky? end
def setuid?(uri) stat(uri).setuid? end
def setgid?(uri) stat(uri).setgid? end
def size(uri) stat(uri).size end
def atime(uri) stat(uri).atime end
def mtime(uri) stat(uri).mtime end
def ctime(uri) stat(uri).ctime end
end
def atime; stat.atime end
def mtime; stat.mtime end
def ctime; stat.ctime end
def pos=(arg)
seek(arg)
end
end
LOG_DOMAIN = "libgnomevfs"
end
GLib::Log.set_log_domain(GnomeVFS::LOG_DOMAIN)
GLib::Log.set_log_domain("gnome-vfs-modules")
GLib::Log.set_log_domain("GnomeVFSMonikers")
| 25.576577 | 62 | 0.579782 |
26ff2efd6b318e05bf39e66676db00676add152a | 4,282 | 1.upto(14) do |i|
Name "gt cds test #{i}"
Keywords "gt_cds"
Test do
run_test "#{$bin}gt cds -minorflen 1 -startcodon yes " +
"-seqfile #{$testdata}gt_cds_test_#{i}.fas -matchdesc " +
"#{$testdata}gt_cds_test_#{i}.in"
run "diff #{last_stdout} #{$testdata}gt_cds_test_#{i}.out"
end
end
Name "gt cds error message"
Keywords "gt_cds"
Test do
run "#{$bin}gt gff3 -offset 1000 #{$testdata}gt_cds_test_1.in | " +
"#{$bin}gt cds -matchdesc -seqfile #{$testdata}gt_cds_test_1.fas -", :retval => 1
grep last_stderr, "Has the sequence-region to sequence mapping been defined correctly"
end
1.upto(14) do |i|
Name "gt cds test #{i} (-usedesc)"
Keywords "gt_cds usedesc"
Test do
run_test "#{$bin}gt cds -minorflen 1 -startcodon yes -usedesc " +
"-seqfile #{$testdata}gt_cds_test_#{i}.fas " +
"#{$testdata}gt_cds_test_#{i}.in"
run "diff #{last_stdout} #{$testdata}gt_cds_test_#{i}.out"
end
end
Name "gt cds test (description range)"
Keywords "gt_cds usedesc"
Test do
run_test "#{$bin}gt cds -minorflen 1 -usedesc -seqfile " +
"#{$testdata}gt_cds_test_descrange.fas " +
"#{$testdata}gt_cds_test_descrange.in"
run "diff #{last_stdout} #{$testdata}gt_cds_test_descrange.out"
end
Name "gt cds test (multi description)"
Keywords "gt_cds usedesc"
Test do
run_test "#{$bin}gt cds -minorflen 1 -usedesc -seqfile " +
"#{$testdata}gt_cds_descrange_multi.fas " +
"#{$testdata}gt_cds_descrange_multi.in"
run "diff #{last_stdout} #{$testdata}gt_cds_descrange_multi.out"
end
Name "gt cds test (multi description fail 1)"
Keywords "gt_cds usedesc"
Test do
run_test("#{$bin}gt cds -usedesc -seqfile " +
"#{$testdata}gt_cds_descrange_multi_fail_1.fas " +
"#{$testdata}gt_cds_test_descrange.in", :retval => 1)
grep last_stderr, "contain multiple sequences with ID"
end
Name "gt cds test (multi description fail 2)"
Keywords "gt_cds usedesc"
Test do
run_test("#{$bin}gt cds -usedesc -seqfile " +
"#{$testdata}gt_cds_descrange_multi_fail_2.fas " +
"#{$testdata}gt_cds_test_descrange.in", :retval => 1)
grep last_stderr, "contain multiple sequences with ID"
end
Name "gt cds test (wrong ID)"
Keywords "gt_cds usedesc"
Test do
run_test("#{$bin}gt cds -usedesc -seqfile " +
"#{$testdata}gt_cds_descrange_wrong_id.fas " +
"#{$testdata}gt_cds_test_descrange.in", :retval => 1)
grep last_stderr, "sequence with ID"
end
Name "gt cds test (wrong range)"
Keywords "gt_cds usedesc"
Test do
run_test("#{$bin}gt cds -usedesc -seqfile " +
"#{$testdata}gt_cds_descrange_wrong_range.fas " +
"#{$testdata}gt_cds_test_descrange.in", :retval => 1)
grep last_stderr, "sequence with ID"
end
Name "gt cds test (-startcodon no -finalstopcodon no)"
Keywords "gt_cds"
Test do
run_test "#{$bin}gt cds -startcodon no -finalstopcodon no -seqfile " +
"#{$testdata}U89959_genomic.fas -matchdesc " +
"#{$testdata}gt_cds_nostartcodon_nofinalstopcodon.in"
run "diff #{last_stdout} " +
"#{$testdata}gt_cds_nostartcodon_nofinalstopcodon.out"
end
Name "gt cds test (nGASP)"
Keywords "gt_cds nGASP"
Test do
run_test "#{$bin}gt cds -startcodon yes -finalstopcodon no -minorflen 64 " +
"-seqfile #{$testdata}nGASP/III.fas -usedesc " +
"#{$testdata}nGASP/resIII.gff3"
run "diff #{last_stdout} #{$testdata}nGASP/resIIIcds.gff3"
end
Name "gt cds test (U89959)"
Keywords "gt_cds"
Test do
run_test "#{$bin}gt cds -seqfile #{$testdata}U89959_genomic.fas " +
"-matchdesc #{$testdata}U89959_csas.gff3"
run "diff #{last_stdout} #{$testdata}U89959_cds.gff3"
end
Name "gt cds test (not sorted)"
Keywords "gt_cds"
Test do
run_test "#{$bin}gt cds -seqfile #{$testdata}U89959_genomic.fas " +
"-matchdesc #{$testdata}not_sorted.gff3", :retval => 1
grep last_stderr, "is not sorted"
end
if $gttestdata then
Name "gt cds bug"
Keywords "gt_cds"
Test do
run_test "#{$bin}gt cds -startcodon yes -minorflen 1 " +
"-seqfile #{$gttestdata}cds/marker_region.fas " +
"-matchdesc #{$gttestdata}cds/marker_bug.gff3"
run "diff #{last_stdout} #{$gttestdata}cds/marker_bug.out"
end
end
| 32.938462 | 88 | 0.663008 |
ace65ec284adaeca8a5e0fc1c4b7ec02b35b31ba | 2,034 | #
# Be sure to run `pod lib lint iAirportsDB.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'iAirportsDB'
s.version = '3.0.0'
s.summary = 'Quickly find airports near a location'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
Airports, heliports, seaplane bases, and balloonports can quickly be found near a location or by identifier. Supporting information such as runways and frequencies are provided. Information is global. The library is Swift but Objective C is supported. Behind the scenes Core Data using sqlite provides the framework for fast lookups.
DESC
s.homepage = 'https://github.com/ckhsponge/iAirportsDB'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Chris Hobbs' => '[email protected]' }
s.source = { :git => 'https://github.com/ckhsponge/iAirportsDB.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '9.3'
s.source_files = 'iAirportsDB/Classes/**/*'
s.resource_bundles = {
'resourcebundle' => ['iAirportsDB/Assets/*']
}
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
s.ios.deployment_target = '9.3'
s.osx.deployment_target = '10.9'
s.tvos.deployment_target = '9.0'
s.watchos.deployment_target = '3.0'
end
| 42.375 | 333 | 0.673058 |
61ea6cd3f4b7aa46f4ee85354769b16adc996f60 | 182 | require 'gom'
require 'gom/couchdb-adapter'
require File.join(File.dirname(__FILE__), "storage")
GOM::Storage::Adapter.register :elasticsearch, GOM::Storage::ElasticSearch::Adapter
| 30.333333 | 83 | 0.785714 |
e9bbdcad7f6db53019a6100f3e92995340cbc79c | 231 | Alchemy::Modules.register_module({
engine_name: 'spree',
name: 'solidus',
navigation: {
controller: 'spree/admin/orders',
action: 'index',
name: 'Shop',
image: 'alchemy/solidus/alchemy_module_icon.png'
}
})
| 21 | 52 | 0.658009 |
ab67504f8513278e414f79b345a6d655d546ecce | 250 | require 'test_helper'
class UserTest < ActiveSupport::TestCase
test 'should not save without email or password' do
invalid = User.new
assert_not invalid.valid?
invalid[:email] = '[email protected]'
assert_not invalid.valid?
end
end
| 22.727273 | 53 | 0.724 |
e962ddaececec91a575de6dbaef278b34df0e891 | 1,263 | # 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-dynamodb/types'
require_relative 'aws-sdk-dynamodb/client_api'
require_relative 'aws-sdk-dynamodb/client'
require_relative 'aws-sdk-dynamodb/errors'
require_relative 'aws-sdk-dynamodb/waiters'
require_relative 'aws-sdk-dynamodb/resource'
require_relative 'aws-sdk-dynamodb/table'
require_relative 'aws-sdk-dynamodb/customizations'
# This module provides support for Amazon DynamoDB. This module is available in the
# `aws-sdk-dynamodb` 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.
#
# See {Client} for more information.
#
# # Errors
#
# Errors returned from Amazon DynamoDB all
# extend {Errors::ServiceError}.
#
# begin
# # do stuff
# rescue Aws::DynamoDB::Errors::ServiceError
# # rescues all service API errors
# end
#
# See {Errors} for more information.
#
# @service
module Aws::DynamoDB
GEM_VERSION = '1.15.0'
end
| 25.26 | 83 | 0.751386 |
281906e6a30595bbcc0783f81e1bbbcd7c5b001d | 236 | class Users < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.boolean :admin, :default => false
t.string :identifier
t.string :token
end
end
def self.down
drop_table :users
end
end | 18.153846 | 41 | 0.644068 |
7a2bd8d4074a2219ce65b89f66a56e7c65501e05 | 394 | class CreateAbuseReportSubject < ActiveRecord::Migration[5.2]
def change
create_table :abuse_report_subjects, id: :uuid do |t|
t.references :abuse_report, type: :uuid, foreign_key: true
t.references :account, type: :uuid, foreign_key: true
t.references :project, type: :uuid, foreign_key: true
t.references :issue, type: :uuid, foreign_key: true
end
end
end
| 35.818182 | 64 | 0.708122 |
bf28f59631b318663e02ee3c544c2f5e32c706a6 | 212 | module VCAP::CloudController
class OrganizationManager < Sequel::Model(:organizations_managers)
include OrganizationRoleMixin
def type
@type ||= RoleTypes::ORGANIZATION_MANAGER
end
end
end
| 21.2 | 68 | 0.75 |
21325d53fe0ab226dcf40bbde58547d708d63967 | 373 | #!/bin/ruby
require_relative 'player.rb'
require_relative 'gather.rb'
require_relative 'cards.rb'
require_relative 'game.rb'
require_relative 'dealing.rb'
system("clear")
Gather.players(2)
while Game.keep_going?()
Dealing.rotate()
Cards.newdeck()
Cards.shuffle()
Player.draw()
Cards.set_trump()
Game.change_cards()
Player.play()
Player.declare_score()
end
| 16.954545 | 29 | 0.745308 |
7a0b3f52717170d8f7363f3deef21438a1d0b442 | 601 | module Doorkeeper
class Application
include Mongoid::Document
include Mongoid::Timestamps
self.store_in collection: :oauth_applications
field :name, :type => String
field :uid, :type => String
field :secret, :type => String
field :redirect_uri, :type => String
index({ uid: 1 }, { unique: true })
has_many :authorized_tokens, :class_name => "Doorkeeper::AccessToken"
def self.authorized_for(resource_owner)
ids = AccessToken.where(:resource_owner_id => resource_owner.id, :revoked_at => nil).map(&:application_id)
find(ids)
end
end
end
| 26.130435 | 112 | 0.68386 |
ffe2f4ebf2c00f61ee778dfe9fe0d5eeb7e86f4f | 6,931 | # frozen_string_literal: true
require_relative 'spec_helper'
module Basic101
describe BasicString do
it_behaves_like 'a basic object' do
let(:default_value) {''}
end
describe 'type_name' do
let(:type_name) {'string'}
subject {described_class.new(0)}
specify {expect(subject.class.type_name).to eq type_name}
specify {expect(subject.type_name).to eq type_name}
end
describe '#left' do
context 'when extracting substring' do
specify do
s = described_class.new('abcd')
expect(s.left(2)).to eq described_class.new('ab')
end
end
context 'when extracting null string' do
specify do
s = described_class.new('abcd')
expect(s.left(0)).to eq described_class.new('')
end
end
context 'when extracting entire string' do
specify do
s = described_class.new('abcd')
expect(s.left(10)).to eq described_class.new('abcd')
end
end
context 'when negative' do
specify do
s = described_class.new('abcd')
expect do
s.left(-1)
end.to raise_error InvalidArgumentError
end
end
end
describe '#length' do
specify do
s = described_class.new('abc')
expect(s.length).to eq BasicInteger.new(3)
end
end
describe '#mid' do
context 'when substring' do
specify do
s = described_class.new('abc')
expect(s.mid(2)).to eq described_class.new('bc')
end
end
context 'when short count' do
specify do
s = described_class.new('abc')
expect(s.mid(2, 1)).to eq described_class.new('b')
end
end
context 'when long count' do
specify do
s = described_class.new('abc')
expect(s.mid(2, 100)).to eq described_class.new('bc')
end
end
context 'when start past end of string' do
specify do
s = described_class.new('abc')
expect(s.mid(100)).to eq described_class.new('')
end
end
context 'when zero start' do
specify do
s = described_class.new('abc')
expect do
s.mid(0)
end.to raise_error InvalidArgumentError
end
end
context 'when zero count' do
specify do
s = described_class.new('abc')
expect do
s.mid(1, 0)
end.to raise_error InvalidArgumentError
end
end
end
describe '#+' do
it 'should concatenate a string' do
a = described_class.new('abc')
b = described_class.new('123')
c = a + b
expect(c).to eq described_class.new('abc123')
end
it 'should not concatenate an integer' do
a = described_class.new('abc')
b = BasicInteger.new(1)
expect {a + b}.to raise_error TypeError
end
end
describe '#right' do
context 'when entire string' do
specify do
a = described_class.new('abc')
b = a.right(10)
expect(b).to eq described_class.new('abc')
end
end
context 'when substring' do
specify do
a = described_class.new('abc')
b = a.right(2)
expect(b).to eq described_class.new('bc')
end
end
context 'when zero count' do
specify do
a = described_class.new('abc')
b = a.right(0)
expect(b).to eq described_class.new('')
end
end
context 'when negative count' do
specify do
a = described_class.new('abc')
expect { a.right(-1) }.to raise_error InvalidArgumentError
end
end
end
describe '#asc' do
context 'when not empty' do
specify do
a = described_class.new('ABC')
expect(a.asc).to eq BasicInteger.new(65)
end
end
context 'when empty' do
specify do
a = described_class.new('')
expect {a.asc}.to raise_error InvalidArgumentError
end
end
end
describe '#val' do
it 'converts to a float' do
a = described_class.new('1.23')
expect(a.val).to eq BasicFloat.new(1.23)
end
it 'converts to an integer' do
a = described_class.new('-123')
expect(a.val).to eq BasicInteger.new(-123)
end
it 'ignores white space' do
a = described_class.new("\t\n 123\t\n ")
expect(a.val).to eq BasicInteger.new(123)
end
end
describe '#to_numeric' do
it 'should refuse' do
a = described_class.new('abc')
expect do
a.to_numeric
end.to raise_error TypeError,
'string cannot be converted to numeric'
end
end
describe '#to_integer' do
specify do
a = described_class.new(12)
expect {a.to_integer}.to raise_error TypeError
end
end
describe '#to_float' do
specify do
a = described_class.new(12.34)
expect {a.to_float}.to raise_error TypeError
end
end
describe '#to_string' do
specify do
a = described_class.new('abc')
expect(a.to_string).to eq a
end
end
describe '#str' do
it 'should return itself' do
a = described_class.new('abc')
expect(a.str).to eq a
end
end
describe '#lcase' do
it 'should leave lowercase alone' do
a = described_class.new('abc')
expect(a.lcase).to eq BasicString.new('abc')
end
it 'should lowercase a capitalized string' do
a = described_class.new('Abc')
expect(a.lcase).to eq BasicString.new('abc')
end
it 'should lowercase an allcaps string' do
a = described_class.new('ABC')
expect(a.lcase).to eq BasicString.new('abc')
end
end
describe '#ucase' do
it 'should uppercase a lowercase string' do
a = described_class.new('abc')
expect(a.ucase).to eq BasicString.new('ABC')
end
it 'should uppercase a capitalized string' do
a = described_class.new('Abc')
expect(a.ucase).to eq BasicString.new('ABC')
end
it 'should leave an uppercase string alone' do
a = described_class.new('ABC')
expect(a.ucase).to eq BasicString.new('ABC')
end
end
describe 'printing' do
let(:output) {double Output}
subject {described_class.new('123')}
describe '#print_string' do
specify do
expect(output).to receive(:print).with('123')
subject.print_string(output)
end
end
describe '#print_new_line' do
specify do
expect(output).to receive(:print).with("\n")
subject.print_new_line(output)
end
end
end
end
end
| 23.103333 | 68 | 0.562834 |
87513a3eb8c08b7277efa49bc7f76dd88463a22d | 679 | # typed: false
# frozen_string_literal: true
require "cmd/shared_examples/args_parse"
describe "brew outdated" do
it_behaves_like "parseable arguments"
it "outputs JSON", :integration_test do
setup_test_formula "testball"
(HOMEBREW_CELLAR/"testball/0.0.1/foo").mkpath
expected_json = {
formulae: [{
name: "testball",
installed_versions: ["0.0.1"],
current_version: "0.1",
pinned: false,
pinned_version: nil,
}],
casks: [],
}.to_json
expect { brew "outdated", "--json=v2" }
.to output("#{expected_json}\n").to_stdout
.and be_a_success
end
end
| 23.413793 | 49 | 0.594993 |
6241c3713c9c61f9af8ec45b541b5f1935f49b84 | 47 | default['traefik']['domain'] = 'home.cobus.io'
| 23.5 | 46 | 0.659574 |
e957e24b5e0c277a8c01481d9f1cd146895e5625 | 1,858 | require 'test_helper'
class TypeTest < Test::Unit::TestCase
def test_create_type
assert_exception(ActiveRecord::StatementInvalid, "Missing columns") {
@connection.create_type("user", {})
}
assert_exception(ActiveRecord::StatementInvalid, "Missing columns") {
@connection.create_type("user", [])
}
[
'CREATE TYPE "user"',
'"name" varchar(10)',
'"zip" numeric(5,0)'
].each {|re|
assert_match re.to_regex, @connection.send("get_type_query", "user", [:name, "varchar(10)"], {:zip => "numeric(5,0)"}, [:is_customer => :boolean])
}
# @connection.drop_type :qualitysmith_user
assert_nothing_raised {
@connection.create_type(:qualitysmith_user, [:name, "varchar(10)"], {:zip => "numeric(5,0)"}, [:is_customer => :boolean])
}
count = @connection.select_value("select count(*) from pg_type where typname = 'qualitysmith_user'", "count")
assert_equal("1", count)
assert_nothing_raised {
@connection.drop_type(:qualitysmith_user)
}
count = @connection.select_value("select count(*) from pg_type where typname = 'qualitysmith_user'", "count")
assert_equal("0", count)
end
def test_schema_dumper_type
# a type test
@connection.create_type("qualitysmith_user", [:name, "varchar(10)"], {:zip => "numeric(5,0)"}, [:is_customer => :boolean])
assert_no_exception(NoMethodError) do
dumper = ActiveRecord::SchemaDumper.new(@connection)
stream = StringIO.new
dumper.send(:types, stream)
stream.rewind
received = stream.read
['[:name, "character varying(10)"]', '[:zip, "numeric(5,0)"]', '[:is_customer, :boolean]'].each do |fragment|
assert received.chomp[%r|create_type "qualitysmith_user",(.*)|, 1].include?(fragment)
end
end
@connection.drop_type(:qualitysmith_user)
end
end
| 37.16 | 152 | 0.652853 |
33a0e0f5f885d51751e6e770e89fe7af757db56b | 4,348 | # frozen_string_literal: true
# rubocop:disable Scalability/IdempotentWorker
module ObjectStorage
class MigrateUploadsWorker
include ApplicationWorker
include ObjectStorageQueue
feature_category_not_owned!
loggable_arguments 0, 1, 2, 3
SanityCheckError = Class.new(StandardError)
class MigrationResult
attr_reader :upload
attr_accessor :error
def initialize(upload, error = nil)
@upload, @error = upload, error
end
def success?
error.nil?
end
def to_s
success? ? _("Migration successful.") : _("Error while migrating %{upload_id}: %{error_message}") % { upload_id: upload.id, error_message: error.message }
end
end
module Report
class MigrationFailures < StandardError
attr_reader :errors
def initialize(errors)
@errors = errors
end
def message
errors.map(&:message).join("\n")
end
end
# rubocop:disable Gitlab/RailsLogger
def report!(results)
success, failures = results.partition(&:success?)
Rails.logger.info header(success, failures)
Rails.logger.warn failures(failures)
raise MigrationFailures.new(failures.map(&:error)) if failures.any?
end
# rubocop:enable Gitlab/RailsLogger
def header(success, failures)
_("Migrated %{success_count}/%{total_count} files.") % { success_count: success.count, total_count: success.count + failures.count }
end
def failures(failures)
failures.map { |f| "\t#{f}" }.join('\n')
end
end
include Report
# rubocop: disable CodeReuse/ActiveRecord
def self.enqueue!(uploads, model_class, mounted_as, to_store)
sanity_check!(uploads, model_class, mounted_as)
perform_async(uploads.ids, model_class.to_s, mounted_as, to_store)
end
# rubocop: enable CodeReuse/ActiveRecord
# We need to be sure all the uploads are for the same uploader and model type
# and that the mount point exists if provided.
#
def self.sanity_check!(uploads, model_class, mounted_as)
upload = uploads.first
uploader_class = upload.uploader.constantize
uploader_types = uploads.map(&:uploader).uniq
model_types = uploads.map(&:model_type).uniq
model_has_mount = mounted_as.nil? || model_class.uploaders[mounted_as] == uploader_class
raise(SanityCheckError, _("Multiple uploaders found: %{uploader_types}") % { uploader_types: uploader_types }) unless uploader_types.count == 1
raise(SanityCheckError, _("Multiple model types found: %{model_types}") % { model_types: model_types }) unless model_types.count == 1
raise(SanityCheckError, _("Mount point %{mounted_as} not found in %{model_class}.") % { mounted_as: mounted_as, model_class: model_class }) unless model_has_mount
end
# rubocop: disable CodeReuse/ActiveRecord
def perform(*args)
args_check!(args)
(ids, model_type, mounted_as, to_store) = args
@model_class = model_type.constantize
@mounted_as = mounted_as&.to_sym
@to_store = to_store
uploads = Upload.preload(:model).where(id: ids)
sanity_check!(uploads)
results = migrate(uploads)
report!(results)
rescue SanityCheckError => e
# do not retry: the job is insane
Rails.logger.warn "#{self.class}: Sanity check error (#{e.message})" # rubocop:disable Gitlab/RailsLogger
end
# rubocop: enable CodeReuse/ActiveRecord
def sanity_check!(uploads)
self.class.sanity_check!(uploads, @model_class, @mounted_as)
end
def args_check!(args)
return if args.count == 4
case args.count
when 3 then raise SanityCheckError, _("Job is missing the `model_type` argument.")
else
raise SanityCheckError, _("Job has wrong arguments format.")
end
end
def build_uploaders(uploads)
uploads.map { |upload| upload.retrieve_uploader(@mounted_as) }
end
def migrate(uploads)
build_uploaders(uploads).map(&method(:process_uploader))
end
def process_uploader(uploader)
MigrationResult.new(uploader.upload).tap do |result|
uploader.migrate!(@to_store)
rescue => e
result.error = e
end
end
end
end
# rubocop:enable Scalability/IdempotentWorker
| 30.405594 | 168 | 0.674103 |
e206e9f04ad34373eb8caffcf0a5f34c38a2d181 | 643 | require 'tzinfo'
set :output, "/home/deploy/apps/simple-server/shared/log/cron.log"
env :PATH, ENV['PATH']
DEFAULT_CRON_TIME_ZONE='Asia/Kolkata'
def local(time)
TZInfo::Timezone.get(DEFAULT_CRON_TIME_ZONE).local_to_utc(Time.parse(time))
end
every :day, at: local('11:00 pm').utc, roles: [:cron] do
rake 'appointment_notification:three_days_after_missed_visit'
end
every :day, at: local('11:00 pm'), roles: [:whitelist_phone_numbers] do
rake 'exotel_tasks:whitelist_patient_phone_numbers'
end
every :week, at: local('11:00 pm'), roles: [:whitelist_phone_numbers] do
rake 'exotel_tasks:update_all_patients_phone_number_details'
end | 29.227273 | 77 | 0.772939 |
28ede88721818d183b70e2e7f140fa8a6cf01c26 | 314 | ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Add more helper methods to be used by all tests here...
end
| 28.545455 | 82 | 0.729299 |
6ab50eff2fd1f7f2a29de8eec77835ad2c3f58d8 | 4,177 | RSpec.describe Metric::Common do
let(:host) { FactoryBot.create(:host) }
let(:metric) do
FactoryBot.create(:metric_rollup_host_hr,
:resource => host,
:timestamp => Time.now.next_week(:sunday).utc
)
end
describe "#v_month" do
it "returns the timestamp in YYYY/MM format" do
m = Metric.new(:timestamp => Time.zone.parse("2015-01-01"))
expect(m.v_month).to eq("2015/01")
end
end
context "#apply_time_profile" do
it "with all days and hours selected it should return true" do
profile = FactoryBot.create(:time_profile,
:description => "foo",
:profile => {:tz => "New Delhi",
:days => TimeProfile::ALL_DAYS,
:hours => TimeProfile::ALL_HOURS}
)
res = metric.apply_time_profile(profile)
expect(res).to be_truthy
end
it "with specific days and hours selected it should return false" do
profile = FactoryBot.create(:time_profile,
:description => "foo",
:profile => {:tz => "New Delhi",
:days => [1],
:hours => [1]}
)
res = metric.apply_time_profile(profile)
expect(res).to be_falsey
end
it "returns true if time profile were used for aggregation (and rollup record refer to it)" do
profile = FactoryBot.create(:time_profile,
:description => "foo",
:profile => {:tz => "New Delhi",
:days => [1],
:hours => [1]})
profile_aggr = FactoryBot.create(:time_profile,
:description => "used_for_daily_aggregation",
:profile => {:tz => "UTC",
:days => (2..4),
:hours => TimeProfile::ALL_HOURS})
metric.time_profile_id = profile_aggr.id
res = metric.apply_time_profile(profile)
expect(res).to be_truthy
end
end
it ".v_derived_cpu_total_cores_used" do
m = Metric.new
# cpu_rate, num_vcpus, cpu_total_cores_used
metrics_exercises = [
[0, 8, 0], [10, 8, 0.8], [50, 8, 4], [75, 8, 6], [100, 8, 8],
[nil, 8, nil], [nil, 4, nil],
[0, 0, nil], [10, 0, nil], [50, 0, nil],
[0, nil, nil], [10, nil, nil], [50, nil, nil],
[nil, nil, nil],
]
metrics_exercises.each do |cpu_rate, num_vcpus, expected|
m.cpu_usage_rate_average = cpu_rate
m.derived_vm_numvcpus = num_vcpus
expect(m.v_derived_cpu_total_cores_used).to eq(expected)
end
end
describe ".for_time_range" do
it "returns nothing for nil dates" do
FactoryBot.create(:metric, :timestamp => 5.days.ago)
expect(Metric.for_time_range(nil, nil)).to be_empty
end
it "returns a single date' worth" do
timestamp = 5.days.ago
good = FactoryBot.create(:metric, :timestamp => timestamp)
FactoryBot.create(:metric, :timestamp => 4.days.ago)
FactoryBot.create(:metric, :timestamp => 6.days.ago)
expect(Metric.for_time_range(timestamp, timestamp)).to eq([good])
end
it "returns open ended date" do
FactoryBot.create(:metric, :timestamp => 30.days.ago)
good = FactoryBot.create(:metric, :timestamp => 5.days.ago)
expect(Metric.for_time_range(10.days.ago, nil)).to eq([good])
end
it "returns range" do
FactoryBot.create(:metric, :timestamp => 30.days.ago)
good = FactoryBot.create(:metric, :timestamp => 5.days.ago)
FactoryBot.create(:metric, :timestamp => 1.day.ago)
expect(Metric.for_time_range(10.days.ago, 3.days.ago)).to eq([good])
end
end
end
| 39.780952 | 98 | 0.510654 |
ff3751bbbd2d4a28ff244a4e8f17b0af107d3222 | 183 | class ProductDecorator < Draper::Decorator
delegate_all
def as_json *args
{
id: id,
name: name,
description: description,
price: price
}
end
end | 15.25 | 42 | 0.612022 |
ed81bbe1fa3264009fa440de0984589a233ba937 | 282 | require "application_system_test_case"
class InHttpTest < ApplicationSystemTestCase
include ConfigurableDaemonSettings
setup do
login_with(FactoryBot.build(:user))
@type = "in_http"
@form_name = "port"
@form_value = "12345"
@daemon = stub_daemon
end
end
| 20.142857 | 44 | 0.730496 |
3850847ba7a632eaeaa5c0e35cdea321a500e89f | 513 | require File.dirname(__FILE__) + '/spec_helper'
describe "model.specdoc" do
before(:all) do
SpecDoc2.auto_migrate!
end
subject { SpecDoc2.specdoc }
it "should provide the specdoc of model" do
# print subject
should include("- should be present")
should include("- should be unique")
should include("- should be a positive number")
end
it "should contain all property names" do
should include("id:")
should include("number:")
should include("number2:")
end
end
| 20.52 | 51 | 0.678363 |
1c0693986dd8e5262ff9698d456d042b91becf61 | 872 | require 'rails/generators'
require 'rails/generators/migration'
require "rails/generators/active_record/migration"
module Proteus
module Generators
class InstallGenerator < Rails::Generators::Base
include ActiveRecord::Generators::Migration
class_option :encryption_engine, type: :string, default: "none"
source_root File.expand_path("templates", __dir__)
desc "Add the migrations for Porteus"
def copy_migrations
# options["encryption_engine"]
warn "Creating Migrations for Proteus Whitelabeling"
migration_template(
"create_proteus.rb.erb",
"db/migrate/create_proteus.rb"
)
end
def encryption_engine
options["encryption_engine"]
end
def migration_version
"[#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}]"
end
end
end
end
| 26.424242 | 69 | 0.677752 |
bf19d5c6b53205e2278b234839b94f8d2c86d238 | 1,742 | require 'test_helper'
module CLI
module Kit
class UtilTest < Minitest::Test
def test_to_filesize
assert_equal('0B', CLI::Kit::Util.to_filesize(0))
assert_equal('0 B', CLI::Kit::Util.to_filesize(0, space: true))
assert_equal('10B', CLI::Kit::Util.to_filesize(10 * 1024**0))
assert_equal('10kB', CLI::Kit::Util.to_filesize(10 * 1024**1))
assert_equal('10MB', CLI::Kit::Util.to_filesize(10 * 1024**2))
assert_equal('10GB', CLI::Kit::Util.to_filesize(10 * 1024**3))
assert_equal('10TB', CLI::Kit::Util.to_filesize(10 * 1024**4))
# Float behavior
assert_equal('12.9kB', CLI::Kit::Util.to_filesize(13_212))
assert_equal('126.0MB', CLI::Kit::Util.to_filesize(132_121_322))
assert_equal('1.23GB', CLI::Kit::Util.to_filesize(1_321_213_212))
assert_equal('-10.5kB', CLI::Kit::Util.to_filesize((-10.5 * 1024**1).round))
end
# Extra tests for edge cases of to_si_scale
def test_to_si_scale
assert_equal('-1ms', CLI::Kit::Util.to_si_scale(-0.001, 's'))
assert_equal('1ms', CLI::Kit::Util.to_si_scale(0.001, 's'))
assert_equal('123ms', CLI::Kit::Util.to_si_scale(0.123, 's'))
assert_equal('123.4µs', CLI::Kit::Util.to_si_scale(0.0001234, 's'))
assert_equal('1.0s', CLI::Kit::Util.to_si_scale(1.001, 's'))
assert_equal('1.001s', CLI::Kit::Util.to_si_scale(1.0012, 's', precision: 3))
assert_equal('10k', CLI::Kit::Util.to_si_scale(10_000))
assert_equal('10 km', CLI::Kit::Util.to_si_scale(10_000, 'm', space: true))
assert_raises(ArgumentError) do
CLI::Kit::Util.to_si_scale(0, '', factor: 10)
end
end
end
end
end
| 40.511628 | 85 | 0.621125 |
615d82de372bfb3585064d39a2c6ff3c2e2bd540 | 1,655 | if RUBY_PLATFORM == "java"
$LOAD_PATH.insert(0, "./lib")
end
unless ENV['MSPEC_RUNNER']
begin
require "pp"
require 'mspec/version'
require 'mspec/helpers'
require 'mspec/guards'
require 'mspec/runner/shared'
require 'mspec/matchers/be_ancestor_of'
require 'mspec/matchers/output'
require 'mspec/matchers/output_to_fd'
require 'mspec/matchers/complain'
require 'mspec/matchers/equal_element'
require 'mspec/matchers/equal_utf16'
require 'mspec/matchers/match_yaml'
# Code to setup HOME directory correctly on Windows
# This duplicates Ruby 1.9 semantics for defining HOME
platform_is :windows do
if ENV['HOME']
ENV['HOME'] = ENV['HOME'].tr '\\', '/'
elsif ENV['HOMEDIR'] && ENV['HOMEDRIVE']
ENV['HOME'] = File.join(ENV['HOMEDRIVE'], ENV['HOMEDIR'])
elsif ENV['HOMEDIR']
ENV['HOME'] = ENV['HOMEDIR']
elsif ENV['HOMEDRIVE']
ENV['HOME'] = ENV['HOMEDRIVE']
elsif ENV['USERPROFILE']
ENV['HOME'] = ENV['USERPROFILE']
else
puts "No suitable HOME environment found. This means that all of"
puts "HOME, HOMEDIR, HOMEDRIVE, and USERPROFILE are not set"
exit 1
end
end
TOLERANCE = 0.00003 unless Object.const_defined?(:TOLERANCE)
rescue LoadError
puts "Please install the MSpec gem to run the specs."
exit 1
end
end
minimum_version = "1.5.10"
unless MSpec::VERSION >= minimum_version
puts "Please install MSpec version >= #{minimum_version} to run the specs"
exit 1
end
$VERBOSE = nil unless ENV['OUTPUT_WARNINGS']
| 30.648148 | 77 | 0.636858 |
f85ced117043b80e960721016a6fad0866906815 | 4,128 | #! /usr/bin/env ruby
#
# check-mesos-cpu-balance
#
# DESCRIPTION:
# This plugin checks that there is less CPU imbalance than specified on a certain mesos cluster
#
# OUTPUT:
# plain text
#
# PLATFORMS:
# Linux
#
# DEPENDENCIES:
# gem: sensu-plugin
# gem: rest-client
# gem: json
#
# USAGE:
# #YELLOW
#
# NOTES:
#
# LICENSE:
# Released under the same terms as Sensu (the MIT license); see LICENSE
# for details.
#
require 'sensu-plugin/check/cli'
require 'rest-client'
require 'json'
class MesosCpuBalanceCheck < Sensu::Plugin::Check::CLI
check_name 'MesosCpuBalanceCheck'
@metrics_name = 'slaves'.freeze
CHECK_TYPE = 'cpus'.freeze
class << self
attr_reader :metrics_name
end
option :server,
description: 'Mesos server',
short: '-s SERVER',
long: '--server SERVER',
default: 'localhost'
option :port,
description: 'port (default 5050)',
short: '-p PORT',
long: '--port PORT',
default: 5050,
required: false
option :uri,
description: 'Endpoint URI',
short: '-u URI',
long: '--uri URI',
default: '/master/slaves'
option :timeout,
description: 'timeout in seconds',
short: '-t TIMEOUT',
long: '--timeout TIMEOUT',
proc: proc(&:to_i),
default: 5
option :crit,
description: 'Critical value to check against',
short: '-c VALUE',
long: '--critical VALUE',
proc: proc(&:to_i),
default: 0,
required: false
option :warn,
description: 'Warning value to check against',
short: '-w VALUE',
long: '--warning VALUE',
proc: proc(&:to_i),
default: 0,
required: false
def run
if config[:crit] < 0 || config[:warn] < 0
unknown "Thresholds cannot be negative, crit: #{config[:crit]}, warn: #{config[:warn]}"
end
server = config[:server]
port = config[:port]
uri = config[:uri]
timeout = config[:timeout]
crit = config[:crit]
warn = config[:warn]
begin
server = get_leader_url server, port
r = RestClient::Resource.new("#{server}#{uri}", timeout).get
compare = get_check_diff(get_slaves(r))
if compare['diff'] >= crit
critical "There is a CPU diff of #{compare['diff']} bigger than #{crit} " + compare['msg']
end
if compare['diff'] >= warn
warning "There is a CPU diff of #{compare['diff']} bigger than #{warn} " + compare['msg']
end
rescue Errno::ECONNREFUSED, RestClient::ResourceNotFound, SocketError
unknown "Mesos #{server} is not responding"
rescue RestClient::RequestTimeout
unknown "Mesos #{server} connection timed out"
end
ok
end
# Redirects server call to discover the Leader
# @param server [String] Server address
# @param port [Number] api port
# @return [Url] Url representing the Leader
def get_leader_url(server, port)
RestClient::Resource.new("http://#{server}:#{port}/redirect").get.request.url
end
# Parses JSON data as returned from Mesos's metrics API
# @param data [String] Server response
# @return [Integer] Number of failed tasks in Mesos
def get_slaves(data)
begin
slaves = JSON.parse(data)[MesosCpuBalanceCheck.metrics_name]
rescue JSON::ParserError
raise "Could not parse JSON response: #{data}"
end
if slaves.nil?
raise "No metrics for [#{MesosCpuBalanceCheck.metrics_name}] in server response: #{data}"
end
slaves
end
def get_check_diff(slavelist)
begin
usages = {}
check_diff = {}
slavelist.each do |slaveinfo|
usages.store(slaveinfo['hostname'], slaveinfo['used_resources'][CHECK_TYPE] * 100 / slaveinfo['resources'][CHECK_TYPE])
end
sorted = usages.sort_by { |_hostname, total| total }
max = usages.length - 1
check_diff['diff'] = sorted[max][1] - sorted[0][1]
check_diff['msg'] = "Hostname #{sorted[0][0]} uses #{sorted[0][1]}% and Hostname #{sorted[max][0]} uses #{sorted[max][1]}%"
end
check_diff
end
end
| 26.632258 | 129 | 0.615068 |
33f7d7d68d7db0f786877480edcc74c3d54ea907 | 115 | # frozen_string_literal: true
class DataMigration < ActiveRecord::Base
validates :version, uniqueness: true
end
| 19.166667 | 40 | 0.8 |
1c12a0626d16195c8ebc83a5d0d8b946e3f9bfeb | 1,071 | require 'data_objects'
if RUBY_PLATFORM =~ /java/
require 'do_jdbc'
require 'java'
module DataObjects
module Postgres
JDBC_DRIVER = 'org.postgresql.Driver'
end
end
begin
java.lang.Thread.currentThread.getContextClassLoader().loadClass(DataObjects::Postgres::JDBC_DRIVER, true)
rescue java.lang.ClassNotFoundException
require 'jdbc/postgres' # the JDBC driver, packaged as a gem
Jdbc::Postgres.load_driver if Jdbc::Postgres.respond_to?(:load_driver)
end
# Another way of loading the JDBC Class. This seems to be more reliable
# than Class.forName() within the data_objects.Connection Java class,
# which is currently not working as expected.
java_import DataObjects::Postgres::JDBC_DRIVER
end
begin
require 'do_postgres/do_postgres'
rescue LoadError
if RUBY_PLATFORM =~ /mingw|mswin/ then
RUBY_VERSION =~ /(\d+.\d+)/
require "do_postgres/#{$1}/do_postgres"
else
raise
end
end
require 'do_postgres/version'
require 'do_postgres/transaction' if RUBY_PLATFORM !~ /java/
require 'do_postgres/encoding'
| 26.775 | 110 | 0.744164 |
bbb7d36afe0494fa05ce64c8f4e638c5fed65d74 | 1,080 | lib = File.expand_path('../lib/', __FILE__)
$:.unshift lib unless $:.include?(lib)
require 'slimkeyfy/version'
Gem::Specification.new do |s|
s.name = "slimkeyfy"
s.version = SlimKeyfy::VERSION
s.platform = Gem::Platform::RUBY
s.homepage = %q{https://phrase.com/}
s.authors = ["Dynport GmbH"]
s.summary = %q{Extract plain strings from slim templates to replace them with calls to I18n's t() method.}
s.description = %q{Replace plain text strings in your slim templates and Rails controllers with calls to I18n t() method. Keys and YAML output files will be automatically generated and filled in.}
s.email = ["[email protected]"]
git_files = `git ls-files | grep -v spec/`.split("\n") rescue ''
s.files = git_files
s.test_files = s.files.grep(%r{^(spec)/})
s.executables = ["slimkeyfy"]
s.require_paths = ["lib"]
s.add_dependency "tty-prompt"
s.add_dependency "diff-lcs"
s.add_dependency "diffy"
s.add_development_dependency('rspec')
s.add_development_dependency('pry-byebug')
end
| 38.571429 | 198 | 0.664815 |
ff457c7a0b460626086ba2562af2775b754e4787 | 2,124 | require 'spec_helper'
describe 'smokeping' do
let :node do
'agent.example.com'
end
on_supported_os.each do |os, facts|
context "on #{os} " do
let :facts do
facts
end
let :params do
{
cgiurl: 'http://some.url/smokeping.cgi',
master_url: 'http://somewhere/cgi-bin/smokeping.cgi',
}
end
context 'with all defaults' do
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_class('smokeping') }
it { is_expected.to contain_class('smokeping::install') }
it { is_expected.to contain_class('smokeping::service') }
it { is_expected.to contain_class('smokeping::config') }
case facts[:osfamily]
when 'RedHat'
it {
is_expected.to contain_file('/var/lib/smokeping/rrd').with(
ensure: 'directory',
owner: 'root',
group: 'root',
recurse: true
)
}
when 'Debian'
it {
is_expected.to contain_file('/var/lib/smokeping').with(
ensure: 'directory',
owner: 'smokeping',
group: 'smokeping',
recurse: true
)
}
end
end
context 'change datadir' do
let :params do
{
cgiurl: 'http://some.url/smokeping.cgi',
master_url: 'http://somewhere/cgi-bin/smokeping.cgi',
path_datadir: '/smokeping/data'
}
end
it {
is_expected.to contain_file('/smokeping/data').with(
ensure: 'directory',
recurse: true
)
}
context "don't manage datadir" do
let :params do
{
cgiurl: 'http://some.url/smokeping.cgi',
master_url: 'http://somewhere/cgi-bin/smokeping.cgi',
path_datadir: '/smokeping/data',
manage_datadir: false
}
end
it { is_expected.not_to contain_file('/smokeping/data') }
end
end
end
end
end
| 25.902439 | 71 | 0.510358 |
f8d7abef24a4a960b9ddc4fee79067cc0c0256b2 | 448 | # frozen_string_literal: true
module RgGen
module Core
class CLI
def initialize(builder = nil)
@builder = builder || Builder.create
@options = Options.new
end
attr_reader :builder
attr_reader :options
def run(args)
options.parse(args)
runner.run(builder, options)
end
private
def runner
options[:runner] || Generator.new
end
end
end
end
| 16.592593 | 44 | 0.591518 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.