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
|
---|---|---|---|---|---|
1ddcea9207bedbb835931adbe697c4f0c2167c54 | 47 | module Linearly
VERSION = '0.1.4'.freeze
end
| 11.75 | 26 | 0.702128 |
aca0e9a0e38a645f0e0223b4e87d28cd4910d99e | 1,767 | class Idba < Formula
# cite Peng_2012: "https://doi.org/10.1093/bioinformatics/bts174"
desc "Iterative De Bruijn Graph De Novo Assembler for sequence assembly"
homepage "https://i.cs.hku.hk/~alse/hkubrg/projects/idba/"
url "https://github.com/loneknightpy/idba/archive/1.1.3.tar.gz"
sha256 "6b1746a29884f4fa17b110d94d9ead677ab5557c084a93b16b6a043dbb148709"
bottle do
root_url "https://linuxbrew.bintray.com/bottles-bio"
cellar :any
sha256 "8dd38aa4b77473863dc5b0d2112cbb10906092197348621e9b04835f690a362b" => :sierra_or_later
sha256 "52b014cf241e90e3e053e752ae860f8c52b75b2498c06ac44b269179696a51a1" => :x86_64_linux
end
fails_with :clang # needs OpenMP
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "gcc" if OS.mac? # for OpenMP
resource "lacto-genus" do
url "https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/hku-idba/lacto-genus.tar.gz"
sha256 "b2496e8b9050c4448057214b9902a5d4db9e0069d480e65af029d53ce167a929"
end
def install
system "aclocal"
system "autoconf"
system "automake", "--add-missing"
system "./configure", "--prefix=#{prefix}"
system "make"
system "make", "check"
# system "make", "install" # currently does not install everything
bin.install Dir["bin/idba*"].select { |x| File.executable? x }
libexec.install Dir["bin/*"].select { |x| File.executable? x }
doc.install %w[AUTHORS ChangeLog NEWS README.md]
end
test do
system "#{bin}/idba_ud 2>&1 |grep IDBA-UD"
resource("lacto-genus").stage testpath
cd testpath do
system libexec/"sim_reads", "220668.fa", "220668.reads-10", "--paired", "--depth", "10"
system bin/"idba", "-r", "220668.reads-10"
end
end
end
| 36.061224 | 117 | 0.712507 |
2615262e7a27d0fcadce875e3e963b9f23a37882 | 10,051 | require 'spec_helper'
require 'base64'
kube_apiserver_secure_port = 6443
describe 'Waiting for all pods to be ready' do
describe command("for i in {1..1200}; do if [ $(kubectl get pods --all-namespaces -o json | jq -r '.items[] | select(.status.phase != \"Running\" or ([ .status.conditions[] | select(.type == \"Ready\" and .status != \"True\") ] | length ) == 1 ) | .metadata.namespace + \"/\" + .metadata.name' | wc -l) -eq 0 ]; \
then echo 'READY'; break; else echo 'WAITING'; sleep 1; fi; done") do
its(:stdout) { should match /READY/ }
its(:exit_status) { should eq 0 }
end
end
describe 'Checking if kubelet service is running' do
describe service('kubelet') do
it { should be_enabled }
it { should be_running }
end
end
describe 'Checking if kube-scheduler is running' do
describe process('kube-scheduler') do
it { should be_running }
end
end
describe 'Checking if kube-controller is running' do
describe process('kube-controller') do
it { should be_running }
end
end
describe 'Checking if kube-apiserver is running' do
describe process("kube-apiserver") do
it { should be_running }
end
end
describe 'Checking if there are any pods that have status other than Running' do
describe command('kubectl get pods --all-namespaces --field-selector=status.phase!=Running') do
its(:stdout) { should match /^$/ }
its(:stderr) { should match /No resources found/ }
end
end
describe 'Checking if the number of master nodes is the same as indicated in the inventory file' do
describe command('kubectl get nodes --selector=node-role.kubernetes.io/control-plane --no-headers | wc -l | tr -d "\n"') do
it "is expected to be equal" do
expect(subject.stdout.to_i).to eq countInventoryHosts("kubernetes_master")
end
end
end
describe 'Checking if the number of worker nodes is the same as indicated in the inventory file' do
describe command('kubectl get nodes --no-headers | grep -v master | wc -l | tr -d "\n"') do
it "is expected to be equal" do
expect(subject.stdout.to_i).to eq countInventoryHosts("kubernetes_node")
end
end
end
describe 'Checking if there are any nodes that have status other than Ready' do
describe command('kubectl get nodes') do
its(:stdout) { should match /\bReady\b/ }
its(:stdout) { should_not match /NotReady/ }
its(:stdout) { should_not match /Unknown/ }
its(:stdout) { should_not match /SchedulingDisabled/ }
end
end
describe 'Checking if the number of all nodes is the same as the number of Ready nodes' do
describe command('out1=$(kubectl get nodes --no-headers | wc -l); out2=$(kubectl get nodes --no-headers | grep -wc Ready); if [ "$out1" = "$out2" ]; then echo "EQUAL"; else echo "NOT EQUAL"; fi') do
its(:stdout) { should match /\bEQUAL\b/ }
its(:stdout) { should_not match /NOT EQUAL/ }
end
end
describe 'Checking the port on which to serve HTTPS with authentication and authorization' do
describe port(kube_apiserver_secure_port) do
let(:disable_sudo) { false }
it { should be_listening }
end
end
describe 'Checking secret creation using kubectl' do
test_user = 'user123'
test_pass = 'pass456'
test_user_b64 = Base64.encode64(test_user)
test_pass_b64 = Base64.encode64(test_pass)
timestamp = DateTime.now.to_time.to_i.to_s
test_secret = 'testsecret' + timestamp
describe 'Checking if the secret was successfully created' do
describe command("kubectl create secret generic #{test_secret} --from-literal=username=#{test_user} --from-literal=password=#{test_pass}") do
its(:stdout) { should match /secret\/#{test_secret} created/ }
end
end
describe 'Checking if the created secret is present on the list with all secrets' do
describe command('kubectl get secrets') do
its(:stdout) { should match /#{test_secret}/ }
end
end
describe 'Checking if the secret stores encoded data' do
describe command("kubectl get secret #{test_secret} -o yaml") do
its(:stdout) { should match /name: #{test_secret}/ }
its(:stdout) { should match /#{test_user_b64}/ }
its(:stdout) { should match /#{test_pass_b64}/ }
end
end
describe 'Deleting created secret' do
describe command("kubectl delete secret #{test_secret}") do
its(:stdout) { should match /secret "#{test_secret}" deleted/ }
its(:exit_status) { should eq 0 }
end
end
end
describe 'Checking kubernetes dashboard availability' do
describe 'Checking if kubernetes-dashboard pod is running' do
describe command('kubectl get pods --all-namespaces | grep kubernetes-dashboard') do
its(:stdout) { should match /kubernetes-dashboard/ }
its(:stdout) { should match /Running/ }
its(:exit_status) { should eq 0 }
end
end
describe 'Checking if kubernetes-dashboard is deployed' do
describe command('kubectl get deployments --all-namespaces --field-selector metadata.name=kubernetes-dashboard') do
its(:stdout) { should match /kubernetes-dashboard/ }
its(:stdout) { should match /1\/1/ }
its(:exit_status) { should eq 0 }
end
end
describe 'Checking if admin token bearer exists' do
describe command("kubectl describe secret $(kubectl get secrets --namespace=kube-system | grep admin-user \
| awk '{print $1}') --namespace=kube-system | awk '/^token/ {print $2}' | head -1") do
its(:stdout) { should_not match /^$/ }
its(:exit_status) { should eq 0 }
end
end
describe 'Setting up proxy and starting to serve on localhost' do
describe command('kubectl proxy >/dev/null 2>&1 &') do
its(:exit_status) { should eq 0 }
end
end
describe 'Checking if the dashboard is available' do
describe command('for i in {1..60}; do if [ $(curl -o /dev/null -s -w "%{http_code}" "http://localhost:8001/api/v1/namespaces/$(kubectl get deployments --all-namespaces --field-selector metadata.name=kubernetes-dashboard --no-headers | awk \'{print $1}\')/services/https:kubernetes-dashboard:/proxy/") -eq 200 ]; \
then echo -n "200"; break; else sleep 1; fi; done') do
it "is expected to be equal" do
expect(subject.stdout.to_i).to eq 200
end
end
end
describe 'Terminating kubectl proxy process' do
describe command('pkill -f "kubectl proxy"') do
its(:exit_status) { should eq 0 }
end
end
end
describe 'Checking if coredns is deployed' do
describe command('kubectl get deployments --all-namespaces --field-selector metadata.name=coredns') do
coredns_counter = 2 # always equal 2
its(:stdout) { should match /coredns/ }
its(:stdout) { should match /#{coredns_counter}\/#{coredns_counter}/ }
its(:exit_status) { should eq 0 }
end
end
describe 'Checking if kubernetes healthz endpoint is responding' do
describe command('curl --insecure -o /dev/null -s -w "%{http_code}" "https://127.0.0.1:10250/healthz"') do
it "is expected to be equal" do
expect(subject.stdout.to_i).to eq 401
end
end
end
if countInventoryHosts("kubernetes_node") == 0
describe 'Checking taints on Kubernetes master' do
describe command('kubectl get nodes -o jsonpath="{.items[*].spec.taints}"') do
its(:stdout) { should match /^$/ }
its(:exit_status) { should eq 0 }
end
describe command('kubectl describe nodes | grep -i taints') do
its(:stdout) { should match /<none>/ }
its(:exit_status) { should eq 0 }
end
end
end
describe 'Check the kubelet cgroup driver' do
describe file('/var/lib/kubelet/config.yaml') do
let(:disable_sudo) { false }
its(:content_as_yaml) { should include('cgroupDriver' => 'systemd') }
its(:content_as_yaml) { should_not include('cgroupDriver' => 'cgroupfs') }
end
end
describe 'Check the kubelet config in ConfigMap' do
describe command("kubectl describe cm $(kubectl get cm -n kube-system \
| awk '/kubelet-config/{print $1}') -n kube-system | grep -i cgroupDriver") do
its(:stdout) { should match(/cgroupDriver: systemd/) }
its(:stdout) { should_not match(/cgroupDriver: cgroupfs/) }
its(:exit_status) { should eq 0 }
end
end
describe 'Check the docker cgroup and logging driver' do
describe file('/etc/docker/daemon.json') do
let(:disable_sudo) { false }
its(:content_as_json) { should include('exec-opts' => include('native.cgroupdriver=systemd')) }
its(:content_as_json) { should include('log-driver' => 'json-file') }
its(:content_as_json) { should_not include('exec-opts' => include('native.cgroupdriver=cgroupfs')) }
end
describe command('docker info | grep -i driver') do
let(:disable_sudo) { false }
its(:stdout) { should match(/Cgroup Driver: systemd/) }
its(:stdout) { should match(/Logging Driver: json-file/) }
its(:exit_status) { should eq 0 }
end
end
describe 'Check certificate rotation for the kubelet' do
describe file('/var/lib/kubelet/config.yaml') do
let(:disable_sudo) { false }
its(:content_as_yaml) { should include('rotateCertificates' => true) }
end
describe command("kubectl describe cm $(kubectl get cm -n kube-system \
| awk '/kubelet-config/{print $1}') -n kube-system | grep -i rotateCertificates") do
its(:stdout) { should match(/rotateCertificates: true/) }
its(:exit_status) { should eq 0 }
end
end
describe 'Check Kubernetes namespace creation and deletion' do
ns_name = 'ns-spectest'
describe command("kubectl create ns #{ns_name}") do
its(:stdout) { should match %r{namespace/#{ns_name} created} }
its(:exit_status) { should eq 0 }
end
describe command("kubectl get ns #{ns_name} -o json") do
its(:stdout_as_json) { should include('metadata' => include('name' => ns_name.to_s)) }
its(:stdout_as_json) { should include('status' => include('phase' => 'Active')) }
its(:exit_status) { should eq 0 }
end
describe command("kubectl delete ns #{ns_name} --timeout=1m") do
its(:stdout) { should match %r{namespace "#{ns_name}" deleted} }
its(:stderr) { should_not match %r{error}i }
its(:exit_status) { should eq 0 }
end
end | 39.727273 | 318 | 0.685006 |
bf2ac15a1ae587bddd25e946eeb04cadefe4ec4a | 1,141 | class SS::DownloadJobFile
include ActiveModel::Model
cattr_accessor(:root, instance_accessor: false) { "#{Rails.root}/private/download" }
attr_reader :user, :filename, :path
attr_accessor :in_file, :in_path
def initialize(user, filename)
@user = user
@filename = filename
id_path = format("%02d", user.id.to_s.slice(0, 2)) + "/#{user.id}"
@path = "#{self.class.root}/#{id_path}/#{filename}"
end
def url(opts = {})
Rails.application.routes.url_helpers.
sns_download_job_files_path(user: user.id, filename: filename, name: opts[:name])
end
def read
::File.exists?(path) ? ::File.read(path) : nil
end
def content_type
::SS::MimeType.find(path, nil)
end
def save
if in_file
original_file_path = in_file.path
elsif in_path
original_file_path = in_path
else
return false
end
::FileUtils.mkdir_p(::File.dirname(path))
::File.write(path, ::File.read(original_file_path))
return true
end
class << self
def find(user, filename)
item = self.new(user, filename)
::File.exist?(item.path) ? item : nil
end
end
end
| 22.82 | 87 | 0.650307 |
333fb7d4c6a74aec445dfbb2f80664c97c5fe40a | 8,787 | require 'cases/helper'
require 'support/ddl_helper'
require 'support/schema_dumping_helper'
if ActiveRecord::Base.connection.supports_foreign_keys?
module ActiveRecord
class Migration
class ForeignKeyTest < ActiveRecord::TestCase
include DdlHelper
include SchemaDumpingHelper
class Rocket < ActiveRecord::Base
end
class Astronaut < ActiveRecord::Base
end
setup do
@connection = ActiveRecord::Base.connection
@connection.create_table "rockets", force: true do |t|
t.string :name
end
@connection.create_table "astronauts", force: true do |t|
t.string :name
t.references :rocket
end
end
teardown do
if defined?(@connection)
@connection.drop_table "astronauts", if_exists: true
@connection.drop_table "rockets", if_exists: true
end
end
def test_foreign_keys
foreign_keys = @connection.foreign_keys("fk_test_has_fk")
assert_equal 1, foreign_keys.size
fk = foreign_keys.first
assert_equal "fk_test_has_fk", fk.from_table
assert_equal "fk_test_has_pk", fk.to_table
assert_equal "fk_id", fk.column
assert_equal "pk_id", fk.primary_key
assert_equal "fk_name", fk.name
end
def test_add_foreign_key_inferes_column
@connection.add_foreign_key :astronauts, :rockets
foreign_keys = @connection.foreign_keys("astronauts")
assert_equal 1, foreign_keys.size
fk = foreign_keys.first
assert_equal "astronauts", fk.from_table
assert_equal "rockets", fk.to_table
assert_equal "rocket_id", fk.column
assert_equal "id", fk.primary_key
assert_equal("fk_rails_78146ddd2e", fk.name)
end
def test_add_foreign_key_with_column
@connection.add_foreign_key :astronauts, :rockets, column: "rocket_id"
foreign_keys = @connection.foreign_keys("astronauts")
assert_equal 1, foreign_keys.size
fk = foreign_keys.first
assert_equal "astronauts", fk.from_table
assert_equal "rockets", fk.to_table
assert_equal "rocket_id", fk.column
assert_equal "id", fk.primary_key
assert_equal("fk_rails_78146ddd2e", fk.name)
end
def test_add_foreign_key_with_non_standard_primary_key
with_example_table @connection, "space_shuttles", "pk integer PRIMARY KEY" do
@connection.add_foreign_key(:astronauts, :space_shuttles,
column: "rocket_id", primary_key: "pk", name: "custom_pk")
foreign_keys = @connection.foreign_keys("astronauts")
assert_equal 1, foreign_keys.size
fk = foreign_keys.first
assert_equal "astronauts", fk.from_table
assert_equal "space_shuttles", fk.to_table
assert_equal "pk", fk.primary_key
@connection.remove_foreign_key :astronauts, name: "custom_pk"
end
end
def test_add_on_delete_restrict_foreign_key
@connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :restrict
foreign_keys = @connection.foreign_keys("astronauts")
assert_equal 1, foreign_keys.size
fk = foreign_keys.first
if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
# ON DELETE RESTRICT is the default on MySQL
assert_equal nil, fk.on_delete
else
assert_equal :restrict, fk.on_delete
end
end
def test_add_on_delete_cascade_foreign_key
@connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :cascade
foreign_keys = @connection.foreign_keys("astronauts")
assert_equal 1, foreign_keys.size
fk = foreign_keys.first
assert_equal :cascade, fk.on_delete
end
def test_add_on_delete_nullify_foreign_key
@connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :nullify
foreign_keys = @connection.foreign_keys("astronauts")
assert_equal 1, foreign_keys.size
fk = foreign_keys.first
assert_equal :nullify, fk.on_delete
end
def test_on_update_and_on_delete_raises_with_invalid_values
assert_raises ArgumentError do
@connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :invalid
end
assert_raises ArgumentError do
@connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_update: :invalid
end
end
def test_add_foreign_key_with_on_update
@connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_update: :nullify
foreign_keys = @connection.foreign_keys("astronauts")
assert_equal 1, foreign_keys.size
fk = foreign_keys.first
assert_equal :nullify, fk.on_update
end
def test_remove_foreign_key_inferes_column
@connection.add_foreign_key :astronauts, :rockets
assert_equal 1, @connection.foreign_keys("astronauts").size
@connection.remove_foreign_key :astronauts, :rockets
assert_equal [], @connection.foreign_keys("astronauts")
end
def test_remove_foreign_key_by_column
@connection.add_foreign_key :astronauts, :rockets, column: "rocket_id"
assert_equal 1, @connection.foreign_keys("astronauts").size
@connection.remove_foreign_key :astronauts, column: "rocket_id"
assert_equal [], @connection.foreign_keys("astronauts")
end
def test_remove_foreign_key_by_symbol_column
@connection.add_foreign_key :astronauts, :rockets, column: :rocket_id
assert_equal 1, @connection.foreign_keys("astronauts").size
@connection.remove_foreign_key :astronauts, column: :rocket_id
assert_equal [], @connection.foreign_keys("astronauts")
end
def test_remove_foreign_key_by_name
@connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", name: "fancy_named_fk"
assert_equal 1, @connection.foreign_keys("astronauts").size
@connection.remove_foreign_key :astronauts, name: "fancy_named_fk"
assert_equal [], @connection.foreign_keys("astronauts")
end
def test_remove_foreign_non_existing_foreign_key_raises
assert_raises ArgumentError do
@connection.remove_foreign_key :astronauts, :rockets
end
end
def test_schema_dumping
@connection.add_foreign_key :astronauts, :rockets
output = dump_table_schema "astronauts"
assert_match %r{\s+add_foreign_key "astronauts", "rockets"$}, output
end
def test_schema_dumping_with_options
output = dump_table_schema "fk_test_has_fk"
assert_match %r{\s+add_foreign_key "fk_test_has_fk", "fk_test_has_pk", column: "fk_id", primary_key: "pk_id", name: "fk_name"$}, output
end
def test_schema_dumping_on_delete_and_on_update_options
@connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :nullify, on_update: :cascade
output = dump_table_schema "astronauts"
assert_match %r{\s+add_foreign_key "astronauts",.+on_update: :cascade,.+on_delete: :nullify$}, output
end
class CreateCitiesAndHousesMigration < ActiveRecord::Migration
def change
create_table("cities") { |t| }
create_table("houses") do |t|
t.column :city_id, :integer
end
add_foreign_key :houses, :cities, column: "city_id"
end
end
def test_add_foreign_key_is_reversible
migration = CreateCitiesAndHousesMigration.new
silence_stream($stdout) { migration.migrate(:up) }
assert_equal 1, @connection.foreign_keys("houses").size
ensure
silence_stream($stdout) { migration.migrate(:down) }
end
private
def silence_stream(stream)
old_stream = stream.dup
stream.reopen(IO::NULL)
stream.sync = true
yield
ensure
stream.reopen(old_stream)
old_stream.close
end
end
end
end
else
module ActiveRecord
class Migration
class NoForeignKeySupportTest < ActiveRecord::TestCase
setup do
@connection = ActiveRecord::Base.connection
end
def test_add_foreign_key_should_be_noop
@connection.add_foreign_key :clubs, :categories
end
def test_remove_foreign_key_should_be_noop
@connection.remove_foreign_key :clubs, :categories
end
def test_foreign_keys_should_raise_not_implemented
assert_raises NotImplementedError do
@connection.foreign_keys("clubs")
end
end
end
end
end
end
| 33.410646 | 143 | 0.680096 |
e95a8de7f959f4f672f80b5d0b723a775036ae3a | 1,119 | class Mdr < Formula
desc "Make diffs readable"
homepage "https://github.com/halffullheart/mdr"
url "https://github.com/halffullheart/mdr/archive/v1.0.1.tar.gz"
sha256 "103d52c47133a43cc7a6cb8a21bfabe2d6e35e222d5b675bc0c868699a127c67"
license "GPL-3.0"
bottle do
cellar :any_skip_relocation
sha256 "9da0233ef931bc31dff9356e3298f5c838fbbe3422d64cbfa1e3751bd09545d0" => :catalina
sha256 "6dec04545f16f59af2b9b2397d4ebf65c204c827fef52cb20ef81c12d2273cda" => :mojave
sha256 "58d0fa82a0e6291d934bbc3f12f586fbb35282f9d15db017126e042f209dd664" => :high_sierra
sha256 "ef68c4389ee92beeb6c04e1859f398d108ffcce03fe692dd5776f7e12d776672" => :sierra
sha256 "0b522120151f1116ae7e681ff2fb129ecd26486202ca753d6b1de902f6f29334" => :el_capitan
sha256 "7048e71ef8f9a1d5c1712dce6cb33df08029038d771789021a1b8bc1e5f4ad10" => :yosemite
sha256 "b80b64d56e7e77e9b53dd8c308dd50450552b782a72204cb710adf2de28c4f9e" => :mavericks
end
def install
system "rake"
libexec.install Dir["*"]
bin.install_symlink libexec/"build/dev/mdr"
end
test do
system "#{bin}/mdr", "-h"
end
end
| 38.586207 | 93 | 0.795353 |
6217a7a5b982a58498c54ea59504c7735d244da8 | 980 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'shellwords/version'
Gem::Specification.new do |spec|
spec.name = "shellwords"
spec.version = Shellwords::VERSION
spec.authors = ["Lars Kanis"]
spec.email = ["[email protected]"]
spec.description = %q{Replacement for shellwords in Ruby's stdlibs. It supports escaping rules of Windows cmd.exe and MS runtime libraries.}
spec.summary = %q{Replacement for shellwords in Ruby's stdlibs.}
spec.homepage = "https://github.com/larskanis/shellwords"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
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_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
end
| 40.833333 | 144 | 0.672449 |
39a74d34e23fa094fec352d5d69cd263a2d0c678 | 1,811 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
class TestInt64Array < Test::Unit::TestCase
include Helper::Buildable
def test_new
assert_equal(build_int64_array([-1, 2, nil]),
Arrow::Int64Array.new(3,
Arrow::Buffer.new([-1, 2].pack("q*")),
Arrow::Buffer.new([0b011].pack("C*")),
-1))
end
def test_buffer
builder = Arrow::Int64ArrayBuilder.new
builder.append_value(-1)
builder.append_value(2)
builder.append_value(-4)
array = builder.finish
assert_equal([-1, 2, -4].pack("q*"), array.buffer.data.to_s)
end
def test_value
builder = Arrow::Int64ArrayBuilder.new
builder.append_value(-1)
array = builder.finish
assert_equal(-1, array.get_value(0))
end
def test_values
builder = Arrow::Int64ArrayBuilder.new
builder.append_value(-1)
builder.append_value(2)
builder.append_value(-4)
array = builder.finish
assert_equal([-1, 2, -4], array.values)
end
end
| 33.537037 | 77 | 0.669796 |
bf2e4aa71f7eccd0012cfd177c326000ca6bf311 | 1,483 | # (C) Copyright 2017 Hewlett Packard Enterprise Development LP
#
# 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_relative '../../api1000/synergy/enclosure_group'
module OneviewSDK
module API1200
module Synergy
# Enclosure group resource implementation on API1200 Synergy
class EnclosureGroup < OneviewSDK::API1000::Synergy::EnclosureGroup
# Create a resource object, associate it with a client, and set its properties.
# @param [OneviewSDK::Client] client The client object for the OneView appliance
# @param [Hash] params The options for this resource (key-value pairs)
# @param [Integer] api_ver The api version to use when interracting with this resource.
def initialize(client, params = {}, api_ver = nil)
@data ||= {}
# Default values:
super
end
def update(attributes = {})
@data['type'] ||= 'EnclosureGroupV8'
super
end
end
end
end
end
| 40.081081 | 95 | 0.697235 |
015415b0258dd00e0d60e1c565b2122cdc2500e9 | 3,400 | #
# Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
#
# 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.
#
tag = `git describe --tags --match "[0-9]*.[0-9]*.[0-9]*"` # e.g: "0.2.7-5-gc9c4730d"
(last_release, _, new_commit) = tag.split("-")
# dev version will only be used when user's Podfile references our git repository directly
# without using tags for releases
dev_version = "#{last_release}-DEV-#{new_commit}"
Pod::Spec.new do |spec|
# ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
spec.name = "BeagleUI"
spec.version = new_commit ? dev_version : last_release
spec.summary = "This is the Beagle framework for iOS"
spec.description = <<-DESC
We encourage you to use Beagle from Carthage, since it is the preferred
way of using it. But if you are willing to just test Beagle, you can use this
pod instead.
DESC
spec.homepage = "https://zup-products.gitbook.io/beagle/"
# ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
spec.license = "Apache License 2.0"
# ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
spec.author = "Zup IT"
# ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
spec.platform = :ios, "10.0"
spec.swift_version = "4.1"
# ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
source = { :git => "[email protected]:ZupIT/beagle.git" }
if new_commit
source[:commit] = new_commit
else
source[:tag] = last_release
end
spec.source = source
# ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
spec.default_subspec = "BeagleUI"
# ――― Beagle UI ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
spec.subspec 'BeagleUI' do |beagleUI|
source = 'iOS/Sources/BeagleUI/Sources'
sourcery = 'iOS/Sources/BeagleUI/SourceryFiles/'
beagleUI.source_files = [
source + '/**/*.swift',
sourcery + "Generated/*.generated.swift",
sourcery + "*.swift"
]
beagleUI.resources = [
"iOS/**/*.xcdatamodeld",
sourcery + "Templates/*"
]
beagleUI.exclude_files = [
source + "/**/Test/**/*.swift",
source + "/**/Tests/**/*.swift",
source + "/**/*Test*.swift"
]
# make sure to declare YogaKit on your Podfile as:
# pod 'YogaKit', :git => '[email protected]:lucasaraujo/yoga.git'
# We need this because we fixed an issue in the original repository and our PR was not merged yet.
beagleUI.frameworks = 'Foundation', 'CoreData'
beagleUI.dependency 'YogaKit'
end
# ――― Beagle Preview ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
spec.subspec 'Preview' do |preview|
source = 'iOS/Sources/Preview/Sources'
preview.source_files = source + '/**/*.swift'
preview.dependency 'Starscream'
end
end
| 31.775701 | 102 | 0.569706 |
62b3d5161093a15da547bdb65e72059fa95f6942 | 1,650 | require 'spec_helper'
describe Cnab240::V87::Pagamentos::Header do
it "deve conter campos header" do
header = Cnab240::V87::Pagamentos::Header.new
header.should respond_to(:controle_banco)
header.should respond_to(:controle_lote)
header.should respond_to(:controle_registro)
header.should respond_to(:servico_operacao)
header.should respond_to(:servico_tipo)
header.should respond_to(:servico_forma)
header.should respond_to(:servico_layout)
header.should respond_to(:cnab_g004_1)
header.should respond_to(:empresa_tipo)
header.should respond_to(:empresa_numero)
header.should respond_to(:empresa_convenio)
header.should respond_to(:empresa_agencia_codigo)
header.should respond_to(:empresa_agencia_dv)
header.should respond_to(:empresa_conta_numero)
header.should respond_to(:empresa_conta_dv)
header.should respond_to(:empresa_agencia_conta_dv)
header.should respond_to(:empresa_nome)
header.should respond_to(:informacao_1)
header.should respond_to(:endereco_logradouro)
header.should respond_to(:endereco_numero)
header.should respond_to(:endereco_complemento)
header.should respond_to(:endereco_cidade)
header.should respond_to(:endereco_cep)
header.should respond_to(:endereco_complemento_cep)
header.should respond_to(:endereco_estado)
header.should respond_to(:indicativo_forma_pagamento)
header.should respond_to(:cnab_g004_2)
header.should respond_to(:ocorrencias)
end
it "header deve ter 240 caracteres" do
header = Cnab240::V87::Pagamentos::Header.new
header.linha.length.should be(240)
end
end | 33 | 57 | 0.773939 |
bfa2a809dd7d7fd472990b00d6f38c8948fd36ce | 4,482 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
require 'devise'
I18n.config.enforce_available_locales = false
Bundler.require(:default, Rails.env)
module Gitlab
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths.push(*%W(#{config.root}/lib
#{config.root}/app/models/hooks
#{config.root}/app/models/concerns
#{config.root}/app/models/project_services
#{config.root}/app/models/members))
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
config.i18n.enforce_available_locales = false
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters.push(:password, :password_confirmation, :private_token, :otp_attempt)
# Enable escaping HTML in JSON.
config.active_support.escape_html_entities_in_json = true
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Enable the asset pipeline
config.assets.enabled = true
config.assets.paths << Emoji.images_path
config.assets.precompile << "emoji/*.png"
config.assets.precompile << "print.css"
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.action_view.sanitized_allowed_protocols = %w(smb)
# Relative url support
# Uncomment and customize the last line to run in a non-root path
# WARNING: We recommend creating a FQDN to host GitLab in a root path instead of this.
# Note that following settings need to be changed for this to work.
# 1) In your application.rb file: config.relative_url_root = "/gitlab"
# 2) In your gitlab.yml file: relative_url_root: /gitlab
# 3) In your unicorn.rb: ENV['RAILS_RELATIVE_URL_ROOT'] = "/gitlab"
# 4) In ../gitlab-shell/config.yml: gitlab_url: "http://127.0.0.1/gitlab"
# 5) In lib/support/nginx/gitlab : do not use asset gzipping, remove block starting with "location ~ ^/(assets)/"
#
# To update the path, run: sudo -u git -H bundle exec rake assets:precompile RAILS_ENV=production
#
# config.relative_url_root = "/gitlab"
config.middleware.use Rack::Attack
# Allow access to GitLab API from other domains
config.middleware.use Rack::Cors do
allow do
origins '*'
resource '/api/*',
headers: :any,
methods: :any,
expose: ['Link']
end
end
# Use Redis caching across all environments
redis_config_file = Rails.root.join('config', 'resque.yml')
redis_url_string = if File.exists?(redis_config_file)
YAML.load_file(redis_config_file)[Rails.env]
else
"redis://localhost:6379"
end
# Redis::Store does not handle Unix sockets well, so let's do it for them
redis_config_hash = Redis::Store::Factory.extract_host_options_from_uri(redis_url_string)
redis_uri = URI.parse(redis_url_string)
if redis_uri.scheme == 'unix'
redis_config_hash[:path] = redis_uri.path
end
redis_config_hash[:namespace] = 'cache:gitlab'
redis_config_hash[:expires_in] = 2.weeks # Cache should not grow forever
config.cache_store = :redis_store, redis_config_hash
# This is needed for gitlab-shell
ENV['GITLAB_PATH_OUTSIDE_HOOK'] = ENV['PATH']
end
end
| 42.283019 | 117 | 0.677822 |
e20bca437b8c9583c675e4362a2863b1ddcf5c32 | 3,355 | require File.dirname(__FILE__) + '/test_helper.rb'
class TestImg < Test::Unit::TestCase
def setup
return unless $dirname.nil?
$dirname = File.dirname(__FILE__)
$bytes888 = []
$bytes8888 = []
$bytes8888rev = []
$bytes565 = []
$bytes4444 = []
$bytes5551 = []
512.times do |y|
512.times do |x|
r = (255 * x / 511.0).round
g = (255 * (511 - x) / 511.0).round
b = (255 * y / 511.0).round
a = (255 * y / 511.0).round
$bytes888.push(r)
$bytes888.push(g)
$bytes888.push(b)
$bytes8888.push(r)
$bytes8888.push(g)
$bytes8888.push(b)
$bytes8888.push(a)
$bytes8888rev.push(a)
$bytes8888rev.push(r)
$bytes8888rev.push(g)
$bytes8888rev.push(b)
# each 16-bit pixel is expressed in big endian order.
r5 = (r * 31 / 255.0).round
g6 = (g * 63 / 255.0).round
b5 = (b * 31 / 255.0).round
p = (r5 << 11) | (g6 << 5) | b5
$bytes565.push((p >> 8) & 0xff)
$bytes565.push((p >> 0) & 0xff)
r4 = (r * 15 / 255.0).round
g4 = (g * 15 / 255.0).round
b4 = (b * 15 / 255.0).round
a4 = (a * 15 / 255.0).round
p = (r4 << 12) | (g4 << 8) | (b4 << 4) | a4
$bytes4444.push((p >> 8) & 0xff)
$bytes4444.push((p >> 0) & 0xff)
r5 = (r * 31 / 255.0).round
g5 = (g * 31 / 255.0).round
b5 = (b * 31 / 255.0).round
a1 = (a * 1 / 255.0).round
p = (r5 << 11) | (g5 << 6) | (b5 << 1) | a1
$bytes5551.push((p >> 8) & 0xff)
$bytes5551.push((p >> 0) & 0xff)
end
end
$bytes888 = $bytes888.pack('C*')
$bytes8888 = $bytes8888.pack('C*')
$bytes8888rev = $bytes8888rev.pack('C*')
$bytes565 = $bytes565.pack('C*')
$bytes4444 = $bytes4444.pack('C*')
$bytes5551 = $bytes5551.pack('C*')
end
def test_version
version = File.read($dirname + '/../VERSION').chomp
assert Img::VERSION == version
end
def test_save_888_png
Img::save($dirname + '/img-888.png', 512, 512, Img::RGB888, $bytes888)
end
def test_save_8888_png
Img::save($dirname + '/img-8888.png', 512, 512, Img::RGBA8888, $bytes8888)
end
def test_save_8888rev_png
Img::save($dirname + '/img-8888rev.png', 512, 512, Img::ARGB8888, $bytes8888rev)
end
def test_save_565_png
Img::save($dirname + '/img-565.png', 512, 512, Img::RGB565, $bytes565)
end
def test_save_4444_png
Img::save($dirname + '/img-4444.png', 512, 512, Img::RGBA4444, $bytes4444)
end
def test_save_5551_png
Img::save($dirname + '/img-5551.png', 512, 512, Img::RGBA5551, $bytes5551)
end
def test_save_888_jpg
Img::save($dirname + '/img-888.jpg', 512, 512, Img::RGB888, $bytes888)
end
def test_save_8888_jpg
Img::save($dirname + '/img-8888.jpg', 512, 512, Img::RGBA8888, $bytes8888)
end
def test_save_8888rev_jpg
Img::save($dirname + '/img-8888rev.jpg', 512, 512, Img::ARGB8888, $bytes8888rev)
end
def test_save_565_jpg
Img::save($dirname + '/img-565.jpg', 512, 512, Img::RGB565, $bytes565)
end
def test_save_4444_jpg
Img::save($dirname + '/img-4444.jpg', 512, 512, Img::RGBA4444, $bytes4444)
end
def test_save_5551_jpg
Img::save($dirname + '/img-5551.jpg', 512, 512, Img::RGBA5551, $bytes5551)
end
end
| 28.922414 | 84 | 0.559463 |
d5cf9e0d53aca4d2180363f4492b518bc6218854 | 798 | # frozen_string_literal: true
# rubocop:disable Style/Documentation
# rubocop:disable Metrics/LineLength
module Gitlab
module BackgroundMigration
class AddMergeRequestDiffCommitsCount
class MergeRequestDiff < ActiveRecord::Base
self.table_name = 'merge_request_diffs'
end
def perform(start_id, stop_id)
Rails.logger.info("Setting commits_count for merge request diffs: #{start_id} - #{stop_id}")
update = '
commits_count = (
SELECT count(*)
FROM merge_request_diff_commits
WHERE merge_request_diffs.id = merge_request_diff_commits.merge_request_diff_id
)'.squish
MergeRequestDiff.where(id: start_id..stop_id).where(commits_count: nil).update_all(update)
end
end
end
end
| 29.555556 | 100 | 0.695489 |
1dfc58763a7c0d7ca3ccb45eeae7e32d144d01c9 | 4,528 | =begin
#Fatture in Cloud API v2 - API Reference
#Connect your software with Fatture in Cloud, the invoicing platform chosen by more than 400.000 businesses in Italy. The Fatture in Cloud API is based on REST, and makes possible to interact with the user related data prior authorization via OAuth2 protocol.
The version of the OpenAPI document: 2.0.7
Contact: [email protected]
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.3.0
=end
require 'spec_helper'
require 'json'
# Unit tests for FattureInCloud_Ruby_Sdk::IssuedEInvoicesApi
# Automatically generated by openapi-generator (https://openapi-generator.tech)
# Please update as you see appropriate
describe 'IssuedEInvoicesApi' do
before do
# run before each test
@api_instance = FattureInCloud_Ruby_Sdk::IssuedEInvoicesApi.new
@send_e_invoice_response_obj = { "data": { "name": "CARICATO", "date": "2021-08-23 10:38:03" } }
allow(@api_instance).to receive(:send_e_invoice) { @send_e_invoice_response_obj }
@verify_e_invoice_xml_response_obj = { "data": { "success": true } }
allow(@api_instance).to receive(:verify_e_invoice_xml) { @verify_e_invoice_xml_response_obj }
@get_e_invoice_xml_response = "<xml-fattura>fields</xml-fattura>"
allow(@api_instance).to receive(:get_e_invoice_xml) { @get_e_invoice_xml_response }
@get_e_invoice_rejection_reason_response_obj = { "data": { "reason": "invalid data" } }
allow(@api_instance).to receive(:get_e_invoice_rejection_reason) { @get_e_invoice_rejection_reason_response_obj }
end
after do
# run after each test
end
describe 'test an instance of IssuedEInvoicesApi' do
it 'should create an instance of IssuedEInvoicesApi' do
expect(@api_instance).to be_instance_of(FattureInCloud_Ruby_Sdk::IssuedEInvoicesApi)
end
end
# unit tests for send_e_invoice
# Send the e-invoice
# Sends the e-invoice to SDI.
# @param company_id The ID of the company.
# @param document_id The ID of the document.
# @param [Hash] opts the optional parameters
# @option opts [SendEInvoiceRequest] :send_e_invoice_request
# @return [SendEInvoiceResponse]
describe 'send_e_invoice test' do
it 'should work' do
response = @api_instance.send_e_invoice(2, 22)
response_obj = JSON.parse(response.to_json, object_class: OpenStruct)
expected_json = @send_e_invoice_response_obj.to_json
actual_json = response.to_json
expect(actual_json).to eq(expected_json)
end
end
# unit tests for verify_e_invoice_xml
# Verify e-invoice xml
# Verifies the e-invoice xml format. Checks if all of the mandatory fields are filled and compliant to the right format.
# @param company_id The ID of the company.
# @param document_id The ID of the document.
# @param [Hash] opts the optional parameters
# @return [VerifyEInvoiceXmlResponse]
describe 'verify_e_invoice_xml test' do
it 'should work' do
response = @api_instance.verify_e_invoice_xml(2, 22)
response_obj = JSON.parse(response.to_json, object_class: OpenStruct)
expected_json = @verify_e_invoice_xml_response_obj.to_json
actual_json = response.to_json
expect(actual_json).to eq(expected_json)
end
end
# unit tests for get_e_invoice_xml
# Get e-invoice XML
# Downloads the e-invoice in XML format.
# @param company_id The ID of the company.
# @param document_id The ID of the document.
# @param [Hash] opts the optional parameters
# @option opts [Boolean] :include_attachment Include the attachment to the XML e-invoice.
# @return [String]
describe 'get_e_invoice_xml test' do
it 'should work' do
response = @api_instance.get_e_invoice_xml(2, 22, true)
expected = @get_e_invoice_xml_response
expect(response).to eq(expected)
end
end
# unit tests for get_e_invoice_rejection_reason
# Get EInvoice rejection reason
# Get EInvoice rejection reason
# @param company_id The ID of the company.
# @param document_id The ID of the document.
# @param [Hash] opts the optional parameters
# @return [GetEInvoiceRejectionReasonResponse]
describe 'get_e_invoice_rejection_reason test' do
it 'should work' do
response = @api_instance.get_e_invoice_rejection_reason(2, 22)
response_obj = JSON.parse(response.to_json, object_class: OpenStruct)
expected_json = @get_e_invoice_rejection_reason_response_obj.to_json
actual_json = response.to_json
expect(actual_json).to eq(expected_json)
end
end
end
| 37.421488 | 261 | 0.746246 |
1c1fd46aed5abdda0abb58aad87ee2c29d92d7a1 | 735 | # A module to produce resources for a Garry's Mod server
class GarrysMod
attr_reader :name, :app_id, :friendly_name
def initialize
@name = "gmod"
@app_id = "4020"
@friendly_name = "Garry's Mod" #TODO: Add friendly name to all server objects
end
def launch(install_path, map = "gm_construct", players = 16, collection_id = "1838303608")
"cd #{install_path} &&
#{install_path}/srcds_run \
-console \
-game garrysmod \
+map #{map} \
+maxplayers #{players} \
+host_workshop_collection #{collection_id} \
-condebug & \
/usr/bin/tail -f #{install_path}/garrysmod/console.log"
end
def post_install(install_path)
system("touch #{install_path}/garrysmod/console.log")
end
end
| 28.269231 | 92 | 0.67483 |
e850ace3e79a1187ef895db1b3d1bc74451b87d5 | 3,384 | require 'spec_helper'
describe Restforce::Concerns::Authentication do
describe '.authenticate!' do
subject(:authenticate!) { client.authenticate! }
context 'when there is no authentication middleware' do
before do
client.stub authentication_middleware: nil
end
it "raises an error" do
expect { authenticate! }.to raise_error Restforce::AuthenticationError,
'No authentication middleware present'
end
end
context 'when there is authentication middleware' do
let(:authentication_middleware) { double('Authentication Middleware') }
subject(:result) { client.authenticate! }
it 'authenticates using the middleware' do
client.stub authentication_middleware: authentication_middleware
client.stub :options
authentication_middleware.
should_receive(:new).
with(nil, client, client.options).
and_return(double(authenticate!: 'foo'))
expect(result).to eq 'foo'
end
end
end
describe '.authentication_middleware' do
subject { client.authentication_middleware }
context 'when username and password options are provided' do
before do
client.stub username_password?: true
end
it { should eq Restforce::Middleware::Authentication::Password }
end
context 'when oauth options are provided' do
before do
client.stub username_password?: false
client.stub oauth_refresh?: true
end
it { should eq Restforce::Middleware::Authentication::Token }
end
context 'when jwt option is provided' do
before do
client.stub username_password?: false
client.stub oauth_refresh?: false
client.stub jwt?: true
end
it { should eq Restforce::Middleware::Authentication::JWTBearer }
end
end
describe '.username_password?' do
subject { client.username_password? }
let(:options) { {} }
before do
client.stub options: options
end
context 'when username and password options are provided' do
let(:options) do
{ username: 'foo',
password: 'bar',
client_id: 'client',
client_secret: 'secret' }
end
it { should be_true }
end
context 'when username and password options are not provided' do
it { should_not be_true }
end
end
describe '.oauth_refresh?' do
subject { client.oauth_refresh? }
let(:options) { {} }
before do
client.stub options: options
end
context 'when oauth options are provided' do
let(:options) do
{ refresh_token: 'token',
client_id: 'client',
client_secret: 'secret' }
end
it { should be_true }
end
context 'when oauth options are not provided' do
it { should_not be_true }
end
end
describe '.jwt?' do
subject { client.jwt? }
let(:options) { Hash.new }
before do
client.stub options: options
end
context 'when jwt options are provided' do
let(:options) do
{ jwt_key: 'path/to/private/key',
username: 'foo',
client_id: 'client' }
end
it { should be_true }
end
context 'when jwt options are not provided' do
it { should_not be_true }
end
end
end
| 25.066667 | 86 | 0.624704 |
b96eaab0927f4487729a1f7010ba4f11de698523 | 447 | cask 'localizationeditor' do
version '2.3'
sha256 'a3b6914ec001effd1d74a8de28550dd475d3168f9487ef8d479503cedd60779c'
url "https://github.com/igorkulman/iOSLocalizationEditor/releases/download/v#{version}/LocalizationEditor.app.zip"
appcast 'https://github.com/igorkulman/iOSLocalizationEditor/releases.atom'
name 'LocalizationEditor'
homepage 'https://github.com/igorkulman/iOSLocalizationEditor/'
app 'LocalizationEditor.app'
end
| 37.25 | 116 | 0.816555 |
e807ffa4470f78f4ef3c1d28d7164d113c90a9d1 | 211 | $LOAD_PATH.unshift(File.dirname(__FILE__) + '/../../lib')
require 'foo'
require 'test/unit/assertions'
require 'test/unit/assertions'
World do |world|
world.extend(Test::Unit::Assertions)
world
end
| 15.071429 | 57 | 0.696682 |
26c855204b05e48ef77a0dc15fcbd2ceb6537790 | 1,233 | =begin
#Accounting API
#No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
The version of the OpenAPI document: 2.1.3
Contact: [email protected]
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 4.3.0
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for XeroRuby::Accounting::CISSetting
# Automatically generated by openapi-generator (https://openapi-generator.tech)
# Please update as you see appropriate
describe 'CISSetting' do
before do
# run before each test
@instance = XeroRuby::Accounting::CISSetting.new
end
after do
# run after each test
end
describe 'test an instance of CISSetting' do
it 'should create an instance of CISSetting' do
expect(@instance).to be_instance_of(XeroRuby::Accounting::CISSetting)
end
end
describe 'test attribute "cis_enabled"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "rate"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end
| 25.6875 | 107 | 0.736415 |
38f19120d00b669f9970ea31e39b6bc003723808 | 4,080 | # frozen_string_literal: true
RSpec.describe 'extractor/type' do
include_context 'clean-up builder'
include_context 'duh common'
before(:all) do
RgGen.enable(:bit_field, :type)
end
it '\'access\'/\'modifiedWriteValue\'/\'readAction\'/\'reserved\'を取り出してbit_field階層の\'type\'とする' do
duh = <<~'DUH'
{
component: {
memoryMaps: [{
addressBlocks: [{
usage: 'register',
registers: [{
fields: [
{ access: 'read-write' },
{ access: 'read-only' },
{ access: 'write-only' },
{ access: 'read-write', readAction: 'clear' },
{ access: 'read-write', readAction: 'set' },
{ access: 'read-only', readAction: 'clear' },
{ access: 'read-write', modifiedWriteValue: 'zeroToClear' },
{ access: 'read-write', modifiedWriteValue: 'oneToClear' },
{ access: 'read-write', modifiedWriteValue: 'clear' },
{ access: 'write-only', modifiedWriteValue: 'clear' },
{ access: 'read-only', readAction: 'set' },
{ access: 'read-write', modifiedWriteValue: 'zeroToSet' },
{ access: 'read-write', modifiedWriteValue: 'oneToSet' },
{ access: 'read-write', modifiedWriteValue: 'set' },
{ access: 'write-only', modifiedWriteValue: 'set' },
{ access: 'read-write', modifiedWriteValue: 'zeroToToggle' },
{ access: 'read-write', modifiedWriteValue: 'oneToToggle' },
{ access: 'read-write', modifiedWriteValue: 'zeroToClear', readAction: 'set' },
{ access: 'read-write', modifiedWriteValue: 'oneToClear', readAction: 'set' },
{ access: 'read-write', modifiedWriteValue: 'clear', readAction: 'set' },
{ access: 'read-write', modifiedWriteValue: 'zeroToSet', readAction: 'clear' },
{ access: 'read-write', modifiedWriteValue: 'oneToSet', readAction: 'clear' },
{ access: 'read-write', modifiedWriteValue: 'set', readAction: 'clear' },
{ access: 'read-writeOnce' },
{ access: 'writeOnce' },
{ reserved: true }
]
}]
}]
}]
}
}
DUH
setup_duh_file(duh)
loader.load_file(file_name, input_data, valid_value_lists)
[
:rw, :ro, :wo, :wrc, :wrs, :rc, :w0c, :w1c, :wc, :woc, :rs, :w0s, :w1s, :ws, :wos,
:w0t, :w1t, :w0crs, :w1crs, :wcrs, :w0src, :w1src, :wsrc, :w1, :wo1, :reserved
].each_with_index do |type, i|
expect(bit_fields[i]).to have_value(:type, type)
end
end
context '\'access\'が未指定の場合' do
specify '上位階層の\'access\'が参照される' do
duh = <<~'DUH'
{
component: {
memoryMaps: [{
addressBlocks: [{
usage: 'register',
access: 'read-only',
registerFiles: [{
registers: [{
fields: [{}]
}]
}],
registers: [{
access: 'write-only',
fields: [{}]
},{
fields: [{}]
}]
},{
usage: 'register',
registers: [{
fields: [{}]
}],
registerFiles: [{
registers: [{
fields: [{}]
}]
}]
}]
}]
}
}
DUH
setup_duh_file(duh)
loader.load_file(file_name, input_data, valid_value_lists)
expect(bit_fields[0]).to have_value(:type, :ro)
expect(bit_fields[1]).to have_value(:type, :wo)
expect(bit_fields[2]).to have_value(:type, :ro)
expect(bit_fields[3]).to have_value(:type, :rw)
expect(bit_fields[4]).to have_value(:type, :rw)
end
end
end
| 36.428571 | 100 | 0.472794 |
28ce1eb5e00467e2e3c86e377319761b7d4c45ad | 162 | Copy the last part of a file.
{[Spec]}[http://pubs.opengroup.org/onlinepubs/9699919799/utilities/tail.html]
(file, options={})
--
execute 'tail', file, options | 27 | 77 | 0.716049 |
bf166bd4834abd570e5614065c8bb0830d95f83a | 1,675 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# 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
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Disables whiny requests
config.web_console.whiny_requests = false
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
| 37.222222 | 85 | 0.773731 |
219adf55ebe8da0c27f19a726f549b55760afe70 | 3,630 | require "rails_helper"
RSpec.describe "Notifications page", :with_stubbed_antivirus, :with_stubbed_notify, type: :request do
context "when signed in as a poison centre user but accessing from submit domain", with_errors_rendered: true do
let(:responsible_person) { create(:responsible_person) }
before do
sign_in_as_poison_centre_user
configure_requests_for_submit_domain
get "/responsible_persons/#{responsible_person.id}/notifications"
end
after do
sign_out(:search_user)
end
it "redirects to invalid account page" do
expect(response).to redirect_to("/invalid-account")
end
end
context "when signed in as a user of a responsible_person" do
let(:responsible_person) { create(:responsible_person, :with_a_contact_person) }
let(:user) { build(:submit_user) }
let(:other_responsible_person) { create(:responsible_person, :with_a_contact_person) }
let(:other_user) { build(:submit_user) }
before do
sign_in_as_member_of_responsible_person(responsible_person, user)
end
after do
sign_out(:submit_user)
end
context "when requesting notifications for the company associated with the user" do
before do
travel_to(Time.zone.local(2021, 2, 20, 13))
# Setup notifications belonging to the company
create(:draft_notification, responsible_person: responsible_person)
create(:registered_notification, product_name: "Product 1", reference_number: 1, responsible_person: responsible_person)
# Setup notifications belonging to other companies or users
create(:draft_notification, responsible_person: other_responsible_person)
create(:registered_notification, responsible_person: other_responsible_person)
end
context "when visiting notification page" do
before do
get "/responsible_persons/#{responsible_person.id}/notifications"
end
it "renders the page successfully" do
expect(response.status).to be(200)
end
it "displays the number of draft notifications" do
expect(response.body).to include("Incomplete notifications (1)")
end
it "displays the number of completed notifications" do
expect(response.body).to include("Product notifications (1)")
end
end
context "when downloading notifications as a file" do
before do
travel_to(Time.zone.local(2021, 2, 20, 13, 1))
create(:registered_notification, product_name: "Product 2", reference_number: 2, responsible_person: responsible_person)
Notification.all.each(&:cache_notification_for_csv!)
get "/responsible_persons/#{responsible_person.id}/notifications.csv"
end
let(:expected_csv) do
<<~CSV
Product name,UK cosmetic product number,Notification date,EU Reference number,EU Notification date,Internal reference,Number of items,Item 1 Level 1 category,Item 1 Level 2 category,Item 1 Level 3 category
Product 1,UKCP-00000001,2021-02-20 13:00:00 +0000,,,,0
Product 2,UKCP-00000002,2021-02-20 13:01:00 +0000,,,,0
CSV
end
it "returns file with proper notifications" do
expect(response.body).to eq expected_csv
end
end
end
context "when requesting notifications for non-existant company ID" do
before do
get "/responsible_persons/99999999/notifications"
end
it "responds with a 404 Page not found error" do
expect(response).to redirect_to("/404")
end
end
end
end
| 35.242718 | 217 | 0.693664 |
33ba0ddcddf9b015d37869902b7fd08ffec650bc | 31,584 | require 'digest/md5'
require 'cgi'
require 'etc'
require 'uri'
require 'fileutils'
require 'enumerator'
require 'pathname'
require 'puppet/parameter/boolean'
require 'puppet/util/diff'
require 'puppet/util/checksums'
require 'puppet/util/backups'
require 'puppet/util/symbolic_file_mode'
Puppet::Type.newtype(:file) do
include Puppet::Util::MethodHelper
include Puppet::Util::Checksums
include Puppet::Util::Backups
include Puppet::Util::SymbolicFileMode
@doc = "Manages files, including their content, ownership, and permissions.
The `file` type can manage normal files, directories, and symlinks; the
type should be specified in the `ensure` attribute.
File contents can be managed directly with the `content` attribute, or
downloaded from a remote source using the `source` attribute; the latter
can also be used to recursively serve directories (when the `recurse`
attribute is set to `true` or `local`). On Windows, note that file
contents are managed in binary mode; Puppet never automatically translates
line endings.
**Autorequires:** If Puppet is managing the user or group that owns a
file, the file resource will autorequire them. If Puppet is managing any
parent directories of a file, the file resource will autorequire them."
feature :manages_symlinks,
"The provider can manage symbolic links."
def self.title_patterns
[ [ /^(.*?)\/*\Z/m, [ [ :path ] ] ] ]
end
newparam(:path) do
desc <<-'EOT'
The path to the file to manage. Must be fully qualified.
On Windows, the path should include the drive letter and should use `/` as
the separator character (rather than `\\`).
EOT
isnamevar
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "File paths must be fully qualified, not '#{value}'"
end
end
munge do |value|
if value.start_with?('//') and ::File.basename(value) == "/"
# This is a UNC path pointing to a share, so don't add a trailing slash
::File.expand_path(value)
else
::File.join(::File.split(::File.expand_path(value)))
end
end
end
newparam(:backup) do
desc <<-EOT
Whether (and how) file content should be backed up before being replaced.
This attribute works best as a resource default in the site manifest
(`File { backup => main }`), so it can affect all file resources.
* If set to `false`, file content won't be backed up.
* If set to a string beginning with `.` (e.g., `.puppet-bak`), Puppet will
use copy the file in the same directory with that value as the extension
of the backup. (A value of `true` is a synonym for `.puppet-bak`.)
* If set to any other string, Puppet will try to back up to a filebucket
with that title. See the `filebucket` resource type for more details.
(This is the preferred method for backup, since it can be centralized
and queried.)
Default value: `puppet`, which backs up to a filebucket of the same name.
(Puppet automatically creates a **local** filebucket named `puppet` if one
doesn't already exist.)
Backing up to a local filebucket isn't particularly useful. If you want
to make organized use of backups, you will generally want to use the
puppet master server's filebucket service. This requires declaring a
filebucket resource and a resource default for the `backup` attribute
in site.pp:
# /etc/puppet/manifests/site.pp
filebucket { 'main':
path => false, # This is required for remote filebuckets.
server => 'puppet.example.com', # Optional; defaults to the configured puppet master.
}
File { backup => main, }
If you are using multiple puppet master servers, you will want to
centralize the contents of the filebucket. Either configure your load
balancer to direct all filebucket traffic to a single master, or use
something like an out-of-band rsync task to synchronize the content on all
masters.
EOT
defaultto "puppet"
munge do |value|
# I don't really know how this is happening.
value = value.shift if value.is_a?(Array)
case value
when false, "false", :false
false
when true, "true", ".puppet-bak", :true
".puppet-bak"
when String
value
else
self.fail "Invalid backup type #{value.inspect}"
end
end
end
newparam(:recurse) do
desc "Whether to recursively manage the _contents_ of a directory. This attribute
is only used when `ensure => directory` is set. The allowed values are:
* `false` --- The default behavior. The contents of the directory will not be
automatically managed.
* `remote` --- If the `source` attribute is set, Puppet will automatically
manage the contents of the source directory (or directories), ensuring
that equivalent files and directories exist on the target system and
that their contents match.
Using `remote` will disable the `purge` attribute, but results in faster
catalog application than `recurse => true`.
The `source` attribute is mandatory when `recurse => remote`.
* `true` --- If the `source` attribute is set, this behaves similarly to
`recurse => remote`, automatically managing files from the source directory.
This also enables the `purge` attribute, which can delete unmanaged
files from a directory. See the description of `purge` for more details.
The `source` attribute is not mandatory when using `recurse => true`, so you
can enable purging in directories where all files are managed individually.
(Note: `inf` is a deprecated synonym for `true`.)
By default, setting recurse to `remote` or `true` will manage _all_
subdirectories. You can use the `recurselimit` attribute to limit the
recursion depth.
"
newvalues(:true, :false, :inf, :remote)
validate { |arg| }
munge do |value|
newval = super(value)
case newval
when :true, :inf; true
when :false; false
when :remote; :remote
else
self.fail "Invalid recurse value #{value.inspect}"
end
end
end
newparam(:recurselimit) do
desc "How far Puppet should descend into subdirectories, when using
`ensure => directory` and either `recurse => true` or `recurse => remote`.
The recursion limit affects which files will be copied from the `source`
directory, as well as which files can be purged when `purge => true`.
Setting `recurselimit => 0` is the same as setting `recurse => false` ---
Puppet will manage the directory, but all of its contents will be treated
as unmanaged.
Setting `recurselimit => 1` will manage files and directories that are
directly inside the directory, but will not manage the contents of any
subdirectories.
Setting `recurselimit => 2` will manage the direct contents of the
directory, as well as the contents of the _first_ level of subdirectories.
And so on --- 3 will manage the contents of the second level of
subdirectories, etc."
newvalues(/^[0-9]+$/)
munge do |value|
newval = super(value)
case newval
when Integer, Fixnum, Bignum; value
when /^\d+$/; Integer(value)
else
self.fail "Invalid recurselimit value #{value.inspect}"
end
end
end
newparam(:replace, :boolean => true, :parent => Puppet::Parameter::Boolean) do
desc "Whether to replace a file or symlink that already exists on the local system but
whose content doesn't match what the `source` or `content` attribute
specifies. Setting this to false allows file resources to initialize files
without overwriting future changes. Note that this only affects content;
Puppet will still manage ownership and permissions. Defaults to `true`."
defaultto :true
end
newparam(:force, :boolean => true, :parent => Puppet::Parameter::Boolean) do
desc "Perform the file operation even if it will destroy one or more directories.
You must use `force` in order to:
* `purge` subdirectories
* Replace directories with files or links
* Remove a directory when `ensure => absent`"
defaultto false
end
newparam(:ignore) do
desc "A parameter which omits action on files matching
specified patterns during recursion. Uses Ruby's builtin globbing
engine, so shell metacharacters are fully supported, e.g. `[a-z]*`.
Matches that would descend into the directory structure are ignored,
e.g., `*/*`."
validate do |value|
unless value.is_a?(Array) or value.is_a?(String) or value == false
self.devfail "Ignore must be a string or an Array"
end
end
end
newparam(:links) do
desc "How to handle links during file actions. During file copying,
`follow` will copy the target file instead of the link, `manage`
will copy the link itself, and `ignore` will just pass it by.
When not copying, `manage` and `ignore` behave equivalently
(because you cannot really ignore links entirely during local
recursion), and `follow` will manage the file to which the link points."
newvalues(:follow, :manage)
defaultto :manage
end
newparam(:purge, :boolean => true, :parent => Puppet::Parameter::Boolean) do
desc "Whether unmanaged files should be purged. This option only makes
sense when `ensure => directory` and `recurse => true`.
* When recursively duplicating an entire directory with the `source`
attribute, `purge => true` will automatically purge any files
that are not in the source directory.
* When managing files in a directory as individual resources,
setting `purge => true` will purge any files that aren't being
specifically managed.
If you have a filebucket configured, the purged files will be uploaded,
but if you do not, this will destroy data.
Unless `force => true` is set, purging will **not** delete directories,
although it will delete the files they contain.
If `recurselimit` is set and you aren't using `force => true`, purging
will obey the recursion limit; files in any subdirectories deeper than the
limit will be treated as unmanaged and left alone."
defaultto :false
end
newparam(:sourceselect) do
desc "Whether to copy all valid sources, or just the first one. This parameter
only affects recursive directory copies; by default, the first valid
source is the only one used, but if this parameter is set to `all`, then
all valid sources will have all of their contents copied to the local
system. If a given file exists in more than one source, the version from
the earliest source in the list will be used."
defaultto :first
newvalues(:first, :all)
end
newparam(:show_diff, :boolean => true, :parent => Puppet::Parameter::Boolean) do
desc "Whether to display differences when the file changes, defaulting to
true. This parameter is useful for files that may contain passwords or
other secret data, which might otherwise be included in Puppet reports or
other insecure outputs. If the global `show_diff` setting
is false, then no diffs will be shown even if this parameter is true."
defaultto :true
end
newparam(:validate_cmd) do
desc "A command for validating the file's syntax before replacing it. If
Puppet would need to rewrite a file due to new `source` or `content`, it
will check the new content's validity first. If validation fails, the file
resource will fail.
This command must have a fully qualified path, and should contain a
percent (`%`) token where it would expect an input file. It must exit `0`
if the syntax is correct, and non-zero otherwise. The command will be
run on the target system while applying the catalog, not on the puppet master.
Example:
file { '/etc/apache2/apache2.conf':
content => 'example',
validate_cmd => '/usr/sbin/apache2 -t -f %',
}
This would replace apache2.conf only if the test returned true.
Note that if a validation command requires a `%` as part of its text,
you can specify a different placeholder token with the
`validate_replacement` attribute."
end
newparam(:validate_replacement) do
desc "The replacement string in a `validate_cmd` that will be replaced
with an input file name. Defaults to: `%`"
defaultto '%'
end
# Autorequire the nearest ancestor directory found in the catalog.
autorequire(:file) do
req = []
path = Pathname.new(self[:path])
if !path.root?
# Start at our parent, to avoid autorequiring ourself
parents = path.parent.enum_for(:ascend)
if found = parents.find { |p| catalog.resource(:file, p.to_s) }
req << found.to_s
end
end
# if the resource is a link, make sure the target is created first
req << self[:target] if self[:target]
req
end
# Autorequire the owner and group of the file.
{:user => :owner, :group => :group}.each do |type, property|
autorequire(type) do
if @parameters.include?(property)
# The user/group property automatically converts to IDs
next unless should = @parameters[property].shouldorig
val = should[0]
if val.is_a?(Integer) or val =~ /^\d+$/
nil
else
val
end
end
end
end
CREATORS = [:content, :source, :target]
SOURCE_ONLY_CHECKSUMS = [:none, :ctime, :mtime]
validate do
creator_count = 0
CREATORS.each do |param|
creator_count += 1 if self.should(param)
end
creator_count += 1 if @parameters.include?(:source)
self.fail "You cannot specify more than one of #{CREATORS.collect { |p| p.to_s}.join(", ")}" if creator_count > 1
self.fail "You cannot specify a remote recursion without a source" if !self[:source] and self[:recurse] == :remote
self.fail "You cannot specify source when using checksum 'none'" if self[:checksum] == :none && !self[:source].nil?
SOURCE_ONLY_CHECKSUMS.each do |checksum_type|
self.fail "You cannot specify content when using checksum '#{checksum_type}'" if self[:checksum] == checksum_type && !self[:content].nil?
end
self.warning "Possible error: recurselimit is set but not recurse, no recursion will happen" if !self[:recurse] and self[:recurselimit]
provider.validate if provider.respond_to?(:validate)
end
def self.[](path)
return nil unless path
super(path.gsub(/\/+/, '/').sub(/\/$/, ''))
end
def self.instances
return []
end
# Determine the user to write files as.
def asuser
if self.should(:owner) and ! self.should(:owner).is_a?(Symbol)
writeable = Puppet::Util::SUIDManager.asuser(self.should(:owner)) {
FileTest.writable?(::File.dirname(self[:path]))
}
# If the parent directory is writeable, then we execute
# as the user in question. Otherwise we'll rely on
# the 'owner' property to do things.
asuser = self.should(:owner) if writeable
end
asuser
end
def bucket
return @bucket if @bucket
backup = self[:backup]
return nil unless backup
return nil if backup =~ /^\./
unless catalog or backup == "puppet"
fail "Can not find filebucket for backups without a catalog"
end
unless catalog and filebucket = catalog.resource(:filebucket, backup) or backup == "puppet"
fail "Could not find filebucket #{backup} specified in backup"
end
return default_bucket unless filebucket
@bucket = filebucket.bucket
@bucket
end
def default_bucket
Puppet::Type.type(:filebucket).mkdefaultbucket.bucket
end
# Does the file currently exist? Just checks for whether
# we have a stat
def exist?
stat ? true : false
end
def present?(current_values)
super && current_values[:ensure] != :false
end
# We have to do some extra finishing, to retrieve our bucket if
# there is one.
def finish
# Look up our bucket, if there is one
bucket
super
end
# Create any children via recursion or whatever.
def eval_generate
return [] unless self.recurse?
recurse
end
def ancestors
ancestors = Pathname.new(self[:path]).enum_for(:ascend).map(&:to_s)
ancestors.delete(self[:path])
ancestors
end
def flush
# We want to make sure we retrieve metadata anew on each transaction.
@parameters.each do |name, param|
param.flush if param.respond_to?(:flush)
end
@stat = :needs_stat
end
def initialize(hash)
# Used for caching clients
@clients = {}
super
# If they've specified a source, we get our 'should' values
# from it.
unless self[:ensure]
if self[:target]
self[:ensure] = :link
elsif self[:content]
self[:ensure] = :file
end
end
@stat = :needs_stat
end
# Configure discovered resources to be purged.
def mark_children_for_purging(children)
children.each do |name, child|
next if child[:source]
child[:ensure] = :absent
end
end
# Create a new file or directory object as a child to the current
# object.
def newchild(path)
full_path = ::File.join(self[:path], path)
# Add some new values to our original arguments -- these are the ones
# set at initialization. We specifically want to exclude any param
# values set by the :source property or any default values.
# LAK:NOTE This is kind of silly, because the whole point here is that
# the values set at initialization should live as long as the resource
# but values set by default or by :source should only live for the transaction
# or so. Unfortunately, we don't have a straightforward way to manage
# the different lifetimes of this data, so we kludge it like this.
# The right-side hash wins in the merge.
options = @original_parameters.merge(:path => full_path).reject { |param, value| value.nil? }
# These should never be passed to our children.
[:parent, :ensure, :recurse, :recurselimit, :target, :alias, :source].each do |param|
options.delete(param) if options.include?(param)
end
self.class.new(options)
end
# Files handle paths specially, because they just lengthen their
# path names, rather than including the full parent's title each
# time.
def pathbuilder
# We specifically need to call the method here, so it looks
# up our parent in the catalog graph.
if parent = parent()
# We only need to behave specially when our parent is also
# a file
if parent.is_a?(self.class)
# Remove the parent file name
list = parent.pathbuilder
list.pop # remove the parent's path info
return list << self.ref
else
return super
end
else
return [self.ref]
end
end
# Recursively generate a list of file resources, which will
# be used to copy remote files, manage local files, and/or make links
# to map to another directory.
def recurse
children = (self[:recurse] == :remote) ? {} : recurse_local
if self[:target]
recurse_link(children)
elsif self[:source]
recurse_remote(children)
end
# If we're purging resources, then delete any resource that isn't on the
# remote system.
mark_children_for_purging(children) if self.purge?
# REVISIT: sort_by is more efficient?
result = children.values.sort { |a, b| a[:path] <=> b[:path] }
remove_less_specific_files(result)
end
# This is to fix bug #2296, where two files recurse over the same
# set of files. It's a rare case, and when it does happen you're
# not likely to have many actual conflicts, which is good, because
# this is a pretty inefficient implementation.
def remove_less_specific_files(files)
# REVISIT: is this Windows safe? AltSeparator?
mypath = self[:path].split(::File::Separator)
other_paths = catalog.vertices.
select { |r| r.is_a?(self.class) and r[:path] != self[:path] }.
collect { |r| r[:path].split(::File::Separator) }.
select { |p| p[0,mypath.length] == mypath }
return files if other_paths.empty?
files.reject { |file|
path = file[:path].split(::File::Separator)
other_paths.any? { |p| path[0,p.length] == p }
}
end
# A simple method for determining whether we should be recursing.
def recurse?
self[:recurse] == true or self[:recurse] == :remote
end
# Recurse the target of the link.
def recurse_link(children)
perform_recursion(self[:target]).each do |meta|
if meta.relative_path == "."
self[:ensure] = :directory
next
end
children[meta.relative_path] ||= newchild(meta.relative_path)
if meta.ftype == "directory"
children[meta.relative_path][:ensure] = :directory
else
children[meta.relative_path][:ensure] = :link
children[meta.relative_path][:target] = meta.full_path
end
end
children
end
# Recurse the file itself, returning a Metadata instance for every found file.
def recurse_local
result = perform_recursion(self[:path])
return {} unless result
result.inject({}) do |hash, meta|
next hash if meta.relative_path == "."
hash[meta.relative_path] = newchild(meta.relative_path)
hash
end
end
# Recurse against our remote file.
def recurse_remote(children)
sourceselect = self[:sourceselect]
total = self[:source].collect do |source|
next unless result = perform_recursion(source)
return if top = result.find { |r| r.relative_path == "." } and top.ftype != "directory"
result.each { |data| data.source = "#{source}/#{data.relative_path}" }
break result if result and ! result.empty? and sourceselect == :first
result
end.flatten.compact
# This only happens if we have sourceselect == :all
unless sourceselect == :first
found = []
total.reject! do |data|
result = found.include?(data.relative_path)
found << data.relative_path unless found.include?(data.relative_path)
result
end
end
total.each do |meta|
if meta.relative_path == "."
parameter(:source).metadata = meta
next
end
children[meta.relative_path] ||= newchild(meta.relative_path)
children[meta.relative_path][:source] = meta.source
if meta.ftype == "file"
children[meta.relative_path][:checksum] = Puppet[:digest_algorithm].to_sym
end
children[meta.relative_path].parameter(:source).metadata = meta
end
children
end
def perform_recursion(path)
Puppet::FileServing::Metadata.indirection.search(
path,
:links => self[:links],
:recurse => (self[:recurse] == :remote ? true : self[:recurse]),
:recurselimit => self[:recurselimit],
:ignore => self[:ignore],
:checksum_type => (self[:source] || self[:content]) ? self[:checksum] : :none,
:environment => catalog.environment_instance
)
end
# Back up and remove the file or directory at `self[:path]`.
#
# @param [Symbol] should The file type replacing the current content.
# @return [Boolean] True if the file was removed, else False
# @raises [fail???] If the current file isn't one of %w{file link directory} and can't be removed.
def remove_existing(should)
wanted_type = should.to_s
current_type = read_current_type
if current_type.nil?
return false
end
if can_backup?(current_type)
backup_existing
end
if wanted_type != "link" and current_type == wanted_type
return false
end
case current_type
when "directory"
return remove_directory(wanted_type)
when "link", "file"
return remove_file(current_type, wanted_type)
else
self.fail "Could not back up files of type #{current_type}"
end
end
def retrieve
if source = parameter(:source)
source.copy_source_values
end
super
end
# Set the checksum, from another property. There are multiple
# properties that modify the contents of a file, and they need the
# ability to make sure that the checksum value is in sync.
def setchecksum(sum = nil)
if @parameters.include? :checksum
if sum
@parameters[:checksum].checksum = sum
else
# If they didn't pass in a sum, then tell checksum to
# figure it out.
currentvalue = @parameters[:checksum].retrieve
@parameters[:checksum].checksum = currentvalue
end
end
end
# Should this thing be a normal file? This is a relatively complex
# way of determining whether we're trying to create a normal file,
# and it's here so that the logic isn't visible in the content property.
def should_be_file?
return true if self[:ensure] == :file
# I.e., it's set to something like "directory"
return false if e = self[:ensure] and e != :present
# The user doesn't really care, apparently
if self[:ensure] == :present
return true unless s = stat
return(s.ftype == "file" ? true : false)
end
# If we've gotten here, then :ensure isn't set
return true if self[:content]
return true if stat and stat.ftype == "file"
false
end
# Stat our file. Depending on the value of the 'links' attribute, we
# use either 'stat' or 'lstat', and we expect the properties to use the
# resulting stat object accordingly (mostly by testing the 'ftype'
# value).
#
# We use the initial value :needs_stat to ensure we only stat the file once,
# but can also keep track of a failed stat (@stat == nil). This also allows
# us to re-stat on demand by setting @stat = :needs_stat.
def stat
return @stat unless @stat == :needs_stat
method = :stat
# Files are the only types that support links
if (self.class.name == :file and self[:links] != :follow) or self.class.name == :tidy
method = :lstat
end
@stat = begin
Puppet::FileSystem.send(method, self[:path])
rescue Errno::ENOENT => error
nil
rescue Errno::ENOTDIR => error
nil
rescue Errno::EACCES => error
warning "Could not stat; permission denied"
nil
end
end
def to_resource
resource = super
resource.delete(:target) if resource[:target] == :notlink
resource
end
# Write out the file. Requires the property name for logging.
# Write will be done by the content property, along with checksum computation
def write(property)
remove_existing(:file)
mode = self.should(:mode) # might be nil
mode_int = mode ? symbolic_mode_to_int(mode, Puppet::Util::DEFAULT_POSIX_MODE) : nil
if write_temporary_file?
Puppet::Util.replace_file(self[:path], mode_int) do |file|
file.binmode
content_checksum = write_content(file)
file.flush
fail_if_checksum_is_wrong(file.path, content_checksum) if validate_checksum?
if self[:validate_cmd]
output = Puppet::Util::Execution.execute(self[:validate_cmd].gsub(self[:validate_replacement], file.path), :failonfail => true, :combine => true)
output.split(/\n/).each { |line|
self.debug(line)
}
end
end
else
umask = mode ? 000 : 022
Puppet::Util.withumask(umask) { ::File.open(self[:path], 'wb', mode_int ) { |f| write_content(f) } }
end
# make sure all of the modes are actually correct
property_fix
end
private
# @return [String] The type of the current file, cast to a string.
def read_current_type
stat_info = stat
if stat_info
stat_info.ftype.to_s
else
nil
end
end
# @return [Boolean] If the current file can be backed up and needs to be backed up.
def can_backup?(type)
if type == "directory" and not force?
# (#18110) Directories cannot be removed without :force, so it doesn't
# make sense to back them up.
false
else
true
end
end
# @return [Boolean] True if the directory was removed
# @api private
def remove_directory(wanted_type)
if force?
debug "Removing existing directory for replacement with #{wanted_type}"
FileUtils.rmtree(self[:path])
stat_needed
true
else
notice "Not removing directory; use 'force' to override"
false
end
end
# @return [Boolean] if the file was removed (which is always true currently)
# @api private
def remove_file(current_type, wanted_type)
debug "Removing existing #{current_type} for replacement with #{wanted_type}"
Puppet::FileSystem.unlink(self[:path])
stat_needed
true
end
def stat_needed
@stat = :needs_stat
end
# Back up the existing file at a given prior to it being removed
# @api private
# @raise [Puppet::Error] if the file backup failed
# @return [void]
def backup_existing
unless perform_backup
raise Puppet::Error, "Could not back up; will not replace"
end
end
# Should we validate the checksum of the file we're writing?
def validate_checksum?
self[:checksum] !~ /time/
end
# Make sure the file we wrote out is what we think it is.
def fail_if_checksum_is_wrong(path, content_checksum)
newsum = parameter(:checksum).sum_file(path)
return if [:absent, nil, content_checksum].include?(newsum)
self.fail "File written to disk did not match checksum; discarding changes (#{content_checksum} vs #{newsum})"
end
# write the current content. Note that if there is no content property
# simply opening the file with 'w' as done in write is enough to truncate
# or write an empty length file.
def write_content(file)
(content = property(:content)) && content.write(file)
end
def write_temporary_file?
# unfortunately we don't know the source file size before fetching it
# so let's assume the file won't be empty
(c = property(:content) and c.length) || @parameters[:source]
end
# There are some cases where all of the work does not get done on
# file creation/modification, so we have to do some extra checking.
def property_fix
properties.each do |thing|
next unless [:mode, :owner, :group, :seluser, :selrole, :seltype, :selrange].include?(thing.name)
# Make sure we get a new stat objct
@stat = :needs_stat
currentvalue = thing.retrieve
thing.sync unless thing.safe_insync?(currentvalue)
end
end
end
# We put all of the properties in separate files, because there are so many
# of them. The order these are loaded is important, because it determines
# the order they are in the property lit.
require 'puppet/type/file/checksum'
require 'puppet/type/file/content' # can create the file
require 'puppet/type/file/source' # can create the file
require 'puppet/type/file/target' # creates a different type of file
require 'puppet/type/file/ensure' # can create the file
require 'puppet/type/file/owner'
require 'puppet/type/file/group'
require 'puppet/type/file/mode'
require 'puppet/type/file/type'
require 'puppet/type/file/selcontext' # SELinux file context
require 'puppet/type/file/ctime'
require 'puppet/type/file/mtime'
| 33.815846 | 155 | 0.670656 |
4a1a712d6edbf02b97252cd056d08b3dca442407 | 1,259 | # frozen_string_literal: true
require "spec_helper"
require "generators/graphql/object_generator"
class GraphQLGeneratorsObjectGeneratorTest < BaseGeneratorTest
tests Graphql::Generators::ObjectGenerator
test "it generates fields with types" do
commands = [
# GraphQL-style:
["Bird", "wingspan:Int!", "foliage:[Color]"],
# Ruby-style:
["BirdType", "wingspan:!Integer", "foliage:[Types::ColorType]"],
# Mixed
["BirdType", "wingspan:!Int", "foliage:[Color]"],
]
expected_content = <<-RUBY
class Types::BirdType < Types::BaseObject
field :wingspan, Integer, null: false
field :foliage, [Types::ColorType], null: true
end
RUBY
commands.each do |c|
prepare_destination
run_generator(c)
assert_file "app/graphql/types/bird_type.rb", expected_content
end
end
test "it generates classifed file" do
run_generator(["page"])
assert_file "app/graphql/types/page_type.rb", <<-RUBY
class Types::PageType < Types::BaseObject
end
RUBY
end
test "it makes Relay nodes" do
run_generator(["Page", "--node"])
assert_file "app/graphql/types/page_type.rb", <<-RUBY
class Types::PageType < Types::BaseObject
implements GraphQL::Relay::Node.interface
end
RUBY
end
end
| 25.693878 | 70 | 0.693407 |
794291e39d57945071dac67c11b301087e96c2c4 | 298 | require 'test_helper'
class AssignmentTest < ActiveSupport::TestCase
def setup
@assignment = assignments(:one)
end
test "should be valid" do
assert @assignment.valid?
end
test "date should be present" do
@assignment.due_at = nil
assert_not @assignment.valid?
end
end
| 17.529412 | 46 | 0.708054 |
e9b43cd0589d37850e21ae858d5445b12c14913a | 791 | require "test_helper"
module Whitespace
describe Counter do
before do
@counter = Counter.new
end
it "is initially 0" do
expect(@counter.to_int).must_equal 0
end
describe "#increment" do
it "increases its value by 1" do
@counter.increment
expect(@counter.to_int).must_equal 1
end
end
describe "#change_to" do
describe "when the value is non-negative" do
it "changes the counter's value to the given value" do
@counter.change_to 5
expect(@counter.to_int).must_equal 5
end
end
describe "when the value is negative" do
it "raises ArgumentError" do
expect { @counter.change_to -1 }.must_raise ArgumentError
end
end
end
end
end
| 20.815789 | 67 | 0.616941 |
8734ed087cb001d887810b2287ab3f7183d87531 | 1,514 | # frozen_string_literal: true
require "spec_helper"
require "tempfile"
RSpec.describe ReciteCSV::Reader::Core do
let(:dummy_class) do
Class.new do
include ReciteCSV::Reader::Core
const_set(:Row, Class.new(ReciteCSV::Row::Base))
const_set(:DEFAULT_CSV_OPTIONS, headers: :first_row)
end
end
let(:temp_csv) { Tempfile.open("csv") }
let(:reader) do
temp_csv.write(csv_string)
temp_csv.flush
temp_csv.rewind
dummy_class.new(temp_csv)
end
after { temp_csv.close }
describe "#each" do
let(:csv_string) do
CSV.generate do |csv|
csv << %w[COL1 COL2]
csv << %w[V1 V2]
end
end
context "call with a block" do
it "enumerate with row objects" do
r = reader.each do |row|
expect(row).to be_a ReciteCSV::Row::Base
expect(row["COL1"]).to eq "V1"
expect(row["COL2"]).to eq "V2"
end
expect(r).to equal reader
end
end
context "call without a block" do
subject { reader.each }
it { is_expected.to be_a Enumerator }
end
end
describe "methods of Enumerable" do
let(:csv_string) do
CSV.generate do |csv|
csv << %w[COL1 COL2]
csv << %w[V1 V2]
csv << %w[V3 V4]
end
end
describe "#map" do
subject { reader.map { |r| r["COL1"] } }
it { is_expected.to eq %w[V1 V3] }
end
describe "#count" do
subject { reader.count }
it { is_expected.to eq 2 }
end
end
end
| 21.323944 | 58 | 0.585865 |
21f5b2f50400f3b72fd328c2faf66ca7e2a7790c | 4,558 | # frozen_string_literal: true
# inspired https://github.com/opentracing-contrib/ruby-rack-tracer/blob/master/lib/rack/tracer.rb
module JCW
module Rack
class Tracer
REQUEST_URI = "REQUEST_URI"
REQUEST_PATH = "REQUEST_PATH"
REQUEST_METHOD = "REQUEST_METHOD"
# Create a new Rack Tracer middleware.
#
# @param app The Rack application/middlewares stack.
# @param tracer [OpenTracing::Tracer] A tracer to be used when start_span, and extract
# is called.
# @param on_start_span [Proc, nil] A callback evaluated after a new span is created.
# @param on_finish_span [Proc, nil] A callback evaluated after a span is finished.
# @param ignore_paths [Array<Class>] An array of paths to be skiped by the tracer.
# @param errors [Array<Class>] An array of error classes to be captured by the tracer
# as errors. Errors are **not** muted by the middleware, they're re-raised afterwards.
def initialize(app, # rubocop:disable Metrics/ParameterLists
tracer: OpenTracing.global_tracer,
on_start_span: nil,
on_finish_span: nil,
trust_incoming_span: true,
ignore_paths: Wrapper.config.rack_ignore_paths,
errors: [StandardError])
@app = app
@tracer = tracer
@on_start_span = on_start_span
@on_finish_span = on_finish_span
@trust_incoming_span = trust_incoming_span
@errors = errors
@ignore_paths = ignore_paths
end
def call(env)
method = env[REQUEST_METHOD]
path = env[REQUEST_PATH]
url = env[REQUEST_URI]
return @app.call(env) if @ignore_paths.include?(path)
set_extract_env(env)
context = @tracer.extract(OpenTracing::FORMAT_TEXT_MAP, env) if @trust_incoming_span
scope = build_scope(method, url, context)
span = scope.span
perform_on_start_span(env, span, @on_start_span)
call_request(env, span)
rescue *@errors => error
build_error_log(span, error)
raise
ensure
begin
close_scope(scope)
ensure
perform_on_finish_span(span)
end
end
private
def set_extract_env(env)
env["uber-trace-id"] = env["HTTP_UBER_TRACE_ID"]
end
def build_scope(method, url, context)
@tracer.start_active_span(
method,
child_of: context,
tags: {
"component" => "rack",
"span.kind" => "server",
"http.method" => method,
"http.url" => url,
},
)
end
def perform_on_start_span(env, span, on_start_span)
on_start_span&.call(span)
env["rack.span"] = span
end
def call_request(env, span)
@app.call(env).tap do |status_code, _headers, _body|
set_tag(span, status_code, env)
end
end
def set_tag(span, status_code, env)
span.set_tag("http.status_code", status_code)
route = route_from_env(env)
span.operation_name = route
end
def route_from_env(env)
method = env[REQUEST_METHOD]
if (sinatra_route = env["sinatra.route"])
sinatra_route
elsif (rails_controller = env["action_controller.instance"])
"#{method} #{rails_controller.controller_name}/#{rails_controller.action_name}"
elsif (grape_route_args = env["grape.routing_args"] || env["rack.routing_args"])
"#{method} #{grape_route_from_args(grape_route_args)}"
else
"#{method} #{env[REQUEST_PATH] || env["SCRIPT_NAME"] || env["PATH_INFO"]}".strip
end
end
def grape_route_from_args(route_args)
route_info = route_args[:route_info]
if route_info.respond_to?(:path)
route_info.path
elsif (rack_route_options = route_info.instance_variable_get(:@options))
rack_route_options[:path]
end
end
def build_error_log(span, error)
span.set_tag("error", true)
span.log_kv(
event: "error",
"error.kind": error.class.to_s,
"error.object": error,
message: error.message,
stack: error.backtrace.join("\n"),
)
end
def perform_on_finish_span(span)
return unless @on_finish_span
@on_finish_span.call(span)
end
def close_scope(scope)
scope&.close
end
end
end
end
| 32.557143 | 99 | 0.604212 |
260639ca2be97f0f3bebe8673368773de3745545 | 121 | class OffsitePaymentsLatipay
require 'offsite_payments'
require_relative 'offsite_payments/integrations/latipay'
end
| 24.2 | 58 | 0.859504 |
790c864e919d68284603ca38708f1da88cba09e7 | 205 | if ENV['CI'] == 'true'
require 'simplecov'
require 'codecov'
SimpleCov.formatter = SimpleCov::Formatter::Codecov
SimpleCov.start do
add_filter '/spec/'
end
end
require 'rspec'
require 'hss'
| 17.083333 | 53 | 0.692683 |
ab0b2c260440ed71bddc15251f1348d4fda2e0a2 | 1,719 | include Chef::Mixin::ShellOut
def whyrun_supported?
true
end
action :run do
converge_by("Sync #{@new_resource.name}") do
source = @new_resource.source.entries[0]
source = alias_provider(*source)
source = download_source_package(*source)
dest = @new_resource.dest.entries[0]
dest = alias_provider(*dest)
args = [
{:verb => 'sync'},
{:source => build_provider_arg(source)},
{:dest => build_provider_arg(dest)}
]
@new_resource.parameters.each do |k, v|
args << {:setParam => %Q("#{k}"="#{v}") }
end
run_msdeploy args
end
end
private
def build_provider_arg(provider)
"#{provider[0]}=#{provider[1]}"
end
def alias_provider(provider, providerPath)
if provider == :path
provider = :contentPath
end
[provider, providerPath]
end
def download_source_package(provider, providerPath)
if provider == :package then
file_name = ::File.basename(providerPath)
local_file = "#{Chef::Config[:file_cache_path]}/#{file_name}"
remote_file local_file do
action :nothing
source new_resource.source[:package]
end.run_action(:create)
providerPath = local_file
end
return [provider, providerPath]
end
def run_msdeploy(args)
cmd = '"' + get_msdeploy_path + '" '
args.each do |param|
key = param.entries[0][0].to_s
value = param.entries[0][1].to_s
cmd += "-#{key}:#{value} "
end
cmd += "-enableRule:AppOffline"
Chef::Log.info("RUN: #{cmd}")
shell_out!(cmd)
end
def get_msdeploy_path
::Win32::Registry::HKEY_LOCAL_MACHINE.open('SOFTWARE\\Microsoft\\IIS Extensions\\MSDeploy\\3') do |reg|
return "#{reg['InstallPath']}\\msdeploy.exe"
end
end
| 20.710843 | 107 | 0.648633 |
ffd18e54824a91c7b9f2a71a549ef748f15910ff | 1,425 | require 'rails_helper'
RSpec.describe Api::V1::SessionsController, type: :controller do
fixtures :all
describe "POST /" do
describe "when invalid credentials" do
it "should answer status :unauthorized" do
post :create, params: { email: 'invalid@email', password: '123' }
expect(response).to have_http_status(:unauthorized)
end
end
describe "when valid credentials" do
it "answers status :ok" do
alex = users(:alex)
old_token = alex.auth_token
post :create, params: { email: alex.email, password: 'password' }
expect(response).to have_http_status(:ok)
end
it "should generate a new auth token" do
alex = users(:alex)
old_token = alex.auth_token
post :create, params: { email: alex.email, password: 'password' }
alex.reload
expect(alex.auth_token).not_to equal old_token
end
it "should get a json with user attributes" do
alex = users(:alex)
old_token = alex.auth_token
post :create, params: { email: alex.email, password: 'password' }
alex.reload
expected_hash = {
token: alex.auth_token,
email: alex.email,
name: alex.name,
role: alex.role,
customerName: alex.customer.try(:name)
}.to_json
expect(response.body).to eq expected_hash
end
end
end
end
| 25.909091 | 73 | 0.612632 |
6a8da7d9c915c73942d253ad0de577e6da79bbde | 2,223 | class Gws::Survey::ReadablesController < ApplicationController
include Gws::BaseFilter
include Gws::CrudFilter
before_action :set_categories
before_action :set_category
before_action :set_search_params
before_action :set_items
before_action :set_item, only: [:show]
model Gws::Survey::Form
navi_view "gws/survey/main/navi"
append_view_path "app/views/gws/survey/main"
private
def set_selected_group
if params[:group].present? && params[:group] != '-'
@selected_group = @cur_site.descendants.active.where(id: params[:group]).first
end
@selected_group ||= @cur_site
@selected_group
end
def set_crumbs
@crumbs << [@cur_site.menu_survey_label || t('modules.gws/survey'), gws_survey_main_path]
@crumbs << [t('ss.navi.readable'), action: :index, folder_id: '-', category_id: '-']
end
def set_categories
@categories ||= Gws::Survey::Category.site(@cur_site).readable(@cur_user, site: @cur_site)
end
def set_category
return if params[:category_id].blank? || params[:category_id] == '-'
@category ||= @categories.find(params[:category_id])
raise '403' unless @category.readable?(@cur_user) || @category.allowed?(:read, @cur_user, site: @cur_site)
end
def set_search_params
@s = OpenStruct.new(params[:s])
@s[:site] = @cur_site
@s[:user] = @cur_user
if @folder.present?
@s[:folder_ids] = [ @folder.id ]
@s[:folder_ids] += @folder.folders.for_post_reader(@cur_site, @cur_user).pluck(:id)
end
@s[:category_id] = @category.id if @category.present?
@s[:answered_state] ||= 'unanswered'
end
def set_items
@items = @model.site(@cur_site).and_public.
readable(@cur_user, site: @cur_site).
without_deleted.
search(@s)
end
def set_item
@item ||= begin
item = @items.find(params[:id])
item.attributes = fix_params
item
end
rescue Mongoid::Errors::DocumentNotFound => e
return render_destroy(true) if params[:action] == 'destroy'
raise e
end
public
def index
@categories = @categories.tree_sort
@items = @items.order_by(due_date: 1, order: 1, updated: -1).page(params[:page]).per(50)
end
def show
render
end
end
| 26.464286 | 110 | 0.671165 |
edd0b5db8e2cfa9e276dd53b503cf5b8af9cf017 | 4,230 | require 'spec_helper'
describe User do
before(:each) do
@attr = {
:email => '[email protected]',
:password => '123456',
:password_confirmation => '123456'
}
end
it 'should create a new instance given valid attributes' do
User.create!(@attr)
end
describe 'email validations' do
it 'should require an email address' do
no_email_user = User.new(@attr.merge(:email => ''))
no_email_user.should_not be_valid
end
it 'should accept valid email addresses' do
addresses = %w[[email protected] [email protected] [email protected]]
addresses.each do |address|
valid_email_user = User.new(@attr.merge(:email => address))
valid_email_user.should be_valid
end
end
it 'should reject invalid email addresses' do
addresses = %w[user@foo,com user_at_foo.org example.user@foo.]
addresses.each do |address|
invalid_email_user = User.new(@attr.merge(:email => address))
invalid_email_user.should_not be_valid
end
end
it 'should reject duplicate email addresses' do
# Put a user with given email address into the database.
User.create!(@attr)
user_with_duplicate_email = User.new(@attr)
user_with_duplicate_email.should_not be_valid
end
it 'should reject email addresses identical up to case' do
upcased_email = @attr[:email].upcase
User.create!(@attr.merge(:email => upcased_email))
user_with_duplicate_email = User.new(@attr)
user_with_duplicate_email.should_not be_valid
end
end
describe 'password validations' do
it 'should require a password' do
User.new(@attr.merge(:password => '', :password_confirmation => '')).
should_not be_valid
end
it 'should require a matching password confirmation' do
User.new(@attr.merge(:password_confirmation => 'invalid')).
should_not be_valid
end
it 'should reject short passwords' do
short = 'a' * 5
hash = @attr.merge(:password => short, :password_confirmation => short)
User.new(hash).should_not be_valid
end
it 'should reject long passwords' do
long = 'a' * 41
hash = @attr.merge(:password => long, :password_confirmation => long)
User.new(hash).should_not be_valid
end
end
describe 'password encryption' do
before(:each) do
@user = User.create!(@attr)
end
it 'should have an encrypted password attribute' do
@user.should respond_to(:encrypted_password)
end
it 'should set the encrypted password' do
@user.encrypted_password.should_not be_blank
end
end
describe 'automatic user role' do
before(:each) do
Factory(:role, :name => 'User')
@user = User.create!(@attr)
end
it 'should automatically get the user role when setting role_ids=' do
admin_role = Factory(:role, :name => 'Admin')
@user.role_ids = [admin_role.id]
@user.should have(2).roles
end
end
describe 'locking' do
before(:each) do
Factory(:role, :name => 'User')
@user = User.create!(@attr)
end
it 'should accept a locked_at value of 1 and set locked_at to the current timestamp' do
['1', 1].each {|param|
@user.locked_at = param
@user.locked_at.class.should == ActiveSupport::TimeWithZone
}
end
it 'should accept a locked_at value of 0 and set locked_at to nil' do
['0', 0].each {|param|
@user.locked_at = '0'
@user.locked_at.should == nil
}
end
end
describe 'xml & json rendering' do
before(:each) do
@user = User.create!(@attr)
end
it 'should not contain the encrypted password in xml' do
@user.to_xml.should_not =~ /encrypted_password/i
end
it 'should not contain the password salt in xml' do
@user.to_xml.should_not =~ /password_salt/i
end
it 'should not contain the encrypted password in json' do
@user.to_json.should_not =~ /encrypted_password/i
end
it 'should not contain the password salt in json' do
@user.to_json.should_not =~ /password_salt/i
end
end
end | 26.772152 | 91 | 0.64208 |
39a5f439aad7262f4d365395c5cd450aa3e73e5e | 516 | unified_mode true
property :mime_magic_file, String,
default: lazy { default_mime_magic_file },
description: 'The location of the mime magic file
Defaults to platform specific locations, see libraries/helpers.rb'
action :create do
template ::File.join(apache_dir, 'mods-available', 'mime_magic.conf') do
source 'mods/mime_magic.conf.erb'
cookbook 'apache2'
variables(mime_magic_file: new_resource.mime_magic_file)
end
end
action_class do
include Apache2::Cookbook::Helpers
end
| 27.157895 | 74 | 0.753876 |
b9764c8a27b67ea1b74f284af709b1add37c91eb | 2,613 | require 'docker'
require_relative '../docker_operations'
require_relative '../build/qa'
require_relative '../build/check'
require_relative '../build/info'
require_relative '../build/gitlab_image'
require_relative '../build/qa_image'
require_relative '../build/qa_trigger'
require_relative '../build/ha_validate'
require_relative "../util.rb"
namespace :qa do
desc "Build QA Docker image"
task :build do
DockerOperations.build(
Build::QA.get_gitlab_repo,
Build::QAImage.gitlab_registry_image_address,
'latest'
)
end
namespace :push do
# Only runs on dev.gitlab.org
desc "Push unstable version of gitlab-{ce,ee}-qa to the GitLab registry"
task :staging do
Build::QAImage.tag_and_push_to_gitlab_registry(Build::Info.gitlab_version)
end
desc "Push stable version of gitlab-{ce,ee}-qa to the GitLab registry and Docker Hub"
task :stable do
# Allows to have gitlab/gitlab-{ce,ee}-qa:10.2.0-ee without the build number
Build::QAImage.tag_and_push_to_gitlab_registry(Build::Info.gitlab_version)
Build::QAImage.tag_and_push_to_dockerhub(Build::Info.gitlab_version, initial_tag: 'latest')
end
desc "Push rc version of gitlab-{ce,ee}-qa to Docker Hub"
task :rc do
if Build::Check.add_rc_tag?
Build::QAImage.tag_and_push_to_dockerhub('rc', initial_tag: 'latest')
end
end
desc "Push nightly version of gitlab-{ce,ee}-qa to Docker Hub"
task :nightly do
if Build::Check.add_nightly_tag?
Build::QAImage.tag_and_push_to_dockerhub('nightly', initial_tag: 'latest')
end
end
desc "Push latest version of gitlab-{ce,ee}-qa to Docker Hub"
task :latest do
if Build::Check.add_latest_tag?
Build::QAImage.tag_and_push_to_dockerhub('latest', initial_tag: 'latest')
end
end
desc "Push triggered version of gitlab-{ce,ee}-qa to the GitLab registry"
task :triggered do
Build::QAImage.tag_and_push_to_gitlab_registry(Gitlab::Util.get_env('IMAGE_TAG'))
end
end
desc "Run QA tests"
task :test do
image_address = Build::GitlabImage.gitlab_registry_image_address(tag: Gitlab::Util.get_env('IMAGE_TAG'))
Build::QATrigger.invoke!(image: image_address, post_comment: true).wait!
end
namespace :ha do
desc "Validate HA setup"
task :validate do
Build::HA::ValidateTrigger.invoke!.wait!
end
desc 'Validate nightly build'
task :nightly do
Build::HA::ValidateNightly.invoke!.wait!
end
desc 'Validate tagged build'
task :tag do
Build::HA::ValidateTag.invoke!
end
end
end
| 30.383721 | 108 | 0.703023 |
1af50427bd21db020379d62a44a71581654514e0 | 5,559 | ##########################GO-LICENSE-START################################
# Copyright 2014 ThoughtWorks, 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.
##########################GO-LICENSE-END##################################
class AdminController < ApplicationController
include ::Admin::ConfigContextHelper
include ::Admin::AuthorizationHelper
layout "admin"
prepend_before_action :default_as_empty_list, :only => [:update]
before_action :enable_admin_error_template
before_action :load_context
GO_CONFIG_ERROR_HEADER = 'Go-Config-Error'
protected
def save_popup(md5, save_action, render_error_options_or_proc = {:action => :new, :layout => false}, url_options = {}, flash_success_message = "Saved successfully.", &load_data)
render_error_options_or_proc.reverse_merge(:layout => false) unless render_error_options_or_proc.is_a?(Proc)
save(md5, render_error_options_or_proc, save_action, flash_success_message, load_data) do |message|
render(:plain => 'Saved successfully', :location => url_options_with_flash(message, {:action => :index, :class => 'success'}.merge(url_options)))
end
end
def set_save_redirect_url url
@onsuccess_redirect_uri = url
end
def save_page(md5, redirect_url, render_error_options_or_proc, save_action, success_message = "Saved successfully.", &load_data)
set_save_redirect_url redirect_url
save(md5, render_error_options_or_proc, save_action, success_message, load_data) do |message|
url = com.thoughtworks.go.util.UrlUtil.urlWithQuery(@onsuccess_redirect_uri, "fm", set_flash_message(message, "success"))
redirect_to(url)
end
end
protected
def render_error_with_options(options)
render(options)
end
def assert_loaded(*args)
options = args.extract_options!
successful = true
args.inject(@asserted_variables ||= {}) do |map, name|
unless (var = instance_variable_get("@#{name}"))
Rails.logger.warn("Could not load '#{name}', rendering failure #{caller[0..10].join("\n")}")
if(@should_not_render_layout)
options = options.merge(:layout => nil)
end
render_assertion_failure(options)
successful = false
end
map[name] = var
end
successful
end
def render_assertion_failure(options)
return if @error_rendered
@message = options.delete(:message) || 'Error occurred while trying to complete your request.'
@error_rendered = true
options[:status] ||= (@update_result && @update_result.httpCode()) || 404
render({:template => "shared/config_error.html", :layout => action_has_layout? ? "application" : nil}.merge(options))
false
end
def assert_load(name, value, message = nil, status = nil)
instance_variable_set("@#{name}", value)
assert_loaded(name, {:message => message, :status => status})
end
def assert_load_eval(name, message = nil, status = nil)
instance_variable_set("@#{name}", yield)
rescue
instance_variable_set("@#{name}", nil)
ensure
return assert_loaded(name, {:message => message, :status => status})
end
def flatten_all_errors(errors)
errors.collect { |e| e.getAll().to_a }.flatten.uniq
end
def render_error(result, errors, options)
@errors = flatten_all_errors(errors)
flash.now[:error] = result.message()
performed? || render_error_with_options(options.merge({:status => result.httpCode()}))
end
private
def save(md5, render_error_options_or_proc, save_action, success_message, load_data)
@update_result = HttpLocalizedOperationResult.new
update_response = go_config_service.updateConfigFromUI(save_action, md5, current_user, @update_result)
@cruise_config, @node, @subject, @config_after = update_response.getCruiseConfig(), update_response.getNode(), update_response.getSubject(), update_response.configAfterUpdate()
unless @update_result.isSuccessful()
@config_file_conflict = (@update_result.httpCode() == 409)
flash.now[:error] = @update_result.message()
response.headers[GO_CONFIG_ERROR_HEADER] = flash[:error]
end
begin
load_data.call
rescue
Rails.logger.error $!
render_assertion_failure({})
end
return if @error_rendered
if @update_result.isSuccessful()
success_message = "#{success_message} #{'The configuration was modified by someone else, but your changes were merged successfully.'}" if update_response.wasMerged()
yield success_message
else
all_errors_on_other_objects = update_response.getCruiseConfig().getAllErrorsExceptFor(@subject)
if render_error_options_or_proc.is_a?(Proc)
render_error_options_or_proc.call(@update_result, all_errors_on_other_objects)
else
render_error(@update_result, all_errors_on_other_objects, render_error_options_or_proc)
end
end
end
def enable_admin_error_template
self.error_template_for_request = 'shared/config_error'
end
def load_context
assert_load :config_context, create_config_context(go_config_service.registry)
end
end
| 38.075342 | 180 | 0.717395 |
21541ef51bf224d689998736e8eb712fe1f0bb3e | 1,530 | require 'sprockets/autoload'
module Sprockets
# Public: YUI compressor.
#
# To accept the default options
#
# environment.register_bundle_processor 'application/javascript',
# Sprockets::YUICompressor
#
# Or to pass options to the YUI::JavaScriptCompressor class.
#
# environment.register_bundle_processor 'application/javascript',
# Sprockets::YUICompressor.new(munge: true)
#
class YUICompressor
VERSION = '1'
# Public: Return singleton instance with default options.
#
# Returns YUICompressor object.
def self.instance
@instance ||= new
end
def self.call(input)
instance.call(input)
end
def self.cache_key
instance.cache_key
end
attr_reader :cache_key
def initialize(options = {})
@options = options
@cache_key = [
self.class.name,
Autoload::YUI::Compressor::VERSION,
VERSION,
options
].freeze
end
def call(input)
data = input[:data]
case input[:content_type]
when 'application/javascript'
key = @cache_key + [input[:content_type], input[:data]]
input[:cache].fetch(key) do
Autoload::YUI::JavaScriptCompressor.new(@options).compress(data)
end
when 'text/css'
key = @cache_key + [input[:content_type], input[:data]]
input[:cache].fetch(key) do
Autoload::YUI::CssCompressor.new(@options).compress(data)
end
else
data
end
end
end
end
| 23.181818 | 74 | 0.621569 |
7afbf25cd49470ccab84facd2243fc708aca2e98 | 6,186 | FactoryGirl.define do
factory :plan do
sequence(:hbx_id) { |n| n + 12345 }
sequence(:name) { |n| "BlueChoice Silver#{n} 2,000" }
abbrev "BC Silver $2k"
sequence(:hios_id, (10..99).cycle) { |n| "41842DC04000#{n}-01" }
active_year { TimeKeeper.date_of_record.year }
coverage_kind "health"
metal_level "silver"
plan_type "pos"
market "shop"
ehb 0.9943
carrier_profile { FactoryGirl.create(:carrier_profile) } #{ BSON::ObjectId.from_time(DateTime.now) }
minimum_age 19
maximum_age 66
deductible "$500"
family_deductible "$500 per person | $1000 per group"
# association :premium_tables, strategy: :build
trait :with_dental_coverage do
coverage_kind "dental"
metal_level "dental"
dental_level "high"
end
trait :with_premium_tables do
transient do
premium_tables_count 48
end
after(:create) do |plan, evaluator|
start_on = Date.new(plan.active_year,1,1)
end_on = start_on + 1.year - 1.day
create_list(:premium_table, evaluator.premium_tables_count, plan: plan, start_on: start_on, end_on: end_on)
end
end
trait :csr_00 do
coverage_kind "health"
metal_level "silver"
market "individual"
csr_variant_id "00"
end
trait :csr_87 do
coverage_kind "health"
metal_level "silver"
market "individual"
csr_variant_id "87"
end
trait :catastrophic do
coverage_kind "health"
metal_level "catastrophic"
market "individual"
end
trait :individual_health do
coverage_kind "health"
market "individual"
end
trait :individual_dental do
coverage_kind "dental"
market "individual"
metal_level "low"
end
trait :shop_health do
coverage_kind "health"
market "shop"
end
trait :shop_dental do
coverage_kind "dental"
market "shop"
metal_level "high"
end
trait :this_year do
active_year Time.now.year
end
trait :next_year do
active_year Time.now.year
end
trait :premiums_for_2015 do
transient do
premium_tables_count 48
end
after :create do |plan, evaluator|
create_list(:premium_table, evaluator.premium_tables_count, plan: plan, start_on: Date.new(2015,1,1))
end
end
trait :with_next_year_premium_tables do
transient do
next_year_premium_tables_count 48
end
active_year {TimeKeeper.date_of_record.next_year.year}
after(:create) do |plan, evaluator|
create_list(:next_year_premium_table, evaluator.next_year_premium_tables_count, plan: plan)
end
end
factory :active_individual_health_plan, traits: [:individual_health, :this_year, :with_premium_tables]
factory :active_shop_health_plan, traits: [:shop_health, :this_year, :with_premium_tables]
factory :active_individual_dental_plan, traits: [:individual_dental, :this_year, :with_premium_tables]
factory :active_individual_catastophic_plan, traits: [:catastrophic, :this_year, :with_premium_tables]
factory :active_csr_87_plan, traits: [:csr_87, :this_year, :with_premium_tables]
factory :active_csr_00_plan, traits: [:csr_00, :this_year, :with_premium_tables]
factory :renewal_individual_health_plan, traits: [:individual_health, :next_year, :with_premium_tables]
factory :renewal_shop_health_plan, traits: [:shop_health, :next_year, :with_premium_tables]
factory :renewal_individual_dental_plan, traits: [:individual_dental, :next_year, :with_premium_tables]
factory :renewal_individual_catastophic_plan, traits: [:catastrophic, :next_year, :with_premium_tables]
factory :renewal_csr_87_plan, traits: [:csr_87, :next_year, :with_premium_tables]
factory :renewal_csr_00_plan, traits: [:csr_00, :next_year, :with_premium_tables]
end
factory :premium_table do
sequence(:age, (19..66).cycle)
start_on TimeKeeper.date_of_record.beginning_of_year
end_on TimeKeeper.date_of_record.beginning_of_year.next_year - 1.day
cost {(age * 1001.00) / 100.00}
after :create do |pt|
metal_hash = {
bronze: 110.00,
silver: 100.00,
gold: 90.00,
platinum: 80.00,
dental: 10.00,
}
pt.update_attribute(:cost, (pt.age * 1001.00) / metal_hash[:"#{pt.plan.metal_level}"] )
end
end
factory(:next_year_premium_table, {class: PremiumTable}) do
sequence(:age, (19..66).cycle)
start_on {TimeKeeper.date_of_record.beginning_of_year.next_year}
end_on {TimeKeeper.date_of_record.beginning_of_year.next_year + 1.year - 1.day}
cost {(age * 1001.00) / 100.00}
after :create do |pt|
metal_hash = {
bronze: 110.00,
silver: 100.00,
gold: 90.00,
platinum: 80.00,
dental: 10.00,
}
pt.update_attribute(:cost, (pt.age * 1500.50) / (metal_hash[:"#{pt.plan.metal_level}"] || 110.0) )
end
end
end
FactoryGirl.define do
factory(:plan_template, {class: Plan}) do
name "Some plan name"
carrier_profile_id { BSON::ObjectId.new }
sequence(:hios_id, (100000..999999).cycle) { |n| "#{n}-01" }
active_year Date.today.year
metal_level { ["bronze","silver","gold","platinum"].shuffle.sample }
trait :shop_health do
market "shop"
coverage_kind "health"
end
trait :ivl_health do
market "individual"
coverage_kind "health"
end
trait :shop_dental do
market "shop"
coverage_kind "dental"
metal_level "dental"
dental_level "high"
end
trait :ivl_dental do
market "individual"
coverage_kind "dental"
metal_level "dental"
dental_level "high"
end
trait :unoffered do
sequence(:hios_id, (100000..999999).cycle) { |n| "#{n}-00" }
end
end
end
| 31.242424 | 115 | 0.634012 |
4a6e31e1a4fb82e068efd46bff05a5ddbffb09ba | 743 | Pod::Spec.new do |s|
s.name = "ExytePopupView"
s.version = "1.0.1"
s.summary = "SwiftUI library for toasts and popups"
s.homepage = 'https://github.com/exyte/PopupView.git'
s.license = 'MIT'
s.author = { 'Exyte' => '[email protected]' }
s.source = { :git => 'https://github.com/exyte/PopupView.git', :tag => s.version.to_s }
s.social_media_url = 'http://exyte.com'
s.ios.deployment_target = '13.0'
s.osx.deployment_target = '10.15'
s.tvos.deployment_target = '13.0'
s.watchos.deployment_target = '6.0'
s.requires_arc = true
s.swift_version = "5.2"
s.source_files = [
'Source/*.h',
'Source/*.swift',
'Source/**/*.swift'
]
end
| 27.518519 | 99 | 0.567968 |
ac85efb61b38e698eaa972d2b86382bc86c2c7f6 | 110 | require 'terminal-table'
require 'percheron/formatters/stack'
module Percheron
module Formatters
end
end
| 13.75 | 36 | 0.8 |
1dfbd8e3419fbee2abd0da968b7c796f71288bd4 | 66,640 | # 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'
module Google
module Apis
module NotebooksV1
# Notebooks API
#
# AI Platform Notebooks API is used to manage notebook resources in Google Cloud.
#
# @example
# require 'google/apis/notebooks_v1'
#
# Notebooks = Google::Apis::NotebooksV1 # Alias the module
# service = Notebooks::AIPlatformNotebooksService.new
#
# @see https://cloud.google.com/ai-platform/notebooks/docs/
class AIPlatformNotebooksService < Google::Apis::Core::BaseService
# @return [String]
# API key. Your API key identifies your project and provides you with API access,
# quota, and reports. Required unless you provide an OAuth 2.0 token.
attr_accessor :key
# @return [String]
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
attr_accessor :quota_user
def initialize
super('https://notebooks.googleapis.com/', '',
client_name: 'google-apis-notebooks_v1',
client_version: Google::Apis::NotebooksV1::GEM_VERSION)
@batch_path = 'batch'
end
# Gets information about a location.
# @param [String] name
# Resource name for the location.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::Location] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::Location]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_project_location(name, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/{+name}', options)
command.response_representation = Google::Apis::NotebooksV1::Location::Representation
command.response_class = Google::Apis::NotebooksV1::Location
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists information about the supported locations for this service.
# @param [String] name
# The resource that owns the locations collection, if applicable.
# @param [String] filter
# The standard list filter.
# @param [Fixnum] page_size
# The standard list page size.
# @param [String] page_token
# The standard list page token.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::ListLocationsResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::ListLocationsResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_project_locations(name, filter: nil, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/{+name}/locations', options)
command.response_representation = Google::Apis::NotebooksV1::ListLocationsResponse::Representation
command.response_class = Google::Apis::NotebooksV1::ListLocationsResponse
command.params['name'] = name unless name.nil?
command.query['filter'] = filter unless filter.nil?
command.query['pageSize'] = page_size unless page_size.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Creates a new Environment.
# @param [String] parent
# Required. Format: `projects/`project_id`/locations/`location``
# @param [Google::Apis::NotebooksV1::Environment] environment_object
# @param [String] environment_id
# Required. User-defined unique ID of this environment. The `environment_id`
# must be 1 to 63 characters long and contain only lowercase letters, numeric
# characters, and dashes. The first character must be a lowercase letter and the
# last character cannot be a dash.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def create_project_location_environment(parent, environment_object = nil, environment_id: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/{+parent}/environments', options)
command.request_representation = Google::Apis::NotebooksV1::Environment::Representation
command.request_object = environment_object
command.response_representation = Google::Apis::NotebooksV1::Operation::Representation
command.response_class = Google::Apis::NotebooksV1::Operation
command.params['parent'] = parent unless parent.nil?
command.query['environmentId'] = environment_id unless environment_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Deletes a single Environment.
# @param [String] name
# Required. Format: `projects/`project_id`/locations/`location`/environments/`
# environment_id``
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def delete_project_location_environment(name, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:delete, 'v1/{+name}', options)
command.response_representation = Google::Apis::NotebooksV1::Operation::Representation
command.response_class = Google::Apis::NotebooksV1::Operation
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Gets details of a single Environment.
# @param [String] name
# Required. Format: `projects/`project_id`/locations/`location`/environments/`
# environment_id``
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::Environment] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::Environment]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_project_location_environment(name, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/{+name}', options)
command.response_representation = Google::Apis::NotebooksV1::Environment::Representation
command.response_class = Google::Apis::NotebooksV1::Environment
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists environments in a project.
# @param [String] parent
# Required. Format: `projects/`project_id`/locations/`location``
# @param [Fixnum] page_size
# Maximum return size of the list call.
# @param [String] page_token
# A previous returned page token that can be used to continue listing from the
# last result.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::ListEnvironmentsResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::ListEnvironmentsResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_project_location_environments(parent, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/{+parent}/environments', options)
command.response_representation = Google::Apis::NotebooksV1::ListEnvironmentsResponse::Representation
command.response_class = Google::Apis::NotebooksV1::ListEnvironmentsResponse
command.params['parent'] = parent unless parent.nil?
command.query['pageSize'] = page_size unless page_size.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Creates a new Instance in a given project and location.
# @param [String] parent
# Required. Format: `parent=projects/`project_id`/locations/`location``
# @param [Google::Apis::NotebooksV1::Instance] instance_object
# @param [String] instance_id
# Required. User-defined unique ID of this instance.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def create_project_location_instance(parent, instance_object = nil, instance_id: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/{+parent}/instances', options)
command.request_representation = Google::Apis::NotebooksV1::Instance::Representation
command.request_object = instance_object
command.response_representation = Google::Apis::NotebooksV1::Operation::Representation
command.response_class = Google::Apis::NotebooksV1::Operation
command.params['parent'] = parent unless parent.nil?
command.query['instanceId'] = instance_id unless instance_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Deletes a single Instance.
# @param [String] name
# Required. Format: `projects/`project_id`/locations/`location`/instances/`
# instance_id``
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def delete_project_location_instance(name, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:delete, 'v1/{+name}', options)
command.response_representation = Google::Apis::NotebooksV1::Operation::Representation
command.response_class = Google::Apis::NotebooksV1::Operation
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Gets details of a single Instance.
# @param [String] name
# Required. Format: `projects/`project_id`/locations/`location`/instances/`
# instance_id``
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::Instance] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::Instance]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_project_location_instance(name, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/{+name}', options)
command.response_representation = Google::Apis::NotebooksV1::Instance::Representation
command.response_class = Google::Apis::NotebooksV1::Instance
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Gets the access control policy for a resource. Returns an empty policy if the
# resource exists and does not have a policy set.
# @param [String] resource
# REQUIRED: The resource for which the policy is being requested. See the
# operation documentation for the appropriate value for this field.
# @param [Fixnum] options_requested_policy_version
# Optional. The policy format version to be returned. Valid values are 0, 1, and
# 3. Requests specifying an invalid value will be rejected. Requests for
# policies with any conditional bindings must specify version 3. Policies
# without any conditional bindings may specify any valid value or leave the
# field unset. To learn which resources support conditions in their IAM policies,
# see the [IAM documentation](https://cloud.google.com/iam/help/conditions/
# resource-policies).
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::Policy] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::Policy]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_project_location_instance_iam_policy(resource, options_requested_policy_version: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/{+resource}:getIamPolicy', options)
command.response_representation = Google::Apis::NotebooksV1::Policy::Representation
command.response_class = Google::Apis::NotebooksV1::Policy
command.params['resource'] = resource unless resource.nil?
command.query['options.requestedPolicyVersion'] = options_requested_policy_version unless options_requested_policy_version.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Check if a notebook instance is upgradable.
# @param [String] notebook_instance
# Required. Format: `projects/`project_id`/locations/`location`/instances/`
# instance_id``
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::IsInstanceUpgradeableResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::IsInstanceUpgradeableResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def is_project_location_instance_upgradeable(notebook_instance, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/{+notebookInstance}:isUpgradeable', options)
command.response_representation = Google::Apis::NotebooksV1::IsInstanceUpgradeableResponse::Representation
command.response_class = Google::Apis::NotebooksV1::IsInstanceUpgradeableResponse
command.params['notebookInstance'] = notebook_instance unless notebook_instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists instances in a given project and location.
# @param [String] parent
# Required. Format: `parent=projects/`project_id`/locations/`location``
# @param [Fixnum] page_size
# Maximum return size of the list call.
# @param [String] page_token
# A previous returned page token that can be used to continue listing from the
# last result.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::ListInstancesResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::ListInstancesResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_project_location_instances(parent, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/{+parent}/instances', options)
command.response_representation = Google::Apis::NotebooksV1::ListInstancesResponse::Representation
command.response_class = Google::Apis::NotebooksV1::ListInstancesResponse
command.params['parent'] = parent unless parent.nil?
command.query['pageSize'] = page_size unless page_size.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Registers an existing legacy notebook instance to the Notebooks API server.
# Legacy instances are instances created with the legacy Compute Engine calls.
# They are not manageable by the Notebooks API out of the box. This call makes
# these instances manageable by the Notebooks API.
# @param [String] parent
# Required. Format: `parent=projects/`project_id`/locations/`location``
# @param [Google::Apis::NotebooksV1::RegisterInstanceRequest] register_instance_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def register_instance(parent, register_instance_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/{+parent}/instances:register', options)
command.request_representation = Google::Apis::NotebooksV1::RegisterInstanceRequest::Representation
command.request_object = register_instance_request_object
command.response_representation = Google::Apis::NotebooksV1::Operation::Representation
command.response_class = Google::Apis::NotebooksV1::Operation
command.params['parent'] = parent unless parent.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Allows notebook instances to report their latest instance information to the
# Notebooks API server. The server will merge the reported information to the
# instance metadata store. Do not use this method directly.
# @param [String] name
# Required. Format: `projects/`project_id`/locations/`location`/instances/`
# instance_id``
# @param [Google::Apis::NotebooksV1::ReportInstanceInfoRequest] report_instance_info_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def report_instance_info(name, report_instance_info_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/{+name}:report', options)
command.request_representation = Google::Apis::NotebooksV1::ReportInstanceInfoRequest::Representation
command.request_object = report_instance_info_request_object
command.response_representation = Google::Apis::NotebooksV1::Operation::Representation
command.response_class = Google::Apis::NotebooksV1::Operation
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Resets a notebook instance.
# @param [String] name
# Required. Format: `projects/`project_id`/locations/`location`/instances/`
# instance_id``
# @param [Google::Apis::NotebooksV1::ResetInstanceRequest] reset_instance_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def reset_instance(name, reset_instance_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/{+name}:reset', options)
command.request_representation = Google::Apis::NotebooksV1::ResetInstanceRequest::Representation
command.request_object = reset_instance_request_object
command.response_representation = Google::Apis::NotebooksV1::Operation::Representation
command.response_class = Google::Apis::NotebooksV1::Operation
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Updates the guest accelerators of a single Instance.
# @param [String] name
# Required. Format: `projects/`project_id`/locations/`location`/instances/`
# instance_id``
# @param [Google::Apis::NotebooksV1::SetInstanceAcceleratorRequest] set_instance_accelerator_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def set_project_location_instance_accelerator(name, set_instance_accelerator_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:patch, 'v1/{+name}:setAccelerator', options)
command.request_representation = Google::Apis::NotebooksV1::SetInstanceAcceleratorRequest::Representation
command.request_object = set_instance_accelerator_request_object
command.response_representation = Google::Apis::NotebooksV1::Operation::Representation
command.response_class = Google::Apis::NotebooksV1::Operation
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Sets the access control policy on the specified resource. Replaces any
# existing policy. Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `
# PERMISSION_DENIED` errors.
# @param [String] resource
# REQUIRED: The resource for which the policy is being specified. See the
# operation documentation for the appropriate value for this field.
# @param [Google::Apis::NotebooksV1::SetIamPolicyRequest] set_iam_policy_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::Policy] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::Policy]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def set_instance_iam_policy(resource, set_iam_policy_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/{+resource}:setIamPolicy', options)
command.request_representation = Google::Apis::NotebooksV1::SetIamPolicyRequest::Representation
command.request_object = set_iam_policy_request_object
command.response_representation = Google::Apis::NotebooksV1::Policy::Representation
command.response_class = Google::Apis::NotebooksV1::Policy
command.params['resource'] = resource unless resource.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Replaces all the labels of an Instance.
# @param [String] name
# Required. Format: `projects/`project_id`/locations/`location`/instances/`
# instance_id``
# @param [Google::Apis::NotebooksV1::SetInstanceLabelsRequest] set_instance_labels_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def set_project_location_instance_labels(name, set_instance_labels_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:patch, 'v1/{+name}:setLabels', options)
command.request_representation = Google::Apis::NotebooksV1::SetInstanceLabelsRequest::Representation
command.request_object = set_instance_labels_request_object
command.response_representation = Google::Apis::NotebooksV1::Operation::Representation
command.response_class = Google::Apis::NotebooksV1::Operation
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Updates the machine type of a single Instance.
# @param [String] name
# Required. Format: `projects/`project_id`/locations/`location`/instances/`
# instance_id``
# @param [Google::Apis::NotebooksV1::SetInstanceMachineTypeRequest] set_instance_machine_type_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def set_project_location_instance_machine_type(name, set_instance_machine_type_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:patch, 'v1/{+name}:setMachineType', options)
command.request_representation = Google::Apis::NotebooksV1::SetInstanceMachineTypeRequest::Representation
command.request_object = set_instance_machine_type_request_object
command.response_representation = Google::Apis::NotebooksV1::Operation::Representation
command.response_class = Google::Apis::NotebooksV1::Operation
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Starts a notebook instance.
# @param [String] name
# Required. Format: `projects/`project_id`/locations/`location`/instances/`
# instance_id``
# @param [Google::Apis::NotebooksV1::StartInstanceRequest] start_instance_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def start_instance(name, start_instance_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/{+name}:start', options)
command.request_representation = Google::Apis::NotebooksV1::StartInstanceRequest::Representation
command.request_object = start_instance_request_object
command.response_representation = Google::Apis::NotebooksV1::Operation::Representation
command.response_class = Google::Apis::NotebooksV1::Operation
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Stops a notebook instance.
# @param [String] name
# Required. Format: `projects/`project_id`/locations/`location`/instances/`
# instance_id``
# @param [Google::Apis::NotebooksV1::StopInstanceRequest] stop_instance_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def stop_instance(name, stop_instance_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/{+name}:stop', options)
command.request_representation = Google::Apis::NotebooksV1::StopInstanceRequest::Representation
command.request_object = stop_instance_request_object
command.response_representation = Google::Apis::NotebooksV1::Operation::Representation
command.response_class = Google::Apis::NotebooksV1::Operation
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Returns permissions that a caller has on the specified resource. If the
# resource does not exist, this will return an empty set of permissions, not a `
# NOT_FOUND` error. Note: This operation is designed to be used for building
# permission-aware UIs and command-line tools, not for authorization checking.
# This operation may "fail open" without warning.
# @param [String] resource
# REQUIRED: The resource for which the policy detail is being requested. See the
# operation documentation for the appropriate value for this field.
# @param [Google::Apis::NotebooksV1::TestIamPermissionsRequest] test_iam_permissions_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::TestIamPermissionsResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::TestIamPermissionsResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def test_instance_iam_permissions(resource, test_iam_permissions_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/{+resource}:testIamPermissions', options)
command.request_representation = Google::Apis::NotebooksV1::TestIamPermissionsRequest::Representation
command.request_object = test_iam_permissions_request_object
command.response_representation = Google::Apis::NotebooksV1::TestIamPermissionsResponse::Representation
command.response_class = Google::Apis::NotebooksV1::TestIamPermissionsResponse
command.params['resource'] = resource unless resource.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Upgrades a notebook instance to the latest version.
# @param [String] name
# Required. Format: `projects/`project_id`/locations/`location`/instances/`
# instance_id``
# @param [Google::Apis::NotebooksV1::UpgradeInstanceRequest] upgrade_instance_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def upgrade_instance(name, upgrade_instance_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/{+name}:upgrade', options)
command.request_representation = Google::Apis::NotebooksV1::UpgradeInstanceRequest::Representation
command.request_object = upgrade_instance_request_object
command.response_representation = Google::Apis::NotebooksV1::Operation::Representation
command.response_class = Google::Apis::NotebooksV1::Operation
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Allows notebook instances to call this endpoint to upgrade themselves. Do not
# use this method directly.
# @param [String] name
# Required. Format: `projects/`project_id`/locations/`location`/instances/`
# instance_id``
# @param [Google::Apis::NotebooksV1::UpgradeInstanceInternalRequest] upgrade_instance_internal_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def upgrade_project_location_instance_internal(name, upgrade_instance_internal_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/{+name}:upgradeInternal', options)
command.request_representation = Google::Apis::NotebooksV1::UpgradeInstanceInternalRequest::Representation
command.request_object = upgrade_instance_internal_request_object
command.response_representation = Google::Apis::NotebooksV1::Operation::Representation
command.response_class = Google::Apis::NotebooksV1::Operation
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Starts asynchronous cancellation on a long-running operation. The server makes
# a best effort to cancel the operation, but success is not guaranteed. If the
# server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`.
# Clients can use Operations.GetOperation or other methods to check whether the
# cancellation succeeded or whether the operation completed despite cancellation.
# On successful cancellation, the operation is not deleted; instead, it becomes
# an operation with an Operation.error value with a google.rpc.Status.code of 1,
# corresponding to `Code.CANCELLED`.
# @param [String] name
# The name of the operation resource to be cancelled.
# @param [Google::Apis::NotebooksV1::CancelOperationRequest] cancel_operation_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::Empty] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::Empty]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def cancel_operation(name, cancel_operation_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/{+name}:cancel', options)
command.request_representation = Google::Apis::NotebooksV1::CancelOperationRequest::Representation
command.request_object = cancel_operation_request_object
command.response_representation = Google::Apis::NotebooksV1::Empty::Representation
command.response_class = Google::Apis::NotebooksV1::Empty
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Deletes a long-running operation. This method indicates that the client is no
# longer interested in the operation result. It does not cancel the operation.
# If the server doesn't support this method, it returns `google.rpc.Code.
# UNIMPLEMENTED`.
# @param [String] name
# The name of the operation resource to be deleted.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::Empty] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::Empty]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def delete_project_location_operation(name, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:delete, 'v1/{+name}', options)
command.response_representation = Google::Apis::NotebooksV1::Empty::Representation
command.response_class = Google::Apis::NotebooksV1::Empty
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Gets the latest state of a long-running operation. Clients can use this method
# to poll the operation result at intervals as recommended by the API service.
# @param [String] name
# The name of the operation resource.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_project_location_operation(name, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/{+name}', options)
command.response_representation = Google::Apis::NotebooksV1::Operation::Representation
command.response_class = Google::Apis::NotebooksV1::Operation
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists operations that match the specified filter in the request. If the server
# doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name`
# binding allows API services to override the binding to use different resource
# name schemes, such as `users/*/operations`. To override the binding, API
# services can add a binding such as `"/v1/`name=users/*`/operations"` to their
# service configuration. For backwards compatibility, the default name includes
# the operations collection id, however overriding users must ensure the name
# binding is the parent resource, without the operations collection id.
# @param [String] name
# The name of the operation's parent resource.
# @param [String] filter
# The standard list filter.
# @param [Fixnum] page_size
# The standard list page size.
# @param [String] page_token
# The standard list page token.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::ListOperationsResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::ListOperationsResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_project_location_operations(name, filter: nil, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/{+name}/operations', options)
command.response_representation = Google::Apis::NotebooksV1::ListOperationsResponse::Representation
command.response_class = Google::Apis::NotebooksV1::ListOperationsResponse
command.params['name'] = name unless name.nil?
command.query['filter'] = filter unless filter.nil?
command.query['pageSize'] = page_size unless page_size.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Triggers execution of an existing schedule.
# @param [String] name
# Required. Format: `parent=projects/`project_id`/locations/`location`/schedules/
# `schedule_id``
# @param [Google::Apis::NotebooksV1::TriggerScheduleRequest] trigger_schedule_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::NotebooksV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::NotebooksV1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def trigger_schedule(name, trigger_schedule_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/{+name}:trigger', options)
command.request_representation = Google::Apis::NotebooksV1::TriggerScheduleRequest::Representation
command.request_object = trigger_schedule_request_object
command.response_representation = Google::Apis::NotebooksV1::Operation::Representation
command.response_class = Google::Apis::NotebooksV1::Operation
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
protected
def apply_command_defaults(command)
command.query['key'] = key unless key.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
end
end
end
end
end
| 61.76089 | 160 | 0.677506 |
f7f10808705de7a83aed9574f62f5ae8586af361 | 337 | class CreateComments < ActiveRecord::Migration[6.0]
def change
create_table :comments do |t|
t.text :body
t.references :commented_ticket, references: :tickets, foreign_key: { to_table: :tickets }
t.references :commenter, references: :users, foreign_key: { to_table: :users }
t.timestamps
end
end
end
| 28.083333 | 95 | 0.688427 |
8772b398b6d972acdafff9b1793c022845b5510c | 1,382 | # frozen_string_literal: true
class DeviseCreateAdmins < ActiveRecord::Migration[6.1]
def change
create_table :admins do |t|
## Database authenticatable
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
t.string :confirmation_token
t.datetime :confirmed_at
t.datetime :confirmation_sent_at
t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
t.string :unlock_token # Only if unlock strategy is :email or :both
t.datetime :locked_at
t.timestamps null: false
end
add_index :admins, :email, unique: true
add_index :admins, :reset_password_token, unique: true
# add_index :admins, :confirmation_token, unique: true
# add_index :admins, :unlock_token, unique: true
end
end
| 31.409091 | 102 | 0.664255 |
ffd31f8d7b73e1bd842706cd32351f2ee19117fb | 2,349 | # frozen_string_literal: true
module QA
module Page
module Component
module Wiki
extend QA::Page::PageConcern
def self.included(base)
super
base.view 'app/views/shared/wikis/show.html.haml' do
element :wiki_page_title
element :edit_page_button
end
base.view 'app/views/shared/wikis/_wiki_content.html.haml' do
element :wiki_page_content
end
base.view 'app/views/shared/wikis/_main_links.html.haml' do
element :new_page_button
element :page_history_button
end
base.view 'app/views/shared/empty_states/_wikis.html.haml' do
element :create_first_page_link
end
base.view 'app/views/shared/empty_states/_wikis_layout.html.haml' do
element :svg_content
end
end
def click_create_your_first_page
# The svg takes a fraction of a second to load after which the
# "Create your first page" button shifts up a bit. This can cause
# webdriver to miss the hit so we wait for the svg to load before
# clicking the button.
within_element(:svg_content) do
has_element?(:js_lazy_loaded)
end
click_element(:create_first_page_link)
end
def click_new_page
click_element(:new_page_button)
end
def click_page_history
click_element(:page_history_button)
end
def click_edit
click_element(:edit_page_button)
end
def has_title?(title)
has_element?(:wiki_page_title, title)
end
def has_content?(content)
has_element?(:wiki_page_content, content)
end
def has_no_content?(content)
has_no_element?(:wiki_page_content, content)
end
def has_no_page?
has_element?(:create_first_page_link)
end
def has_heading?(heading_type, text)
within_element(:wiki_page_content) do
has_css?(heading_type, text: text)
end
end
def has_image?(image_file_name)
within_element(:wiki_page_content) do
has_css?("img[src$='#{image_file_name}']")
end
end
end
end
end
end
| 26.1 | 78 | 0.598978 |
870cc443815abc7871eb9ecc76615167694ee850 | 550 | module OpenBD
class Contributor
attr_reader :source
ROLE_MAP = {
"A01" => "著者",
"B06" => "翻訳者"
}.freeze
def initialize(source)
@source = source
end
def description
source.dig("BiographicalNote")
end
def kana_name
source.dig("PersonName", "collationkey")
end
def name
source.dig("PersonName", "content")
end
def role
roles.first
end
def roles
source.dig("ContributorRole").map do |role|
ROLE_MAP[role]
end
end
end
end
| 14.864865 | 49 | 0.569091 |
1a93e41bca01e2e35c5ce7a897ec0b2a605ee55a | 7,939 | =begin
#The Plaid API
#The Plaid REST API. Please see https://plaid.com/docs/api for more details.
The version of the OpenAPI document: 2020-09-14_1.64.13
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.1.0
=end
require 'date'
require 'time'
module Plaid
# An optional object to filter `/accounts/balance/get` results.
class AccountsBalanceGetRequestOptions
# A list of `account_ids` to retrieve for the Item. The default value is `null`. Note: An error will be returned if a provided `account_id` is not associated with the Item.
attr_accessor :account_ids
# Timestamp in [ISO 8601](https://wikipedia.org/wiki/ISO_8601) format (`YYYY-MM-DDTHH:mm:ssZ`) indicating the oldest acceptable balance when making a request to `/accounts/balance/get`. If the balance that is pulled for `ins_128026` (Capital One) is older than the given timestamp, an `INVALID_REQUEST` error with the code of `LAST_UPDATED_DATETIME_OUT_OF_RANGE` will be returned with the most recent timestamp for the requested account contained in the response. This field is only used when the institution is `ins_128026` (Capital One), in which case a value must be provided or an `INVALID_REQUEST` error with the code of `INVALID_FIELD` will be returned. For all other institutions, this field is ignored.
attr_accessor :min_last_updated_datetime
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'account_ids' => :'account_ids',
:'min_last_updated_datetime' => :'min_last_updated_datetime'
}
end
# Returns all the JSON keys this model knows about
def self.acceptable_attributes
attribute_map.values
end
# Attribute type mapping.
def self.openapi_types
{
:'account_ids' => :'Array<String>',
:'min_last_updated_datetime' => :'Time'
}
end
# List of attributes with nullable: true
def self.openapi_nullable
Set.new([
])
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `Plaid::AccountsBalanceGetRequestOptions` initialize method"
end
# check to see if the attribute exists and convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h|
if (!self.class.attribute_map.key?(k.to_sym))
fail ArgumentError, "`#{k}` is not a valid attribute in `Plaid::AccountsBalanceGetRequestOptions`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
end
h[k.to_sym] = v
}
if attributes.key?(:'account_ids')
if (value = attributes[:'account_ids']).is_a?(Array)
self.account_ids = value
end
end
if attributes.key?(:'min_last_updated_datetime')
self.min_last_updated_datetime = attributes[:'min_last_updated_datetime']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
account_ids == o.account_ids &&
min_last_updated_datetime == o.min_last_updated_datetime
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
def hash
[account_ids, min_last_updated_datetime].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def self.build_from_hash(attributes)
new.build_from_hash(attributes)
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.openapi_types.each_pair do |key, type|
if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key)
self.send("#{key}=", nil)
elsif type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :Time
Time.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :Boolean
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
# models (e.g. Pet) or oneOf
klass = Plaid.const_get(type)
klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
if value.nil?
is_nullable = self.class.openapi_nullable.include?(attr)
next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
end
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 34.072961 | 716 | 0.649956 |
91a0cf51d78704d5c72580dd4f6739da91fe493a | 41,043 | require 'adwords4r/v201003/BidLandscapeService'
require 'soap/mapping'
module AdWords; module V201003; module BidLandscapeService
module DefaultMappingRegistry
EncodedRegistry = ::SOAP::Mapping::EncodedRegistry.new
LiteralRegistry = ::SOAP::Mapping::LiteralRegistry.new
NsV201003 = "https://adwords.google.com/api/adwords/cm/v201003"
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::AuthenticationError,
:schema_type => XSD::QName.new(NsV201003, "AuthenticationError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::AuthenticationErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::AuthorizationError,
:schema_type => XSD::QName.new(NsV201003, "AuthorizationError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::AuthorizationErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::BidLandscapeIdFilter,
:schema_type => XSD::QName.new(NsV201003, "BidLandscapeIdFilter"),
:schema_element => [
["campaignId", "SOAP::SOAPLong", [0, 1]],
["adGroupId", "SOAP::SOAPLong", [0, 1]],
["criterionId", "SOAP::SOAPLong", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::BidLandscapeServiceError,
:schema_type => XSD::QName.new(NsV201003, "BidLandscapeServiceError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::BidLandscapeServiceErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::ClientTermsError,
:schema_type => XSD::QName.new(NsV201003, "ClientTermsError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::ClientTermsErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::CriterionBidLandscape,
:schema_type => XSD::QName.new(NsV201003, "CriterionBidLandscape"),
:schema_basetype => XSD::QName.new(NsV201003, "BidLandscape"),
:schema_element => [
["campaignId", "SOAP::SOAPLong", [0, 1]],
["adGroupId", "SOAP::SOAPLong", [0, 1]],
["startDate", "SOAP::SOAPString", [0, 1]],
["endDate", "SOAP::SOAPString", [0, 1]],
["landscapePoints", "AdWords::V201003::BidLandscapeService::BidLandscapeLandscapePoint[]", [0, nil]],
["bidLandscape_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "BidLandscape.Type")], [0, 1]],
["criterionId", "SOAP::SOAPLong", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::CriterionBidLandscapeSelector,
:schema_type => XSD::QName.new(NsV201003, "CriterionBidLandscapeSelector"),
:schema_basetype => XSD::QName.new(NsV201003, "BidLandscapeSelector"),
:schema_element => [
["idFilters", "AdWords::V201003::BidLandscapeService::BidLandscapeIdFilter[]", [0, nil]],
["bidLandscapeSelector_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "BidLandscapeSelector.Type")], [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::DoubleValue,
:schema_type => XSD::QName.new(NsV201003, "DoubleValue"),
:schema_basetype => XSD::QName.new(NsV201003, "NumberValue"),
:schema_element => [
["comparableValue_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ComparableValue.Type")], [0, 1]],
["number", "SOAP::SOAPDouble", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::InternalApiError,
:schema_type => XSD::QName.new(NsV201003, "InternalApiError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::InternalApiErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::LongValue,
:schema_type => XSD::QName.new(NsV201003, "LongValue"),
:schema_basetype => XSD::QName.new(NsV201003, "NumberValue"),
:schema_element => [
["comparableValue_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ComparableValue.Type")], [0, 1]],
["number", "SOAP::SOAPLong", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::Money,
:schema_type => XSD::QName.new(NsV201003, "Money"),
:schema_basetype => XSD::QName.new(NsV201003, "ComparableValue"),
:schema_element => [
["comparableValue_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ComparableValue.Type")], [0, 1]],
["microAmount", "SOAP::SOAPLong", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::NotEmptyError,
:schema_type => XSD::QName.new(NsV201003, "NotEmptyError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::NotEmptyErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::NotWhitelistedError,
:schema_type => XSD::QName.new(NsV201003, "NotWhitelistedError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::NotWhitelistedErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::NullError,
:schema_type => XSD::QName.new(NsV201003, "NullError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::NullErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::OperationAccessDenied,
:schema_type => XSD::QName.new(NsV201003, "OperationAccessDenied"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::OperationAccessDeniedReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::OperatorError,
:schema_type => XSD::QName.new(NsV201003, "OperatorError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::OperatorErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::QuotaCheckError,
:schema_type => XSD::QName.new(NsV201003, "QuotaCheckError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::QuotaCheckErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::C_RangeError,
:schema_type => XSD::QName.new(NsV201003, "RangeError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::RangeErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::RateExceededError,
:schema_type => XSD::QName.new(NsV201003, "RateExceededError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::RateExceededErrorReason", [0, 1]],
["rateName", "SOAP::SOAPString", [0, 1]],
["rateScope", "SOAP::SOAPString", [0, 1]],
["retryAfterSeconds", "SOAP::SOAPInt", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::ReadOnlyError,
:schema_type => XSD::QName.new(NsV201003, "ReadOnlyError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::ReadOnlyErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::RequestError,
:schema_type => XSD::QName.new(NsV201003, "RequestError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::RequestErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::RequiredError,
:schema_type => XSD::QName.new(NsV201003, "RequiredError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::RequiredErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::SizeLimitError,
:schema_type => XSD::QName.new(NsV201003, "SizeLimitError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::SizeLimitErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::SoapHeader,
:schema_type => XSD::QName.new(NsV201003, "SoapHeader"),
:schema_element => [
["authToken", "SOAP::SOAPString", [0, 1]],
["clientCustomerId", "SOAP::SOAPString", [0, 1]],
["clientEmail", "SOAP::SOAPString", [0, 1]],
["developerToken", "SOAP::SOAPString", [0, 1]],
["userAgent", "SOAP::SOAPString", [0, 1]],
["validateOnly", "SOAP::SOAPBoolean", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::SoapResponseHeader,
:schema_type => XSD::QName.new(NsV201003, "SoapResponseHeader"),
:schema_element => [
["requestId", "SOAP::SOAPString", [0, 1]],
["operations", "SOAP::SOAPLong", [0, 1]],
["responseTime", "SOAP::SOAPLong", [0, 1]],
["units", "SOAP::SOAPLong", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::DatabaseError,
:schema_type => XSD::QName.new(NsV201003, "DatabaseError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::DatabaseErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::ApiException,
:schema_type => XSD::QName.new(NsV201003, "ApiException"),
:schema_basetype => XSD::QName.new(NsV201003, "ApplicationException"),
:schema_element => [
["message", "SOAP::SOAPString", [0, 1]],
["applicationException_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApplicationException.Type")], [0, 1]],
["errors", "AdWords::V201003::BidLandscapeService::ApiError[]", [0, nil]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::ApplicationException,
:schema_type => XSD::QName.new(NsV201003, "ApplicationException"),
:schema_element => [
["message", "SOAP::SOAPString", [0, 1]],
["applicationException_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApplicationException.Type")], [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::BidLandscapeLandscapePoint,
:schema_type => XSD::QName.new(NsV201003, "BidLandscape.LandscapePoint"),
:schema_element => [
["bid", "AdWords::V201003::BidLandscapeService::Money", [0, 1]],
["clicks", "SOAP::SOAPLong", [0, 1]],
["cost", "AdWords::V201003::BidLandscapeService::Money", [0, 1]],
["marginalCpc", "AdWords::V201003::BidLandscapeService::Money", [0, 1]],
["impressions", "SOAP::SOAPLong", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::AuthenticationErrorReason,
:schema_type => XSD::QName.new(NsV201003, "AuthenticationError.Reason")
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::AuthorizationErrorReason,
:schema_type => XSD::QName.new(NsV201003, "AuthorizationError.Reason")
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::BidLandscapeServiceErrorReason,
:schema_type => XSD::QName.new(NsV201003, "BidLandscapeServiceError.Reason")
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::ClientTermsErrorReason,
:schema_type => XSD::QName.new(NsV201003, "ClientTermsError.Reason")
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::DatabaseErrorReason,
:schema_type => XSD::QName.new(NsV201003, "DatabaseError.Reason")
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::InternalApiErrorReason,
:schema_type => XSD::QName.new(NsV201003, "InternalApiError.Reason")
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::NotEmptyErrorReason,
:schema_type => XSD::QName.new(NsV201003, "NotEmptyError.Reason")
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::NotWhitelistedErrorReason,
:schema_type => XSD::QName.new(NsV201003, "NotWhitelistedError.Reason")
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::NullErrorReason,
:schema_type => XSD::QName.new(NsV201003, "NullError.Reason")
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::OperationAccessDeniedReason,
:schema_type => XSD::QName.new(NsV201003, "OperationAccessDenied.Reason")
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::OperatorErrorReason,
:schema_type => XSD::QName.new(NsV201003, "OperatorError.Reason")
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::QuotaCheckErrorReason,
:schema_type => XSD::QName.new(NsV201003, "QuotaCheckError.Reason")
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::RangeErrorReason,
:schema_type => XSD::QName.new(NsV201003, "RangeError.Reason")
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::RateExceededErrorReason,
:schema_type => XSD::QName.new(NsV201003, "RateExceededError.Reason")
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::ReadOnlyErrorReason,
:schema_type => XSD::QName.new(NsV201003, "ReadOnlyError.Reason")
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::RequestErrorReason,
:schema_type => XSD::QName.new(NsV201003, "RequestError.Reason")
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::RequiredErrorReason,
:schema_type => XSD::QName.new(NsV201003, "RequiredError.Reason")
)
EncodedRegistry.register(
:class => AdWords::V201003::BidLandscapeService::SizeLimitErrorReason,
:schema_type => XSD::QName.new(NsV201003, "SizeLimitError.Reason")
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::AuthenticationError,
:schema_type => XSD::QName.new(NsV201003, "AuthenticationError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::AuthenticationErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::AuthorizationError,
:schema_type => XSD::QName.new(NsV201003, "AuthorizationError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::AuthorizationErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::BidLandscapeIdFilter,
:schema_type => XSD::QName.new(NsV201003, "BidLandscapeIdFilter"),
:schema_element => [
["campaignId", "SOAP::SOAPLong", [0, 1]],
["adGroupId", "SOAP::SOAPLong", [0, 1]],
["criterionId", "SOAP::SOAPLong", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::BidLandscapeServiceError,
:schema_type => XSD::QName.new(NsV201003, "BidLandscapeServiceError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::BidLandscapeServiceErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::ClientTermsError,
:schema_type => XSD::QName.new(NsV201003, "ClientTermsError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::ClientTermsErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::CriterionBidLandscape,
:schema_type => XSD::QName.new(NsV201003, "CriterionBidLandscape"),
:schema_basetype => XSD::QName.new(NsV201003, "BidLandscape"),
:schema_element => [
["campaignId", "SOAP::SOAPLong", [0, 1]],
["adGroupId", "SOAP::SOAPLong", [0, 1]],
["startDate", "SOAP::SOAPString", [0, 1]],
["endDate", "SOAP::SOAPString", [0, 1]],
["landscapePoints", "AdWords::V201003::BidLandscapeService::BidLandscapeLandscapePoint[]", [0, nil]],
["bidLandscape_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "BidLandscape.Type")], [0, 1]],
["criterionId", "SOAP::SOAPLong", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::CriterionBidLandscapeSelector,
:schema_type => XSD::QName.new(NsV201003, "CriterionBidLandscapeSelector"),
:schema_basetype => XSD::QName.new(NsV201003, "BidLandscapeSelector"),
:schema_element => [
["idFilters", "AdWords::V201003::BidLandscapeService::BidLandscapeIdFilter[]", [0, nil]],
["bidLandscapeSelector_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "BidLandscapeSelector.Type")], [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::DoubleValue,
:schema_type => XSD::QName.new(NsV201003, "DoubleValue"),
:schema_basetype => XSD::QName.new(NsV201003, "NumberValue"),
:schema_element => [
["comparableValue_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ComparableValue.Type")], [0, 1]],
["number", "SOAP::SOAPDouble", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::InternalApiError,
:schema_type => XSD::QName.new(NsV201003, "InternalApiError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::InternalApiErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::LongValue,
:schema_type => XSD::QName.new(NsV201003, "LongValue"),
:schema_basetype => XSD::QName.new(NsV201003, "NumberValue"),
:schema_element => [
["comparableValue_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ComparableValue.Type")], [0, 1]],
["number", "SOAP::SOAPLong", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::Money,
:schema_type => XSD::QName.new(NsV201003, "Money"),
:schema_basetype => XSD::QName.new(NsV201003, "ComparableValue"),
:schema_element => [
["comparableValue_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ComparableValue.Type")], [0, 1]],
["microAmount", "SOAP::SOAPLong", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::NotEmptyError,
:schema_type => XSD::QName.new(NsV201003, "NotEmptyError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::NotEmptyErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::NotWhitelistedError,
:schema_type => XSD::QName.new(NsV201003, "NotWhitelistedError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::NotWhitelistedErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::NullError,
:schema_type => XSD::QName.new(NsV201003, "NullError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::NullErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::OperationAccessDenied,
:schema_type => XSD::QName.new(NsV201003, "OperationAccessDenied"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::OperationAccessDeniedReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::OperatorError,
:schema_type => XSD::QName.new(NsV201003, "OperatorError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::OperatorErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::QuotaCheckError,
:schema_type => XSD::QName.new(NsV201003, "QuotaCheckError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::QuotaCheckErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::C_RangeError,
:schema_type => XSD::QName.new(NsV201003, "RangeError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::RangeErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::RateExceededError,
:schema_type => XSD::QName.new(NsV201003, "RateExceededError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::RateExceededErrorReason", [0, 1]],
["rateName", "SOAP::SOAPString", [0, 1]],
["rateScope", "SOAP::SOAPString", [0, 1]],
["retryAfterSeconds", "SOAP::SOAPInt", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::ReadOnlyError,
:schema_type => XSD::QName.new(NsV201003, "ReadOnlyError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::ReadOnlyErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::RequestError,
:schema_type => XSD::QName.new(NsV201003, "RequestError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::RequestErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::RequiredError,
:schema_type => XSD::QName.new(NsV201003, "RequiredError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::RequiredErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::SizeLimitError,
:schema_type => XSD::QName.new(NsV201003, "SizeLimitError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::SizeLimitErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::SoapHeader,
:schema_type => XSD::QName.new(NsV201003, "SoapHeader"),
:schema_element => [
["authToken", "SOAP::SOAPString", [0, 1]],
["clientCustomerId", "SOAP::SOAPString", [0, 1]],
["clientEmail", "SOAP::SOAPString", [0, 1]],
["developerToken", "SOAP::SOAPString", [0, 1]],
["userAgent", "SOAP::SOAPString", [0, 1]],
["validateOnly", "SOAP::SOAPBoolean", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::SoapResponseHeader,
:schema_type => XSD::QName.new(NsV201003, "SoapResponseHeader"),
:schema_element => [
["requestId", "SOAP::SOAPString", [0, 1]],
["operations", "SOAP::SOAPLong", [0, 1]],
["responseTime", "SOAP::SOAPLong", [0, 1]],
["units", "SOAP::SOAPLong", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::DatabaseError,
:schema_type => XSD::QName.new(NsV201003, "DatabaseError"),
:schema_basetype => XSD::QName.new(NsV201003, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApiError.Type")], [0, 1]],
["reason", "AdWords::V201003::BidLandscapeService::DatabaseErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::ApiException,
:schema_type => XSD::QName.new(NsV201003, "ApiException"),
:schema_basetype => XSD::QName.new(NsV201003, "ApplicationException"),
:schema_element => [
["message", "SOAP::SOAPString", [0, 1]],
["applicationException_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApplicationException.Type")], [0, 1]],
["errors", "AdWords::V201003::BidLandscapeService::ApiError[]", [0, nil]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::ApplicationException,
:schema_type => XSD::QName.new(NsV201003, "ApplicationException"),
:schema_element => [
["message", "SOAP::SOAPString", [0, 1]],
["applicationException_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApplicationException.Type")], [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::BidLandscapeLandscapePoint,
:schema_type => XSD::QName.new(NsV201003, "BidLandscape.LandscapePoint"),
:schema_element => [
["bid", "AdWords::V201003::BidLandscapeService::Money", [0, 1]],
["clicks", "SOAP::SOAPLong", [0, 1]],
["cost", "AdWords::V201003::BidLandscapeService::Money", [0, 1]],
["marginalCpc", "AdWords::V201003::BidLandscapeService::Money", [0, 1]],
["impressions", "SOAP::SOAPLong", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::AuthenticationErrorReason,
:schema_type => XSD::QName.new(NsV201003, "AuthenticationError.Reason")
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::AuthorizationErrorReason,
:schema_type => XSD::QName.new(NsV201003, "AuthorizationError.Reason")
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::BidLandscapeServiceErrorReason,
:schema_type => XSD::QName.new(NsV201003, "BidLandscapeServiceError.Reason")
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::ClientTermsErrorReason,
:schema_type => XSD::QName.new(NsV201003, "ClientTermsError.Reason")
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::DatabaseErrorReason,
:schema_type => XSD::QName.new(NsV201003, "DatabaseError.Reason")
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::InternalApiErrorReason,
:schema_type => XSD::QName.new(NsV201003, "InternalApiError.Reason")
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::NotEmptyErrorReason,
:schema_type => XSD::QName.new(NsV201003, "NotEmptyError.Reason")
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::NotWhitelistedErrorReason,
:schema_type => XSD::QName.new(NsV201003, "NotWhitelistedError.Reason")
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::NullErrorReason,
:schema_type => XSD::QName.new(NsV201003, "NullError.Reason")
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::OperationAccessDeniedReason,
:schema_type => XSD::QName.new(NsV201003, "OperationAccessDenied.Reason")
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::OperatorErrorReason,
:schema_type => XSD::QName.new(NsV201003, "OperatorError.Reason")
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::QuotaCheckErrorReason,
:schema_type => XSD::QName.new(NsV201003, "QuotaCheckError.Reason")
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::RangeErrorReason,
:schema_type => XSD::QName.new(NsV201003, "RangeError.Reason")
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::RateExceededErrorReason,
:schema_type => XSD::QName.new(NsV201003, "RateExceededError.Reason")
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::ReadOnlyErrorReason,
:schema_type => XSD::QName.new(NsV201003, "ReadOnlyError.Reason")
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::RequestErrorReason,
:schema_type => XSD::QName.new(NsV201003, "RequestError.Reason")
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::RequiredErrorReason,
:schema_type => XSD::QName.new(NsV201003, "RequiredError.Reason")
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::SizeLimitErrorReason,
:schema_type => XSD::QName.new(NsV201003, "SizeLimitError.Reason")
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::GetBidLandscape,
:schema_name => XSD::QName.new(NsV201003, "getBidLandscape"),
:schema_element => [
["selector", "AdWords::V201003::BidLandscapeService::BidLandscapeSelector", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::GetBidLandscapeResponse,
:schema_name => XSD::QName.new(NsV201003, "getBidLandscapeResponse"),
:schema_element => [
["rval", "AdWords::V201003::BidLandscapeService::BidLandscape[]", [0, nil]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::ApiException,
:schema_name => XSD::QName.new(NsV201003, "ApiExceptionFault"),
:schema_element => [
["message", "SOAP::SOAPString", [0, 1]],
["applicationException_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201003, "ApplicationException.Type")], [0, 1]],
["errors", "AdWords::V201003::BidLandscapeService::ApiError[]", [0, nil]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::SoapHeader,
:schema_name => XSD::QName.new(NsV201003, "RequestHeader"),
:schema_element => [
["authToken", "SOAP::SOAPString", [0, 1]],
["clientCustomerId", "SOAP::SOAPString", [0, 1]],
["clientEmail", "SOAP::SOAPString", [0, 1]],
["developerToken", "SOAP::SOAPString", [0, 1]],
["userAgent", "SOAP::SOAPString", [0, 1]],
["validateOnly", "SOAP::SOAPBoolean", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdWords::V201003::BidLandscapeService::SoapResponseHeader,
:schema_name => XSD::QName.new(NsV201003, "ResponseHeader"),
:schema_element => [
["requestId", "SOAP::SOAPString", [0, 1]],
["operations", "SOAP::SOAPLong", [0, 1]],
["responseTime", "SOAP::SOAPLong", [0, 1]],
["units", "SOAP::SOAPLong", [0, 1]]
]
)
end
end; end; end
| 42.797706 | 122 | 0.652121 |
3937588ea6b02c980cd0b1ebd817682d67cdc21c | 605 | require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Phuonghoang713chat
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
end
end
| 31.842105 | 82 | 0.770248 |
bb3f0e942a553076590665e818166322296ebfef | 703 | # frozen_string_literal: true
require 'maxmind/geoip2/record/location'
module Minfraud
module Model
# Model of the GeoIP2 location information, including the local time.
class GeoIP2Location < MaxMind::GeoIP2::Record::Location
# The date and time of the transaction in the time zone associated with
# the IP address. The value is formatted according to RFC 3339. For
# instance, the local time in Boston might be returned as
# 2015-04-27T19:17:24-04:00.
#
# @return [String]
attr_reader :local_time
# @!visibility private
def initialize(record)
super(record)
@local_time = get('local_time')
end
end
end
end
| 27.038462 | 77 | 0.674253 |
38fb405e3547bc57730fe57d03293f698f9952fc | 8,521 | # Utility methods used for versioning projects for various kinds of packaging
module Pkg::Util::Version
class << self
GIT = Pkg::Util::Tool::GIT
def git_co(ref)
Pkg::Util.in_project_root do
%x{#{GIT} reset --hard ; #{GIT} checkout #{ref}}
$?.success? or fail "Could not checkout #{ref} git branch to build package from...exiting"
end
end
def git_tagged?
Pkg::Util.in_project_root do
%x{#{GIT} describe >/dev/null 2>&1}
$?.success?
end
end
def git_describe
Pkg::Util.in_project_root do
%x{#{GIT} describe}.strip
end
end
# return the sha of HEAD on the current branch
def git_sha
Pkg::Util.in_project_root do
%x{#{GIT} rev-parse HEAD}.strip
end
end
# Return the ref type of HEAD on the current branch
def git_ref_type
Pkg::Util.in_project_root do
%x{#{GIT} cat-file -t #{git_describe}}.strip
end
end
# If HEAD is a tag, return the tag. Otherwise return the sha of HEAD.
def git_sha_or_tag
if git_ref_type == "tag"
git_describe
else
git_sha
end
end
# Return true if we're in a git repo, otherwise false
def is_git_repo?
Pkg::Util.in_project_root do
%x{#{GIT} rev-parse --git-dir > /dev/null 2>&1}
$?.success?
end
end
alias :is_git_repo :is_git_repo?
# Return information about the current tree, using `git describe`, ready for
# further processing.
#
# Returns an array of one to four elements, being:
# * version (three dot-joined numbers, leading `v` stripped)
# * the string 'rcX' (if the last tag was an rc release, where X is the rc number)
# * commits (string containing integer, number of commits since that version was tagged)
# * dirty (string 'dirty' if local changes exist in the repo)
def git_describe_version
return nil unless is_git_repo and raw = run_git_describe_internal
# reprocess that into a nice set of output data
# The elements we select potentially change if this is an rc
# For an rc with added commits our string will be something like '0.7.0-rc1-63-g51ccc51'
# and our return will be [0.7.0, rc1, 63, <dirty>]
# For a final with added commits, it will look like '0.7.0-63-g51ccc51'
# and our return will be [0.7.0, 64, <dirty>]
info = raw.chomp.sub(/^v/, '').split('-')
if info[1].to_s.match('^[\d]+')
version_string = info.values_at(0,1,3).compact
else
version_string = info.values_at(0,1,2,4).compact
end
version_string
end
# This is a stub to ease testing...
def run_git_describe_internal
Pkg::Util.in_project_root do
raw = %x{#{GIT} describe --tags --dirty 2>/dev/null}
$?.success? ? raw : nil
end
end
def get_dash_version
if info = git_describe_version
info.join('-')
else
get_pwd_version
end
end
def uname_r
uname = Pkg::Util::Tool.find_tool('uname', :required => true)
%x{#{uname} -r}.chomp
end
def get_ips_version
if info = git_describe_version
version, commits, dirty = info
if commits.to_s.match('^rc[\d]+')
commits = info[2]
dirty = info[3]
end
osrelease = uname_r
"#{version},#{osrelease}-#{commits.to_i}#{dirty ? '-dirty' : ''}"
else
get_pwd_version
end
end
def get_dot_version
get_dash_version.gsub('-', '.')
end
def get_pwd_version
Dir.pwd.split('.')[-1]
end
def get_base_pkg_version
dash = get_dash_version
if dash.include?("rc")
# Grab the rc number
rc_num = dash.match(/rc(\d+)/)[1]
ver = dash.sub(/-?rc[0-9]+/, "-0.#{Pkg::Config.release}rc#{rc_num}").gsub(/(rc[0-9]+)-(\d+)?-?/, '\1.\2')
else
ver = dash.gsub('-','.') + "-#{Pkg::Config.release}"
end
ver.split('-')
end
def get_debversion
get_base_pkg_version.join('-') << "#{Pkg::Config.packager}1"
end
def get_origversion
Pkg::Config.debversion.split('-')[0]
end
def get_rpmversion
get_base_pkg_version[0]
end
def get_rpmrelease
get_base_pkg_version[1]
end
def source_dirty?
git_describe_version.include?('dirty')
end
def fail_on_dirty_source
if source_dirty?
fail "
The source tree is dirty, e.g. there are uncommited changes. Please
commit/discard changes and try again."
end
end
# Determines if this package is a final package via the
# selected version_strategy.
# There are currently two supported version strategies.
#
# This method calls down to the version strategy indicated, defaulting to the
# rc_final strategy. The methods themselves will return false if it is a final
# release, so their return values are collected and then inverted before being
# returned.
def is_final?
ret = nil
case Pkg::Config.version_strategy
when "rc_final"
ret = is_rc?
when "odd_even"
ret = is_odd?
when nil
ret = is_rc?
end
return (! ret)
end
# the rc_final strategy (default)
# Assumes version strings in the formats:
# final:
# '0.7.0'
# '0.7.0-63'
# '0.7.0-63-dirty'
# development:
# '0.7.0rc1 (we don't actually use this format anymore, but once did)
# '0.7.0-rc1'
# '0.7.0-rc1-63'
# '0.7.0-rc1-63-dirty'
def is_rc?
return TRUE if get_dash_version =~ /^\d+\.\d+\.\d+-*rc\d+/
return FALSE
end
# the odd_even strategy (mcollective)
# final:
# '0.8.0'
# '1.8.0-63'
# '0.8.1-63-dirty'
# development:
# '0.7.0'
# '1.7.0-63'
# '0.7.1-63-dirty'
def is_odd?
return TRUE if get_dash_version.match(/^\d+\.(\d+)\.\d+/)[1].to_i.odd?
return FALSE
end
# Utility method to return the dist method if this is a redhat box. We use this
# in rpm packaging to define a dist macro, and we use it in the pl:fetch task
# to disable ssl checking for redhat 5 because it has a certs bundle so old by
# default that it's useless for our purposes.
def el_version
if File.exists?('/etc/fedora-release')
nil
elsif File.exists?('/etc/redhat-release')
rpm = Pkg::Util::Tool.find_tool('rpm', :required => true)
return %x{#{rpm} -q --qf \"%{VERSION}\" $(#{rpm} -q --whatprovides /etc/redhat-release )}
end
end
# This is to support packages that only burn-in the version number in the
# release artifact, rather than storing it two (or more) times in the
# version control system. Razor is a good example of that; see
# https://github.com/puppetlabs/Razor/blob/master/lib/project_razor/version.rb
# for an example of that this looks like.
#
# If you invoke this the version will only be modified in the temporary copy,
# with the intent that it never change the official source tree.
def versionbump(workdir=nil)
version = ENV['VERSION'] || Pkg::Config.version.to_s.strip
new_version = '"' + version + '"'
version_file = "#{workdir ? workdir + '/' : ''}#{Pkg::Config.version_file}"
# Read the previous version file in...
contents = IO.read(version_file)
# Match version files containing 'VERSION = "x.x.x"' and just x.x.x
if version_string = contents.match(/VERSION =.*/)
old_version = version_string.to_s.split()[-1]
else
old_version = contents
end
puts "Updating #{old_version} to #{new_version} in #{version_file}"
if contents.match("@DEVELOPMENT_VERSION@")
contents.gsub!("@DEVELOPMENT_VERSION@", version)
elsif contents.match('version\s*=\s*[\'"]DEVELOPMENT[\'"]')
contents.gsub!(/version\s*=\s*['"]DEVELOPMENT['"]/, "version = '#{version}'")
elsif contents.match("VERSION = #{old_version}")
contents.gsub!("VERSION = #{old_version}", "VERSION = #{new_version}")
elsif contents.match("#{Pkg::Config.project.upcase}VERSION = #{old_version}")
contents.gsub!("#{Pkg::Config.project.upcase}VERSION = #{old_version}", "#{Pkg::Config.project.upcase}VERSION = #{new_version}")
else
contents.gsub!(old_version, Pkg::Config.version)
end
# ...and write it back on out.
File.open(version_file, 'w') {|f| f.write contents }
end
end
end
| 30.873188 | 136 | 0.608966 |
d59bd80408294d3febcffcda958d37e9dc3c9bf2 | 125 | FactoryGirl.define do
factory :book_author do
book_id Faker::Number.digit
author_id Faker::Number.digit
end
end
| 15.625 | 33 | 0.744 |
61f52033f8afc247557b08d2b70085e3c93f9c0d | 770 | #
# Cookbook:: django
# Recipe:: startproject
#
# Copyright:: 2017, The Authors, All Rights Reserved.
project_name = node.default['django']['project_name']
env = node.default['django']['env']
# Create the environment directory
directory "#{env}/#{project_name}/#{project_name}" do
recursive true
end
# Add manage.py
template "#{env}/#{project_name}/manage.py" do
source 'manage.py.erb'
variables project: "#{project_name}"
end
# Setting files
['settings.py', 'urls.py', 'wsgi.py'].each do |setting_file|
template "#{env}/#{project_name}/#{project_name}/#{setting_file}" do
source "#{setting_file}.erb"
variables project: "#{project_name}"
end
end
# Create __init__.py file
file "#{env}/#{project_name}/#{project_name}/__init__.py" | 26.551724 | 72 | 0.685714 |
6aa7bc43a8bd160d2a2b4b40fb54f81c961f7308 | 1,297 | class WikiPageVersion < ApplicationRecord
array_attribute :other_names
belongs_to :wiki_page
belongs_to_updater
user_status_counter :wiki_edit_count, foreign_key: :updater_id
belongs_to :artist, optional: true
delegate :visible?, :to => :wiki_page
extend Memoist
module SearchMethods
def for_user(user_id)
where("updater_id = ?", user_id)
end
def search(params)
q = super
if params[:updater_id].present?
q = q.for_user(params[:updater_id].to_i)
end
if params[:wiki_page_id].present?
q = q.where("wiki_page_id = ?", params[:wiki_page_id].to_i)
end
q = q.attribute_matches(:title, params[:title])
q = q.attribute_matches(:body, params[:body])
q = q.attribute_matches(:is_locked, params[:is_locked])
q = q.attribute_matches(:is_deleted, params[:is_deleted])
if params[:ip_addr].present?
q = q.where("updater_ip_addr <<= ?", params[:ip_addr])
end
q.apply_default_order(params)
end
end
extend SearchMethods
def pretty_title
title.tr("_", " ")
end
def previous
WikiPageVersion.where("wiki_page_id = ? and id < ?", wiki_page_id, id).order("id desc").first
end
memoize :previous
def category_name
Tag.category_for(title)
end
end
| 23.581818 | 97 | 0.666924 |
7af54d9791c70c6b03848bd17312f32d32da74a3 | 6,585 | # Copyright 2016 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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 "helper"
describe Google::Cloud::Logging::Middleware, :mock_logging do
let(:app_exception_msg) { "A serious error from application" }
let(:service_name) { "My microservice" }
let(:service_version) { "Version testing" }
let(:trace_id) { "1234567890abcdef1234567890abcdef" }
let(:trace_context) { "#{trace_id}/123456;o=1" }
let(:rack_env) {{
"HTTP_X_CLOUD_TRACE_CONTEXT" => trace_context,
"PATH_INFO" => "/_ah/health"
}}
let(:app_exception) { StandardError.new(app_exception_msg) }
let(:rack_app) {
app = OpenStruct.new
def app.call(_) end
app
}
let(:log_name) { "web_app_log" }
let(:resource) do
Google::Cloud::Logging::Resource.new.tap do |r|
r.type = "gce_instance"
r.labels["zone"] = "global"
r.labels["instance_id"] = "abc123"
end
end
let(:labels) { { "env" => "production" } }
let(:logger) { Google::Cloud::Logging::Logger.new logging, log_name, resource, labels }
let(:middleware) {
Google::Cloud::Logging::Middleware.new rack_app, logger: logger,
project_id: project
}
after {
# Clear configuration values between each test
Google::Cloud::Logging.configure.delete :project_id
Google::Cloud::Logging.configure.delete :keyfile
Google::Cloud::Logging.configure.delete :log_name
Google::Cloud::Logging.configure.delete :log_name_map
Google::Cloud::Logging.configure.monitored_resource.delete :type
Google::Cloud::Logging.configure.monitored_resource.delete :labels
Google::Cloud.configure.delete :use_logging
}
describe "#initialize" do
let(:default_credentials) do
creds = OpenStruct.new empty: true
def creds.is_a? target
target == Google::Auth::Credentials
end
creds
end
it "creates a default logger object if one isn't provided" do
Google::Cloud::Logging::Project.stub :default_project_id, project do
Google::Cloud::Logging::Credentials.stub :default, default_credentials do
middleware = Google::Cloud::Logging::Middleware.new rack_app
end
end
middleware.logger.must_be_kind_of Google::Cloud::Logging::Logger
end
it "uses the logger provided if given" do
middleware.logger.must_equal logger
end
end
describe "#call" do
it "sets env[\"rack.logger\"] to the given logger" do
stubbed_call = ->(env) {
env["rack.logger"].must_equal logger
}
rack_app.stub :call, stubbed_call do
middleware.call rack_env
end
end
it "calls logger.add_request_info to track trace_id and log_name" do
stubbed_add_request_info = ->(args) {
args[:trace_id].must_equal trace_id
args[:log_name].must_equal "ruby_health_check_log"
args[:env].must_equal rack_env
}
logger.stub :add_request_info, stubbed_add_request_info do
middleware.call rack_env
end
end
it "calls logger.delete_request_info when exiting even app.call fails" do
method_called = false
stubbed_delete_request_info = ->() {
method_called = true
}
stubbed_call = ->(_) { raise "die" }
logger.stub :delete_request_info, stubbed_delete_request_info do
rack_app.stub :call, stubbed_call do
assert_raises StandardError do
middleware.call rack_env
end
method_called.must_equal true
end
end
end
end
describe ".build_monitored_resource" do
let(:custom_type) { "custom-monitored-resource-type" }
let(:custom_labels) { {label_one: 1, label_two: 2} }
let(:default_rc) { "Default-monitored-resource" }
it "returns resource of right type if given parameters" do
Google::Cloud::Logging::Middleware.stub :default_monitored_resource, default_rc do
rc = Google::Cloud::Logging::Middleware.build_monitored_resource custom_type, custom_labels
rc.type.must_equal custom_type
rc.labels.must_equal custom_labels
end
end
it "returns default monitored resource if only given type" do
Google::Cloud::Logging::Middleware.stub :default_monitored_resource, default_rc do
rc = Google::Cloud::Logging::Middleware.build_monitored_resource custom_type
rc.must_equal default_rc
end
end
it "returns default monitored resource if only given labels" do
Google::Cloud::Logging::Middleware.stub :default_monitored_resource, default_rc do
rc = Google::Cloud::Logging::Middleware.build_monitored_resource nil, custom_labels
rc.must_equal default_rc
end
end
end
describe ".default_monitored_resource" do
it "returns resource of type gae_app if app_engine? is true" do
Google::Cloud.stub :env, OpenStruct.new(:app_engine? => true, :container_engine? => false, :compute_engine? => true) do
rc = Google::Cloud::Logging::Middleware.build_monitored_resource
rc.type.must_equal "gae_app"
end
end
it "returns resource of type container if container_engine? is true" do
Google::Cloud.stub :env, OpenStruct.new(:app_engine? => false, :container_engine? => true, :compute_engine? => true) do
rc = Google::Cloud::Logging::Middleware.build_monitored_resource
rc.type.must_equal "container"
end
end
it "returns resource of type gce_instance if compute_engine? is true" do
Google::Cloud.stub :env, OpenStruct.new(:app_engine? => false, :container_engine? => false, :compute_engine? => true) do
rc = Google::Cloud::Logging::Middleware.build_monitored_resource
rc.type.must_equal "gce_instance"
end
end
it "returns resource of type global if not on GCP" do
Google::Cloud.stub :env, OpenStruct.new(:app_engine? => false, :container_engine? => false, :compute_engine? => false) do
rc = Google::Cloud::Logging::Middleware.build_monitored_resource
rc.type.must_equal "global"
end
end
end
end
| 36.381215 | 127 | 0.686409 |
e2b1b332a0e674fce1e63b094d6bb9ca7d128341 | 4,550 | # encoding: UTF-8
#
# Copyright (c) 2015 by Chris Schlaeger <[email protected]>
#
# MIT License
#
# 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.
#
$:.unshift File.join(File.dirname(__FILE__), '..', '..', 'lib')
require 'perobs'
# This class creates and manages a simple DB with some toy data to check the
# conversion routines for legacy DB formats.
class LegacyDB
class Fragment < PEROBS::Object
attr_persist :str, :pred, :succ
def initialize(p, str, pred = nil)
super(p)
self.str = str
self.pred = pred
self.succ = nil
end
end
N1 = 293
N2 = 427
def initialize(name)
@name = name
@store = nil
end
def create
@store = PEROBS::Store.new(@name)
@store['fragments'] = @store.new(PEROBS::Array)
@store['metadata'] = @store.new(PEROBS::Hash)
@store['by_length'] = @store.new(PEROBS::Hash)
# Create a long string of digits.
number = (N1**N2).to_s
# Find a suitable digit that we can use a separator to split the long
# string into smaller strings.
separator = find_separator(number)
@store['metadata']['separator'] = separator
pred = nil
# Store all the fragments in the @store['fragments'] array.
number.split(separator).each do |fragment|
@store['fragments'] << (f = @store.new(Fragment, fragment, pred))
# Additionally, we create the doubly-linked list of the fragments.
pred.succ = f if pred
pred = f
# And we store the fragments hashed by their length.
length = fragment.length.to_s
if @store['by_length'][length].nil?
@store['by_length'][length] = @store.new(PEROBS::Array)
end
@store['by_length'][length] << f
end
@store.exit
end
def open
@store = PEROBS::Store.new(@name)
end
def check
# Recreate the original number from the @store['fragments'] list.
number = @store['fragments'].map { |f| f.str }.
join(@store['metadata']['separator'])
if number.to_i != N1 ** N2
raise RuntimeError, "Number mismatch\n#{number}\n#{N1 ** N2}"
end
# Check the total number of digits based on the bash by length.
fragment_counter = 0
total_fragment_length = 0
@store['by_length'].each do |length, fragments|
fragment_counter += fragments.length
total_fragment_length += length.to_i * fragments.length
end
if number.length != total_fragment_length + fragment_counter - 1
raise RuntimeError, "Number length mismatch"
end
# Recreate the original number from the linked list forward traversal.
number = ''
f = @store['fragments'][0]
while f
number += @store['metadata']['separator'] unless number.empty?
number += f.str
f = f.succ
end
if number.to_i != N1 ** N2
raise RuntimeError, "Number mismatch\n#{number}\n#{N1 ** N2}"
end
# Recreate the original number from the linked list backwards traversal.
number = ''
f = @store['fragments'][-1]
while f
number = @store['metadata']['separator'] + number unless number.empty?
number = f.str + number
f = f.pred
end
if number.to_i != N1 ** N2
raise RuntimeError, "Number mismatch\n#{number}\n#{N1 ** N2}"
end
true
end
def repair
@store.check(true)
end
private
def find_separator(str)
0.upto(9) do |digit|
c = digit.to_s
return c if str[0] != c && str[-1] != c
end
raise RuntimeError, "Could not find separator"
end
end
#db = LegacyDB.new('test')
#db.create
#db.open
#db.check
| 29.166667 | 76 | 0.663736 |
6279f0946063f23ece78234147eefe124ff0c15e | 1,178 | class FontBitstreamVera < Formula
version "1.10"
sha256 "1b0ba0f7af2e1d05f64e259d351965a2cb2673104a057ce715a06969c478f6cc"
url "https://ftp.gnome.org/pub/GNOME/sources/ttf-bitstream-vera/#{version}/ttf-bitstream-vera-#{version}.zip"
desc "Bitstream Vera"
homepage "https://www.gnome.org/fonts/"
def install
parent = File.dirname(Dir.pwd) != (ENV['HOMEBREW_TEMP'] || '/tmp') ? '../' : ''
(share/"fonts").install "#{parent}ttf-bitstream-vera-1.10/Vera.ttf"
(share/"fonts").install "#{parent}ttf-bitstream-vera-1.10/VeraBI.ttf"
(share/"fonts").install "#{parent}ttf-bitstream-vera-1.10/VeraBd.ttf"
(share/"fonts").install "#{parent}ttf-bitstream-vera-1.10/VeraIt.ttf"
(share/"fonts").install "#{parent}ttf-bitstream-vera-1.10/VeraMoBI.ttf"
(share/"fonts").install "#{parent}ttf-bitstream-vera-1.10/VeraMoBd.ttf"
(share/"fonts").install "#{parent}ttf-bitstream-vera-1.10/VeraMoIt.ttf"
(share/"fonts").install "#{parent}ttf-bitstream-vera-1.10/VeraMono.ttf"
(share/"fonts").install "#{parent}ttf-bitstream-vera-1.10/VeraSe.ttf"
(share/"fonts").install "#{parent}ttf-bitstream-vera-1.10/VeraSeBd.ttf"
end
test do
end
end
| 51.217391 | 111 | 0.698642 |
4ac68bea7a7807d2c249a2591d821d13e153ae8c | 10,725 | # frozen_string_literal: true
# Represents an assessment in Coursemology, as well as the enclosing module for associated models.
#
# An assessment is a collection of questions that can be asked.
class Course::Assessment < ApplicationRecord
acts_as_lesson_plan_item has_todo: true
acts_as_conditional
has_one_folder
# Concern must be included below acts_as_lesson_plan_item to override #can_user_start?
include Course::Assessment::TodoConcern
include Course::ClosingReminderConcern
include DuplicationStateTrackingConcern
after_initialize :set_defaults, if: :new_record?
before_validation :propagate_course, if: :new_record?
before_validation :assign_folder_attributes
after_commit :grade_with_new_test_cases, on: :update
before_save :save_tab, on: :create
enum randomization: { prepared: 0 }
validates :autograded, inclusion: { in: [true, false] }
validates :session_password, length: { maximum: 255 }, allow_nil: true
validates :tabbed_view, inclusion: { in: [true, false] }
validates :view_password, length: { maximum: 255 }, allow_nil: true
validates :creator, presence: true
validates :updater, presence: true
validates :tab, presence: true
belongs_to :tab, inverse_of: :assessments
# `submissions` association must be put before `questions`, so that all answers will be deleted
# first when deleting the course. Otherwise due to the foreign key `question_id` in answers table,
# questions cannot be deleted.
has_many :submissions, inverse_of: :assessment, dependent: :destroy
has_many :question_assessments, class_name: Course::QuestionAssessment.name,
inverse_of: :assessment, dependent: :destroy
has_many :questions, through: :question_assessments do
include Course::Assessment::QuestionsConcern
end
has_many :multiple_response_questions,
through: :questions, inverse_through: :question, source: :actable,
source_type: Course::Assessment::Question::MultipleResponse.name
has_many :text_response_questions,
through: :questions, inverse_through: :question, source: :actable,
source_type: Course::Assessment::Question::TextResponse.name
has_many :programming_questions,
through: :questions, inverse_through: :question, source: :actable,
source_type: Course::Assessment::Question::Programming.name
has_many :scribing_questions,
through: :questions, inverse_through: :question, source: :actable,
source_type: Course::Assessment::Question::Scribing.name
has_many :voice_response_questions,
through: :questions, inverse_through: :question, source: :actable,
source_type: Course::Assessment::Question::VoiceResponse.name
has_many :assessment_conditions, class_name: Course::Condition::Assessment.name,
inverse_of: :assessment, dependent: :destroy
has_many :question_groups, class_name: Course::Assessment::QuestionGroup.name,
inverse_of: :assessment, dependent: :destroy
has_many :question_bundles, class_name: Course::Assessment::QuestionBundle.name, through: :question_groups
has_many :question_bundle_questions, class_name: Course::Assessment::QuestionBundleQuestion.name,
through: :question_bundles
has_many :question_bundle_assignments, class_name: Course::Assessment::QuestionBundleAssignment.name,
inverse_of: :assessment, dependent: :destroy
validate :tab_in_same_course
validate :selected_test_type_for_grading
scope :published, -> { where(published: true) }
# @!attribute [r] maximum_grade
# Gets the maximum grade allowed by this assessment. This is the sum of all questions'
# maximum grade.
# @return [Integer]
calculated :maximum_grade, (lambda do
Course::Assessment::Question.
select('coalesce(sum(caq.maximum_grade), 0)').
from(
"course_assessment_questions caq INNER JOIN course_question_assessments cqa ON \
cqa.assessment_id = course_assessments.id AND cqa.question_id = caq.id"
)
end)
# @!method self.ordered_by_date_and_title
# Orders the assessments by the starting date and title.
scope :ordered_by_date_and_title, (lambda do
select(<<~SQL).
course_assessments.*, course_reference_times.start_at, course_lesson_plan_items.title
SQL
joins(:lesson_plan_item).
merge(Course::LessonPlan::Item.ordered_by_date_and_title)
end)
# @!method with_submissions_by(creator)
# Includes the submissions by the provided user.
# @param [User] user The user to preload submissions for.
scope :with_submissions_by, (lambda do |user|
submissions = Course::Assessment::Submission.by_user(user).
where(assessment: distinct(false).pluck(:id)).ordered_by_date
all.to_a.tap do |result|
preloader = ActiveRecord::Associations::Preloader::ManualPreloader.new
preloader.preload(result, :submissions, submissions)
end
end)
# Used by the with_actable_types scope in Course::LessonPlan::Item.
# Edit this to remove items for showing in the lesson plan.
#
# Here, actable_data contains the list of tab IDs to be removed.
scope :ids_showable_in_lesson_plan, (lambda do |actable_data|
joining { lesson_plan_item }.
where.not(tab_id: actable_data).
selecting { lesson_plan_item.id }
end)
def self.use_relative_model_naming?
true
end
def to_partial_path
'course/assessment/assessments/assessment'
end
# Update assessment mode from params.
#
# @param [Hash] params Params with autograded mode from user.
def update_mode(params)
target_mode = params[:autograded]
return if target_mode == autograded || !allow_mode_switching?
if target_mode == true
self.autograded = true
self.session_password = nil
self.view_password = nil
self.delayed_grade_publication = false
elsif target_mode == false # Ignore the case when the params is empty.
self.autograded = false
self.skippable = false
end
end
# Update assessment randomization from params
#
# @param [Hash] Params with randomization boolean from user
def update_randomization(params)
self.randomization = params[:randomization] ? :prepared : nil
end
# Whether the assessment allows mode switching.
# Allow mode switching if:
# - The assessment don't have any submissions.
# - Switching from autograded mode to manually graded mode.
def allow_mode_switching?
submissions.count == 0 || autograded?
end
# @override ConditionalInstanceMethods#permitted_for!
def permitted_for!(_course_user)
end
# @override ConditionalInstanceMethods#precluded_for!
def precluded_for!(_course_user)
end
# @override ConditionalInstanceMethods#satisfiable?
def satisfiable?
published?
end
# The password to prevent from viewing the assessment.
def view_password_protected?
view_password.present?
end
# The password to prevent attempting submission from multiple sessions.
def session_password_protected?
session_password.present?
end
def downloadable?
questions.any?(&:downloadable?)
end
def initialize_duplicate(duplicator, other)
copy_attributes(other, duplicator)
target_tab = initialize_duplicate_tab(duplicator, other)
self.folder = duplicator.duplicate(other.folder)
folder.parent = target_tab.category.folder
self.question_assessments = duplicator.duplicate(other.question_assessments)
initialize_duplicate_conditions(duplicator, other)
set_duplication_flag
end
def include_in_consolidated_email?(event)
Course::Settings::AssessmentsComponent.email_enabled?(tab.category,
"assessment_#{event}".to_sym)
end
def graded_test_case_types
[].tap do |result|
result.push('public_test') if use_public
result.push('private_test') if use_private
result.push('evaluation_test') if use_evaluation
end
end
private
# Parents the assessment under its duplicated parent tab, if it exists.
#
# @return [Course::Assessment::Tab] The duplicated assessment's tab
def initialize_duplicate_tab(duplicator, other)
if duplicator.duplicated?(other.tab)
target_tab = duplicator.duplicate(other.tab)
else
target_category = duplicator.options[:destination_course].assessment_categories.first
target_tab = target_category.tabs.first
end
self.tab = target_tab
end
# Set up conditions that depend on this assessment and conditions that this assessment depends on.
def initialize_duplicate_conditions(duplicator, other)
duplicate_conditions(duplicator, other)
assessment_conditions << other.assessment_conditions.
select { |condition| duplicator.duplicated?(condition.conditional) }.
map { |condition| duplicator.duplicate(condition) }
end
# Sets the course of the lesson plan item to be the same as the one for the assessment.
def propagate_course
lesson_plan_item.course = tab.category.course
end
def assign_folder_attributes
# Folder attributes are handled during duplication by folder duplication code
return if duplicating?
folder.assign_attributes(name: title, course: course, parent: tab.category.folder,
start_at: start_at)
end
def set_defaults
self.published = false
self.autograded ||= false
end
def tab_in_same_course
return unless tab_id_changed?
errors.add(:tab, :not_in_same_course) unless tab.category.course == course
end
def selected_test_type_for_grading
errors.add(:no_test_type_chosen) unless use_public || use_private || use_evaluation
end
# Check for changes to graded test case booleans for autograded assessments.
def regrade_programming_answers?
(previous_changes.keys & ['use_private', 'use_public', 'use_evaluation']).any? && autograded?
end
# Re-grades all submissions to programming_questions after any change to
# test case booleans has been committed
def grade_with_new_test_cases
return unless regrade_programming_answers?
# Regrade all published submissions' programming answers and update exp points awarded
submissions.select(&:published?).each do |submission|
submission.resubmit_programming!
submission.save!
submission.mark!
submission.publish!
end
end
# Somehow autosaving more than 1 level of association doesn't work in Rails 5.2
def save_tab
tab.category.save if tab&.category && !tab.category.persisted?
tab.save if tab && !tab.persisted?
end
end
| 37.897527 | 108 | 0.728671 |
381bbe3db3787769120ee17d155e703e171db434 | 156 | require File.expand_path('../../../../spec_helper', __FILE__)
describe "CGI::Util#escape_element" do
it "needs to be reviewed for spec completeness"
end
| 26 | 61 | 0.724359 |
ed0fb3631b761bb2d5d3eadc99ff04c9877e185c | 2,603 | require 'api/lib/restresource'
require 'api/lib/restresource_tags'
require 'api/resources/polls/polls.objects'
require 'api/resources/polls/votes.rest'
module MojuraAPI
class PollsResource < RestResource
def name
'Polls'
end
def description
'Resource of polls'
end
def all(params)
params[:pagesize] ||= 50
result = paginate(params) { | options | Polls.new(self.filter(params), options) }
return result
end
def post(params)
poll = Poll.new
raise NoRightsException unless AccessControl.has_rights?(:create, poll)
return poll.load_from_hash(params).save_to_db.to_h(false, params[:include_votes])
end
def get(params)
poll = Poll.new(params[:ids][0])
raise NoRightsException unless AccessControl.has_rights?(:read, poll)
return poll.to_h(false, params[:include_votes])
end
def put(params)
poll = Poll.new(params[:ids][0])
raise NoRightsException unless AccessControl.has_rights?(:update, poll)
poll.load_from_hash(params)
poll.clear_votes if params[:clear_votes]
return poll.save_to_db.to_h(false, params[:include_votes])
end
def delete(params)
poll = Poll.new(params[:ids][0])
raise NoRightsException unless AccessControl.has_rights?(:delete, poll)
poll.delete_from_db
return [:success => true]
end
def all_conditions
result = {
description: 'Returns a list of polls. Use pagination to make selections.',
attributes: {}
}
return result
end
def post_conditions
result = {
description: 'Creates a poll and returns the object.',
attributes: {
title: {required: true, type: String, description: 'The title of the poll.'},
description: {required: false, type: String, description: 'The description of the poll.'},
options: {required: true, type: String, description: 'All available options for the poll, seperated by newlines \n.'},
active: {required: false, type: Boolean, description: 'Set to true to make the poll voteable.'},
}
}
result[:attributes].merge(self.tags_conditions)
return result
end
def get_conditions
{
description: 'Returns a poll with the specified pollid.',
}
end
def put_conditions
result =
{
description: 'Updates a poll with the given keys.',
attributes: self.post_conditions[:attributes].each { |_, v| v[:required] = false }
}
return result
end
def delete_conditions
{
description: 'Deletes the poll.'
}
end
end
API.register_resource(PollsResource.new('polls', '', '[pollid]'))
API.register_resource(TagsResource.new('polls', '[pollid]/tags', Poll))
end | 26.292929 | 123 | 0.699577 |
615f53268e11ef1865876e8049041e3976b2f457 | 379 | cask 'lacona' do
version '0.3'
sha256 'e45fb6f855ffca635b96f79bdc262d46d1e384157163694f8686c29095c5e450'
url "http://lacona-download.firebaseapp.com/packages/#{version}/LaconaBeta.zip"
name 'Lacona'
homepage 'http://www.lacona.io'
license :unknown # TODO: change license and remove this comment; ':unknown' is a machine-generated placeholder
app 'Lacona.app'
end
| 31.583333 | 112 | 0.765172 |
1c80155860ff66b8f85f3a99f76e87e92102cf33 | 2,213 | # encoding: utf-8
# This file is distributed under New Relic's license terms.
# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
# This class represents a set of metrics that were recorded during a single
# transaction. Since the name of the transaction is not known until its end, we
# don't save explicit scopes with these metrics, we just keep separate
# collections of scoped and unscoped metrics.
module NewRelic
module Agent
class TransactionMetrics
DEFAULT_PROC = Proc.new { |hash, name| hash[name] = NewRelic::Agent::Stats.new }
def initialize
@lock = Mutex.new
@unscoped = Hash.new(&DEFAULT_PROC)
@scoped = Hash.new(&DEFAULT_PROC)
end
# As a general rule, when recording a scoped metric, the corresponding
# unscoped metric should always be recorded as well.
#
# As an optimization, scoped metrics are representated within this class
# only by their entries in the @scoped Hash, and it's up to clients to
# propagate them into unscoped metrics as well when instances of this
# class are merged into the global metric store.
#
def record_scoped_and_unscoped(names, value = nil, aux = nil, &blk)
_record_metrics(names, value, aux, @scoped, &blk)
end
def record_unscoped(names, value = nil, aux = nil, &blk)
_record_metrics(names, value, aux, @unscoped, &blk)
end
def has_key?(key)
@unscoped.has_key?(key)
end
def [](key)
@unscoped[key]
end
def each_unscoped
@lock.synchronize { @unscoped.each { |name, stats| yield name, stats } }
end
def each_scoped
@lock.synchronize { @scoped.each { |name, stats| yield name, stats } }
end
def _record_metrics(names, value, aux, target, &blk)
# This looks dumb, but we're avoiding an extra Array allocation.
case names
when Array
names.each do |name|
@lock.synchronize { target[name].record(value, aux, &blk) }
end
else
@lock.synchronize { target[names].record(value, aux, &blk) }
end
end
end
end
end
| 33.029851 | 93 | 0.646182 |
5d89377303229cacd4fbf6bd6860cd4e15ccf36a | 5,815 | namespace :radiant do
namespace :extensions do
namespace :ratings do
desc "Single task to install and update the ratings extension"
task :install => [:environment, :migrate, 'update:all']
desc "Single task to uninstall the ratings extension"
task :uninstall => :environment do
if confirm('Are you sure you want to uninstall the ratings extension? This will revert the migration, remove the ratings assets, and delete the rating snippets and config settings.')
ENV['FORCE'] = 'true'
%w(revert_migration delete:all).each { |t| Rake::Task["radiant:extensions:ratings:#{t}"].invoke }
end
end
def confirm(question)
require 'highline/import' unless respond_to?(:agree)
ENV['FORCE'] || agree("#{question} [yn]")
end
desc "Runs the migration of the Ratings extension"
task :migrate => :environment do
require 'radiant/extension_migrator'
if ENV["VERSION"]
RatingsExtension.migrator.migrate(ENV["VERSION"].to_i)
else
RatingsExtension.migrator.migrate
end
end
desc "Reverts the migrations run by the ratings extension"
task :revert_migration => :environment do
if Rating.table_exists? && confirm("This task will destroy all your ratings data. Are you sure you want to continue?")
require 'radiant/extension_migrator'
RatingsExtension.migrator.migrate(0)
end
end
def get_yaml(filename)
yaml_file = File.join(RatingsExtension.root, "db", filename)
yaml = File.open(yaml_file) { |f| f.read }
YAML.load(yaml)
end
namespace :update do
desc "Update assets and snippets for the ratings extension."
task :all => [:environment, :config, :assets, :snippets]
desc "Updates the rating configuration settings for the ratings extension to the latest defaults"
task :config => :environment do
if Radiant::Config.table_exists?
puts "Updating config settings..."
get_yaml('config_defaults.yml').each do |key, value|
c = Radiant::Config.find_or_initialize_by_key("ratings.#{key}")
if c.new_record? || confirm("Are you sure you want to overwrite existing config setting ratings.#{key}?")
c.value = value
c.save!
puts " - ratings.#{key} = #{value}"
end
end
else
puts "The radiant config table does not exist. Please create it, then re-run this migration."
end
end
desc "Copies public assets of the ratings extension to the instance public/ directory."
task :assets => :environment do
puts "Copying assets for the ratings extension..."
Dir[RatingsExtension.root + "/public/**/*"].each do |file|
next if File.directory?(file)
path = file.sub(RatingsExtension.root, '')
directory = File.dirname(path)
if !File.exists?(RAILS_ROOT + path) || confirm("Are you sure you want to overwrite existing asset #{path}?")
mkdir_p RAILS_ROOT + directory, :verbose => false
cp file, RAILS_ROOT + path, :verbose => false
puts " - #{path}"
end
end
end
desc "Creates or updates the default snippets used by the ratings extension"
task :snippets => :environment do
puts "Updating snippets for the ratings extension..."
get_yaml('snippets.yml').each do |snippet_name, snippet_content|
s = Snippet.find_or_initialize_by_name(snippet_name)
if s.new_record? || confirm("Are you sure you want to overwrite existing snippet #{snippet_name}?")
s.content = snippet_content
s.save!
puts " - #{snippet_name}"
end
end
end
end
namespace :delete do
desc "Deletes the assets and snippets installed by the ratings extension."
task :all => [:environment, :config, :assets, :snippets]
desc "Deletes the radiant configuration settings added by the ratings extension"
task :config => :environment do
if Radiant::Config.table_exists?
puts "Deleting config settings..."
get_yaml('config_defaults.yml').each do |key, value|
if c = Radiant::Config.find_by_key("ratings.#{key}") and confirm("Are you sure you want to delete config setting ratings.#{key}?")
c.destroy
puts " - ratings.#{key} = #{value}"
end
end
end
end
desc "Deletes the public assets installed by the ratings extension."
task :assets => :environment do
puts "Deleting assets installed by the ratings extension..."
Dir[RatingsExtension.root + "/public/**/*"].each do |file|
next if File.directory?(file)
path = file.sub(RatingsExtension.root, '')
if File.exists?(RAILS_ROOT + path) && confirm("Are you sure you want to delete asset #{path}?")
rm RAILS_ROOT + path, :verbose => false
puts " - #{path}"
end
end
end
desc "Deletes the snippets created as part of the ratings installation"
task :snippets => :environment do
puts "Deleting snippets installed by the ratings extension..."
get_yaml('snippets.yml').each do |snippet_name, snippet_content|
if s = Snippet.find_by_name(snippet_name) and confirm("Are you sure you want to delete snippet #{snippet_name}?")
s.destroy
puts " - #{snippet_name}"
end
end
end
end
end
end
end | 42.137681 | 191 | 0.601032 |
ff0c1ca01716a29855a8c74afd58e0d99a296046 | 172 | require 'checkout_system/product'
require 'checkout_system/promotion_rule'
require 'checkout_system/checkout'
module CheckoutSystem
class Error < StandardError; end
end
| 21.5 | 40 | 0.837209 |
62ce8b492d6a4483d6230241fbac069fe72bbff7 | 68 | module OpsWorks
module CLI
VERSION = '0.7.1'.freeze
end
end
| 11.333333 | 28 | 0.661765 |
330ff1852de8d1b90efef4f0db63f25d9ee4e1ec | 238 | class CreateLessons < ActiveRecord::Migration[5.0]
def change
create_table :lessons do |t|
t.string :title
t.string :video_url
t.string :description
t.boolean :published
t.timestamps
end
end
end
| 18.307692 | 50 | 0.651261 |
619cd3ae363da91b75bc3b26290d9b86be2fe5c6 | 1,144 | require 'test_helper'
class ChirpyTest < Test::Unit::TestCase
@@root = "http://twitter.com/"
context "Class methods" do
should "request the public timeline URL" do
assert_equal @@root + "statuses/public_timeline.xml", Chirpy.public_timeline.url
end
should "request the test URL" do
assert_equal @@root + "help/test.xml", Chirpy.test.url
end
should "request a search URL" do
search_term = 'three blind mice'
assert_equal "http://search.twitter.com/search.atom?q=" + CGI.escape(search_term), Chirpy.search(search_term).url
end
end
context "Authenticated user" do
setup do
@username = 'testuser'
@password = 'testpass'
@chirpy = Chirpy.new(@username, @password)
end
should "send authentication in URL" do
assert_equal "https://#{@username}:#{@password}@twitter.com/statuses/user_timeline.xml", @chirpy.user_timeline.url
end
should "not send authentication in URL when specified" do
assert_equal "http://twitter.com/statuses/user_timeline.xml", @chirpy.user_timeline(:authenticate => false).url
end
end
end
| 30.918919 | 120 | 0.674825 |
33e985ac1cd26e5319e73a815f22f35f6212ae06 | 89 | # desc "Explaining what the task does"
# task :healthcheck do
# # Task goes here
# end
| 17.8 | 38 | 0.685393 |
21d4afff9c279307447b83e0f4a4a9bda5262d44 | 712 | require 'json'
package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
Pod::Spec.new do |s|
s.name = 'react-native-camera'
s.version = package['version']
s.summary = package['description']
s.description = package['description']
s.license = package['license']
s.author = package['author']
s.homepage = package['homepage']
s.source = { :git => 'https://github.com/react-native-community/react-native-camera', :tag => s.version }
s.requires_arc = true
s.platform = :ios, '8.0'
s.preserve_paths = 'LICENSE', 'README.md', 'package.json', 'index.js'
s.source_files = 'ios/**/*.{h,m}'
s.dependency 'React'
end
| 30.956522 | 115 | 0.601124 |
91d21cfd8472fd5245775d607600c55e728f0688 | 1,160 | #
# Be sure to run `pod lib lint DLCommonTool.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'DLCommonTool'
s.version = '0.0.6'
s.summary = '常用类'
s.homepage = 'https://github.com/LwqDeveloper/DLCommonTool'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'LwqDeveloper' => '[email protected]' }
s.source = { :git => 'https://github.com/LwqDeveloper/DLCommonTool.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '8.0'
s.source_files = 'DLCommonTool/Classes/**/*'
# s.resource_bundles = {
# 'DLCommonTool' => ['DLCommonTool/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
| 35.151515 | 109 | 0.627586 |
11127fb382a2c080228c4ba17bed92f2049bd106 | 3,263 | #!/usr/bin/ruby -w
# -*- ruby -*-
require 'riel/text'
#
# = string.rb
#
# RIEL extensions to the Ruby String class.
#
# Author:: Jeff Pace <[email protected]>
# Documentation:: Author
#
class String
#
# Returns whether the string ends with the given substring.
#
def ends_with(substr)
return rindex(substr) == (length - substr.length)
end
#
# Returns the string, as a number if it is one, and nil otherwise,
#
def num
begin
Integer(self)
rescue ArgumentError => ae
nil
end
end
#
# Returns a string based on this instance, with the first occurrance of
# +other+ removed. +other+ may be a string or regular expression.
#
def -(other)
sub(other, '')
end
#
# Represents infinity, for the +to_ranges+ function.
#
Infinity = (1.0 / 0)
# :stopdoc:
# from (maybe to this)
RANGE_REGEXP = %r{^ \s* (\d*) (?: \s* (\-|\.\.) \s* (\d*) )? \s* $ }x
# :startdoc:
#
# A class method for +to_ranges+. Deprecated in favor of the instance method.
#
def self.to_ranges(str, args = Hash.new)
str.to_ranges(args)
end
#
# Splits num into array of ranges, limiting itself to +args[:min]+ and +args[:max]+,
# if specified. The +args[:collapse]+, if true, results in sequential values put
# into the same range.
#
# Examples:
#
# "1,2".to_ranges # [ 1 .. 1, 2 .. 2 ]
# "1,2".to_ranges :collapse => true # [ 1 .. 2 ]
# "1-4".to_ranges # [ 1 .. 4 ]
# "1-3,5-6,10,11,12,".to_ranges :collapse => true # [ 1 .. 3, 5 .. 6, 10 .. 12 ]
# "1-3,5-6,10,11,12,".to_ranges # [ 1 .. 3, 5 .. 6, 10 .. 10, 11 .. 11, 12 .. 12 ]
# "-4".to_ranges # [ -String::Infinity .. 4 ]
# "4-".to_ranges # [ 4 .. String::Infinity ]
# "1-".to_ranges :min => 0, :max => 8 # [ 1 .. 8 ]
#
def to_ranges(args = Hash.new)
min = args[:min] || -Infinity
max = args[:max] || Infinity
collapse = args[:collapse]
ranges = Array.new
self.split(%r{\s*,\s*}).each do |section|
md = section.match(RANGE_REGEXP)
next unless md
from = String._matchdata_to_number(md, 1, min)
to = String._has_matchdata?(md, 2) ? String._matchdata_to_number(md, 3, max) : from
prevrange = ranges[-1]
if collapse && prevrange && prevrange.include?(from - 1) && prevrange.include?(to - 1)
ranges[-1] = (prevrange.first .. to)
else
ranges << (from .. to)
end
end
ranges
end
# :stopdoc:
HIGHLIGHTER = ::Text::ANSIHighlighter.new
# :startdoc:
#
# Returns a highlighted (colored) version of the string, applying the regular
# expressions in the array, which are paired with the desired color.
#
def highlight(re, color)
gsub(re) do |match|
HIGHLIGHTER.color(color, match)
end
end
# :stopdoc:
def self._has_matchdata?(md, idx)
md && md[idx] && !md[idx].empty?
end
def self._matchdata_to_number(md, idx, default)
_has_matchdata?(md, idx) ? md[idx].to_i : default
end
# :startdoc:
end
| 25.896825 | 107 | 0.539994 |
281fab0b869396661f322a91492c82c0a1af1a06 | 4,780 | # Cloud Foundry Java Buildpack
# Copyright 2013-2017 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
require 'component_helper'
require 'fileutils'
require 'java_buildpack/container/tomcat'
require 'java_buildpack/container/tomcat/tomcat_access_logging_support'
require 'java_buildpack/container/tomcat/tomcat_geode_store'
require 'java_buildpack/container/tomcat/tomcat_insight_support'
require 'java_buildpack/container/tomcat/tomcat_instance'
require 'java_buildpack/container/tomcat/tomcat_lifecycle_support'
require 'java_buildpack/container/tomcat/tomcat_logging_support'
require 'java_buildpack/container/tomcat/tomcat_redis_store'
describe JavaBuildpack::Container::Tomcat do
include_context 'component_helper'
let(:component) { StubTomcat.new context }
let(:configuration) do
{ 'access_logging_support' => access_logging_support_configuration,
'external_configuration' => tomcat_external_configuration,
'geode_store' => geode_store_configuration,
'lifecycle_support' => lifecycle_support_configuration,
'logging_support' => logging_support_configuration,
'redis_store' => redis_store_configuration,
'tomcat' => tomcat_configuration }
end
let(:access_logging_support_configuration) { instance_double('logging-support-configuration') }
let(:lifecycle_support_configuration) { instance_double('lifecycle-support-configuration') }
let(:logging_support_configuration) { instance_double('logging-support-configuration') }
let(:geode_store_configuration) { instance_double('geode_store_configuration') }
let(:redis_store_configuration) { instance_double('redis-store-configuration') }
let(:tomcat_configuration) { { 'external_configuration_enabled' => false } }
let(:tomcat_external_configuration) { instance_double('tomcat_external_configuration') }
it 'detects WEB-INF',
app_fixture: 'container_tomcat' do
expect(component.supports?).to be
end
it 'does not detect when WEB-INF is absent',
app_fixture: 'container_main' do
expect(component.supports?).not_to be
end
it 'does not detect when WEB-INF is present in a Java main application',
app_fixture: 'container_main_with_web_inf' do
expect(component.supports?).not_to be
end
it 'creates submodules' do
allow(JavaBuildpack::Container::TomcatAccessLoggingSupport)
.to receive(:new).with(sub_configuration_context(access_logging_support_configuration))
allow(JavaBuildpack::Container::TomcatGeodeStore)
.to receive(:new).with(sub_configuration_context(geode_store_configuration))
allow(JavaBuildpack::Container::TomcatInstance)
.to receive(:new).with(sub_configuration_context(tomcat_configuration))
allow(JavaBuildpack::Container::TomcatInsightSupport).to receive(:new).with(context)
allow(JavaBuildpack::Container::TomcatLifecycleSupport)
.to receive(:new).with(sub_configuration_context(lifecycle_support_configuration))
allow(JavaBuildpack::Container::TomcatLoggingSupport)
.to receive(:new).with(sub_configuration_context(logging_support_configuration))
allow(JavaBuildpack::Container::TomcatRedisStore)
.to receive(:new).with(sub_configuration_context(redis_store_configuration))
component.sub_components context
end
it 'returns command' do
expect(component.command).to eq("test-var-2 test-var-1 #{java_home.as_env_var} JAVA_OPTS=\"test-opt-2 " \
'test-opt-1 -Dhttp.port=$PORT" exec $PWD/.java-buildpack/tomcat/bin/catalina.sh' \
' run')
end
context do
let(:tomcat_configuration) { { 'external_configuration_enabled' => true } }
it 'creates submodule TomcatExternalConfiguration' do
allow(JavaBuildpack::Container::TomcatExternalConfiguration)
.to receive(:new).with(sub_configuration_context(tomcat_external_configuration))
component.sub_components context
end
end
end
class StubTomcat < JavaBuildpack::Container::Tomcat
public :command, :sub_components, :supports?
end
def sub_configuration_context(configuration)
c = context.clone
c[:configuration] = configuration
c
end
| 38.548387 | 120 | 0.755858 |
790e03718650c03fcb8d2ea4f3e4674effb64964 | 21,929 | # assert_select plugins for Rails
#
# Copyright (c) 2006 Assaf Arkin, under Creative Commons Attribution and/or MIT License
# Developed for http://co.mments.com
# Code and documention: http://labnotes.org
unless defined?(RAILS_ROOT)
RAILS_ROOT = ENV["RAILS_ROOT"]
end
require File.join(RAILS_ROOT, "test", "test_helper")
require File.join(File.dirname(__FILE__), "..", "init")
class SelectorTest < Test::Unit::TestCase
def setup
end
def teardown
end
#
# Basic selector: element, id, class, attributes.
#
def test_element
parse(%Q{<div id="1"></div><p></p><div id="2"></div>})
# Match element by name.
select("div")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "2", @matches[1].attributes["id"]
# Not case sensitive.
select("DIV")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "2", @matches[1].attributes["id"]
# Universal match (all elements).
select("*")
assert_equal 3, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal nil, @matches[1].attributes["id"]
assert_equal "2", @matches[2].attributes["id"]
end
def test_identifier
parse(%Q{<div id="1"></div><p></p><div id="2"></div>})
# Match element by ID.
select("div#1")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
# Match element by ID, substitute value.
select("div#?", 2)
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
# Element name does not match ID.
select("p#?", 2)
assert_equal 0, @matches.size
# Use regular expression.
select("#?", /\d/)
assert_equal 2, @matches.size
end
def test_class_name
parse(%Q{<div id="1" class=" foo "></div><p id="2" class=" foo bar "></p><div id="3" class="bar"></div>})
# Match element with specified class.
select("div.foo")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
# Match any element with specified class.
select("*.foo")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "2", @matches[1].attributes["id"]
# Match elements with other class.
select("*.bar")
assert_equal 2, @matches.size
assert_equal "2", @matches[0].attributes["id"]
assert_equal "3", @matches[1].attributes["id"]
# Match only element with both class names.
select("*.bar.foo")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
end
def test_attribute
parse(%Q{<div id="1"></div><p id="2" title="" bar="foo"></p><div id="3" title="foo"></div>})
# Match element with attribute.
select("div[title]")
assert_equal 1, @matches.size
assert_equal "3", @matches[0].attributes["id"]
# Match any element with attribute.
select("*[title]")
assert_equal 2, @matches.size
assert_equal "2", @matches[0].attributes["id"]
assert_equal "3", @matches[1].attributes["id"]
# Match alement with attribute value.
select("*[title=foo]")
assert_equal 1, @matches.size
assert_equal "3", @matches[0].attributes["id"]
# Match alement with attribute and attribute value.
select("[bar=foo][title]")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
# Not case sensitive.
select("[BAR=foo][TiTle]")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
end
def test_attribute_quoted
parse(%Q{<div id="1" title="foo"></div><div id="2" title="bar"></div><div id="3" title=" bar "></div>})
# Match without quotes.
select("[title = bar]")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
# Match with single quotes.
select("[title = 'bar' ]")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
# Match with double quotes.
select("[title = \"bar\" ]")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
# Match with spaces.
select("[title = \" bar \" ]")
assert_equal 1, @matches.size
assert_equal "3", @matches[0].attributes["id"]
end
def test_attribute_equality
parse(%Q{<div id="1" title="foo bar"></div><div id="2" title="barbaz"></div>})
# Match (fail) complete value.
select("[title=bar]")
assert_equal 0, @matches.size
# Match space-separate word.
select("[title~=foo]")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
select("[title~=bar]")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
# Match beginning of value.
select("[title^=ba]")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
# Match end of value.
select("[title$=ar]")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
# Match text in value.
select("[title*=bar]")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "2", @matches[1].attributes["id"]
# Match first space separated word.
select("[title|=foo]")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
select("[title|=bar]")
assert_equal 0, @matches.size
end
#
# Selector composition: groups, sibling, children
#
def test_selector_group
parse(%Q{<h1 id="1"></h1><h2 id="2"></h2><h3 id="3"></h3>})
# Simple group selector.
select("h1,h3")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "3", @matches[1].attributes["id"]
select("h1 , h3")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "3", @matches[1].attributes["id"]
# Complex group selector.
parse(%Q{<h1 id="1"><a href="foo"></a></h1><h2 id="2"><a href="bar"></a></h2><h3 id="2"><a href="baz"></a></h3>})
select("h1 a, h3 a")
assert_equal 2, @matches.size
assert_equal "foo", @matches[0].attributes["href"]
assert_equal "baz", @matches[1].attributes["href"]
# And now for the three selector challange.
parse(%Q{<h1 id="1"><a href="foo"></a></h1><h2 id="2"><a href="bar"></a></h2><h3 id="2"><a href="baz"></a></h3>})
select("h1 a, h2 a, h3 a")
assert_equal 3, @matches.size
assert_equal "foo", @matches[0].attributes["href"]
assert_equal "bar", @matches[1].attributes["href"]
assert_equal "baz", @matches[2].attributes["href"]
end
def test_sibling_selector
parse(%Q{<h1 id="1"></h1><h2 id="2"></h2><h3 id="3"></h3>})
# Test next sibling.
select("h1+*")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
select("h1+h2")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
select("h1+h3")
assert_equal 0, @matches.size
select("*+h3")
assert_equal 1, @matches.size
assert_equal "3", @matches[0].attributes["id"]
# Test any sibling.
select("h1~*")
assert_equal 2, @matches.size
assert_equal "2", @matches[0].attributes["id"]
assert_equal "3", @matches[1].attributes["id"]
select("h2~*")
assert_equal 1, @matches.size
assert_equal "3", @matches[0].attributes["id"]
end
def test_children_selector
parse(%Q{<div><p id="1"><span id="2"></span></p></div><div><p id="3"><span id="4" class="foo"></span></p></div>})
# Test child selector.
select("div>p")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "3", @matches[1].attributes["id"]
select("div>span")
assert_equal 0, @matches.size
select("div>p#3")
assert_equal 1, @matches.size
assert_equal "3", @matches[0].attributes["id"]
select("div>p>span")
assert_equal 2, @matches.size
assert_equal "2", @matches[0].attributes["id"]
assert_equal "4", @matches[1].attributes["id"]
# Test descendant selector.
select("div p")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "3", @matches[1].attributes["id"]
select("div span")
assert_equal 2, @matches.size
assert_equal "2", @matches[0].attributes["id"]
assert_equal "4", @matches[1].attributes["id"]
select("div *#3")
assert_equal 1, @matches.size
assert_equal "3", @matches[0].attributes["id"]
select("div *#4")
assert_equal 1, @matches.size
assert_equal "4", @matches[0].attributes["id"]
# This is here because it failed before when whitespaces
# were not properly stripped.
select("div .foo")
assert_equal 1, @matches.size
assert_equal "4", @matches[0].attributes["id"]
end
#
# Pseudo selectors: root, nth-child, empty, content, etc
#
def test_root_selector
parse(%Q{<div id="1"><div id="2"></div></div>})
# Can only find element if it's root.
select(":root")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
select("#1:root")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
select("#2:root")
assert_equal 0, @matches.size
# Opposite for nth-child.
select("#1:nth-child(1)")
assert_equal 0, @matches.size
end
def test_nth_child_odd_even
parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
# Test odd nth children.
select("tr:nth-child(odd)")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "3", @matches[1].attributes["id"]
# Test even nth children.
select("tr:nth-child(even)")
assert_equal 2, @matches.size
assert_equal "2", @matches[0].attributes["id"]
assert_equal "4", @matches[1].attributes["id"]
end
def test_nth_child_a_is_zero
parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
# Test the third child.
select("tr:nth-child(0n+3)")
assert_equal 1, @matches.size
assert_equal "3", @matches[0].attributes["id"]
# Same but an can be omitted when zero.
select("tr:nth-child(3)")
assert_equal 1, @matches.size
assert_equal "3", @matches[0].attributes["id"]
# Second element (but not every second element).
select("tr:nth-child(0n+2)")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
# Before first and past last returns nothing.:
assert_raises(ArgumentError) { select("tr:nth-child(-1)") }
select("tr:nth-child(0)")
assert_equal 0, @matches.size
select("tr:nth-child(5)")
assert_equal 0, @matches.size
end
def test_nth_child_a_is_one
parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
# a is group of one, pick every element in group.
select("tr:nth-child(1n+0)")
assert_equal 4, @matches.size
# Same but a can be omitted when one.
select("tr:nth-child(n+0)")
assert_equal 4, @matches.size
# Same but b can be omitted when zero.
select("tr:nth-child(n)")
assert_equal 4, @matches.size
end
def test_nth_child_b_is_zero
parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
# If b is zero, pick the n-th element (here each one).
select("tr:nth-child(n+0)")
assert_equal 4, @matches.size
# If b is zero, pick the n-th element (here every second).
select("tr:nth-child(2n+0)")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "3", @matches[1].attributes["id"]
# If a and b are both zero, no element selected.
select("tr:nth-child(0n+0)")
assert_equal 0, @matches.size
select("tr:nth-child(0)")
assert_equal 0, @matches.size
end
def test_nth_child_a_is_negative
parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
# Since a is -1, picks the first three elements.
select("tr:nth-child(-n+3)")
assert_equal 3, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "2", @matches[1].attributes["id"]
assert_equal "3", @matches[2].attributes["id"]
# Since a is -2, picks the first in every second of first four elements.
select("tr:nth-child(-2n+3)")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "3", @matches[1].attributes["id"]
# Since a is -2, picks the first in every second of first three elements.
select("tr:nth-child(-2n+2)")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
end
def test_nth_child_b_is_negative
parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
# Select last of four.
select("tr:nth-child(4n-1)")
assert_equal 1, @matches.size
assert_equal "4", @matches[0].attributes["id"]
# Select first of four.
select("tr:nth-child(4n-4)")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
# Select last of every second.
select("tr:nth-child(2n-1)")
assert_equal 2, @matches.size
assert_equal "2", @matches[0].attributes["id"]
assert_equal "4", @matches[1].attributes["id"]
# Select nothing since an+b always < 0
select("tr:nth-child(-1n-1)")
assert_equal 0, @matches.size
end
def test_nth_child_substitution_values
parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
# Test with ?n?.
select("tr:nth-child(?n?)", 2, 1)
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "3", @matches[1].attributes["id"]
select("tr:nth-child(?n?)", 2, 2)
assert_equal 2, @matches.size
assert_equal "2", @matches[0].attributes["id"]
assert_equal "4", @matches[1].attributes["id"]
select("tr:nth-child(?n?)", 4, 2)
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
# Test with ? (b only).
select("tr:nth-child(?)", 3)
assert_equal 1, @matches.size
assert_equal "3", @matches[0].attributes["id"]
select("tr:nth-child(?)", 5)
assert_equal 0, @matches.size
end
def test_nth_last_child
parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
# Last two elements.
select("tr:nth-last-child(-n+2)")
assert_equal 2, @matches.size
assert_equal "3", @matches[0].attributes["id"]
assert_equal "4", @matches[1].attributes["id"]
# All old elements counting from last one.
select("tr:nth-last-child(odd)")
assert_equal 2, @matches.size
assert_equal "2", @matches[0].attributes["id"]
assert_equal "4", @matches[1].attributes["id"]
end
def test_nth_of_type
parse(%Q{<table><thead></thead><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
# First two elements.
select("tr:nth-of-type(-n+2)")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "2", @matches[1].attributes["id"]
# All old elements counting from last one.
select("tr:nth-last-of-type(odd)")
assert_equal 2, @matches.size
assert_equal "2", @matches[0].attributes["id"]
assert_equal "4", @matches[1].attributes["id"]
end
def test_first_and_last
parse(%Q{<table><thead></thead><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
# First child.
select("tr:first-child")
assert_equal 0, @matches.size
select(":first-child")
assert_equal 1, @matches.size
assert_equal "thead", @matches[0].name
# First of type.
select("tr:first-of-type")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
select("thead:first-of-type")
assert_equal 1, @matches.size
assert_equal "thead", @matches[0].name
select("div:first-of-type")
assert_equal 0, @matches.size
# Last child.
select("tr:last-child")
assert_equal 1, @matches.size
assert_equal "4", @matches[0].attributes["id"]
# Last of type.
select("tr:last-of-type")
assert_equal 1, @matches.size
assert_equal "4", @matches[0].attributes["id"]
select("thead:last-of-type")
assert_equal 1, @matches.size
assert_equal "thead", @matches[0].name
select("div:last-of-type")
assert_equal 0, @matches.size
end
def test_first_and_last
# Only child.
parse(%Q{<table><tr></tr></table>})
select("table:only-child")
assert_equal 0, @matches.size
select("tr:only-child")
assert_equal 1, @matches.size
assert_equal "tr", @matches[0].name
parse(%Q{<table><tr></tr><tr></tr></table>})
select("tr:only-child")
assert_equal 0, @matches.size
# Only of type.
parse(%Q{<table><thead></thead><tr></tr><tr></tr></table>})
select("thead:only-of-type")
assert_equal 1, @matches.size
assert_equal "thead", @matches[0].name
select("td:only-of-type")
assert_equal 0, @matches.size
end
def test_empty
parse(%Q{<table><tr></tr></table>})
select("table:empty")
assert_equal 0, @matches.size
select("tr:empty")
assert_equal 1, @matches.size
parse(%Q{<div> </div>})
select("div:empty")
assert_equal 1, @matches.size
end
def test_content
parse(%Q{<div> </div>})
select("div:content()")
assert_equal 1, @matches.size
parse(%Q{<div>something </div>})
select("div:content()")
assert_equal 0, @matches.size
select("div:content(something)")
assert_equal 1, @matches.size
select("div:content( 'something' )")
assert_equal 1, @matches.size
select("div:content( \"something\" )")
assert_equal 1, @matches.size
select("div:content(?)", "something")
assert_equal 1, @matches.size
select("div:content(?)", /something/)
assert_equal 1, @matches.size
end
#
# Test negation.
#
def test_element_negation
parse(%Q{<p></p><div></div>})
select("*")
assert_equal 2, @matches.size
select("*:not(p)")
assert_equal 1, @matches.size
assert_equal "div", @matches[0].name
select("*:not(div)")
assert_equal 1, @matches.size
assert_equal "p", @matches[0].name
select("*:not(span)")
assert_equal 2, @matches.size
end
def test_id_negation
parse(%Q{<p id="1"></p><p id="2"></p>})
select("p")
assert_equal 2, @matches.size
select(":not(#1)")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
select(":not(#2)")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
end
def test_class_name_negation
parse(%Q{<p class="foo"></p><p class="bar"></p>})
select("p")
assert_equal 2, @matches.size
select(":not(.foo)")
assert_equal 1, @matches.size
assert_equal "bar", @matches[0].attributes["class"]
select(":not(.bar)")
assert_equal 1, @matches.size
assert_equal "foo", @matches[0].attributes["class"]
end
def test_attribute_negation
parse(%Q{<p title="foo"></p><p title="bar"></p>})
select("p")
assert_equal 2, @matches.size
select(":not([title=foo])")
assert_equal 1, @matches.size
assert_equal "bar", @matches[0].attributes["title"]
select(":not([title=bar])")
assert_equal 1, @matches.size
assert_equal "foo", @matches[0].attributes["title"]
end
def test_pseudo_class_negation
parse(%Q{<div><p id="1"></p><p id="2"></p></div>})
select("p")
assert_equal 2, @matches.size
select("p:not(:first-child)")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
select("p:not(:nth-child(2))")
assert_equal 1, @matches.size
assert_equal "1", @matches[0].attributes["id"]
end
def test_negation_details
parse(%Q{<p id="1"></p><p id="2"></p><p id="3"></p>})
assert_raises(ArgumentError) { select(":not(") }
assert_raises(ArgumentError) { select(":not(:not())") }
select("p:not(#1):not(#3)")
assert_equal 1, @matches.size
assert_equal "2", @matches[0].attributes["id"]
end
def test_select_from_element
parse(%Q{<div><p id="1"></p><p id="2"></p></div>})
select("div")
@matches = @matches[0].select("p")
assert_equal 2, @matches.size
assert_equal "1", @matches[0].attributes["id"]
assert_equal "2", @matches[1].attributes["id"]
end
#
# Test Node.select
#
def test_node_select
html = HTML::Document.new(%Q{<div id="1"></div><p></p><div id="2"></div>})
matches = html.select("div")
assert_equal 2, matches.size
assert_equal "1", matches[0].attributes["id"]
assert_equal "2", matches[1].attributes["id"]
matches = matches[0].select("div")
assert_equal 1, matches.size
assert_equal "1", matches[0].attributes["id"]
matches = html.select("#1")
assert_equal 1, matches.size
assert_equal "1", matches[0].attributes["id"]
end
def test_node_select_first
html = HTML::Document.new(%Q{<div id="1"></div><p></p><div id="2"></div>})
matches = html.select(:all, "div")
assert_equal 2, matches.size
assert_equal "1", matches[0].attributes["id"]
assert_equal "2", matches[1].attributes["id"]
matches = html.root.select(:all, "div")
assert_equal 2, matches.size
assert_equal "1", matches[0].attributes["id"]
assert_equal "2", matches[1].attributes["id"]
match = html.select(:first, "div")
assert_equal "1", match.attributes["id"]
match = html.root.select(:first, "div")
assert_equal "1", match.attributes["id"]
end
protected
def parse(html)
@html = HTML::Document.new(html).root
end
def select(*selector)
@matches = HTML.selector(*selector).select(@html)
end
end
| 32.296024 | 117 | 0.626476 |
e29bcb225e3166a33ed1abffa79715cecedede4e | 586 | require 'cancancan'
require 'kaminari'
require 'jquery-rails'
require 'carrierwave'
require 'mini_magick'
require 'closure_tree'
require 'optimadmin/presenter_methods'
module Optimadmin
class Engine < ::Rails::Engine
config.generators do |g|
g.test_framework :rspec, fixture: false
g.fixture_replacement :factory_girl, dir: 'spec/factories'
g.assets false
g.helper false
end
isolate_namespace Optimadmin
initializer 'optimadmin.assets.precompile' do |app|
app.config.assets.precompile += %w( optimadmin/modernizr.js )
end
end
end
| 24.416667 | 67 | 0.728669 |
abe598077bd782fc70dd6e71bdeabaaa192ea3ab | 2,605 | # Copyright © 2011 MUSC Foundation for Research Development
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
# BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
require 'spec_helper'
feature 'super users' do
background do
default_catalog_manager_setup
end
scenario 'user adds a new super user to institution', :js => true do
add_super_user
within "#su_info" do
page.should have_text("Julia Glenn ([email protected])")
end
end
scenario 'user deletes a super user from institution', :js => true do
add_super_user
within "#su_info" do
find("img.su_delete").click
end
a = page.driver.browser.switch_to.alert
a.text.should eq "Are you sure you want to remove this Super User?"
a.accept
within "#su_info" do
page.should_not have_text("Julia Glenn")
end
end
end
def add_super_user
wait_for_javascript_to_finish
click_link('Office of Biomedical Informatics')
within '#user_rights' do
find('.legend').click
wait_for_javascript_to_finish
end
sleep 3
fill_in "new_su", :with => "Julia"
wait_for_javascript_to_finish
page.find('a', :text => "Julia Glenn", :visible => true).click()
wait_for_javascript_to_finish
end | 38.880597 | 145 | 0.758157 |
1de8cdb2887f3c79f08e6b6bc59a7525e842f292 | 1,122 | # frozen_string_literal: true
class BlueprintsBoy::BlueprintBuilder
def initialize(blueprint, environment, strategy, options)
@environment = environment
@name = blueprint.name
@factory = blueprint.factory_class
@options = options
@attributes = normalize_attributes(blueprint).merge(options)
@strategy = blueprint.strategies[strategy]
@strategy ||= BlueprintsBoy.factories[blueprint.factory_class, strategy] if blueprint.factory_class
fail BlueprintsBoy::StrategyNotFound, "Blueprint #{@name.inspect} does not define strategy #{strategy.inspect}" unless @strategy
end
def build
required = @strategy.parameters.select { |key, _| key == :keyreq }
.map { |_, name| [name, instance_variable_get("@#{name}")] }.to_h
@environment.autoset @name, @environment.instance_exec(**required, &@strategy)
end
private
def normalize_attributes(blueprint)
blueprint.attributes.transform_values do |value|
case value
when BlueprintsBoy::Dependency
@environment.instance_eval(&value)
else
value
end
end
end
end
| 31.166667 | 132 | 0.704991 |
3876a656ee7c0dd38d306340e0fa46bd10556b23 | 5,023 | require 'open3'
require 'fileutils'
require 'socket'
require 'capybara'
require 'selenium-webdriver'
require 'capybara/webmock/version'
require 'capybara/webmock/proxy'
require 'capybara/webmock/proxied_request'
module Capybara
module Webmock
class << self
attr_accessor :port_number, :pid_file, :kill_timeout, :start_timeout
def start(options = {})
if @pid.nil?
kill_old_process
gem_path = File.dirname(__FILE__)
proxy_file = File.join(gem_path, 'webmock', 'config.ru')
stdin, stdout, wait_thr = Open3.popen2e(
{
"PROXY_PORT_NUMBER" => port_number.to_s,
"PROXY_ALLOWED_HOSTS" => options[:allowed_hosts]
},
"rackup",
proxy_file
)
stdin.close
@stdout = stdout
@pid = wait_thr[:pid]
write_pid_file
wait_for_proxy_start
end
reset
end
def reset
get_output_nonblocking
@output_buf = ""
end
def proxied_requests
@output_buf += get_output_nonblocking
matches = @output_buf.sub(/\n[^\n]+\z/, '').split("\n").map do |line|
match = /\A(.+) -> (.+)\Z/.match(line)
next nil unless match
match.captures
end
matches.compact.map{ |raw_referrer, raw_uri| ProxiedRequest.new(raw_referrer, raw_uri) }
end
def stop
return if @pid.nil?
@stdout.close
kill_process(@pid)
remove_pid_file
@pid = nil
@stdout = nil
end
def firefox_profile
proxy_host = '127.0.0.1'
profile = ::Selenium::WebDriver::Firefox::Profile.new
profile["network.proxy.type"] = 1
profile["network.proxy.http"] = proxy_host
profile["network.proxy.http_port"] = port_number
profile["network.proxy.ssl"] = proxy_host
profile["network.proxy.ssl_port"] = port_number
profile
end
def chrome_options
::Selenium::WebDriver::Chrome::Options.new.tap do |options|
options.add_argument "--proxy-server=127.0.0.1:#{port_number}"
end
end
def chrome_headless_options
chrome_options.tap { |options| options.headless! }
end
def phantomjs_options
["--proxy=127.0.0.1:#{port_number}"]
end
private
def wait_for_proxy_start
connected = false
(1..start_timeout).each do
begin
Socket.tcp("127.0.0.1", port_number, connect_timeout: 1) {}
connected = true
break
rescue => e
sleep 1
end
end
unless connected
raise "Unable to connect to capybara-webmock proxy on #{port_number}"
end
end
def get_output_nonblocking
buf = ""
while true
begin
output = @stdout.read_nonblock(1024)
break if output == ""
buf += output
rescue IO::WaitReadable
break
end
end
buf
end
def kill_old_process
return unless File.exists?(pid_file)
old_pid = File.read(pid_file).to_i
kill_process(old_pid) if old_pid > 1
remove_pid_file
end
def kill_process(pid)
Process.kill('HUP', pid) if process_alive?(pid)
(1..kill_timeout).each do
sleep(1) if process_alive?(pid)
end
Process.kill('KILL', pid) if process_alive?(pid)
(1..kill_timeout).each do
sleep(1) if process_alive?(pid)
end
if process_alive?(pid)
raise "Unable to kill capybara-webmock process with PID #{pid}"
end
end
def process_alive?(pid)
!!Process.kill(0, pid) rescue false
end
def write_pid_file
raise "Pid file #{pid_file} already exists" if File.exists?(pid_file)
FileUtils.mkdir_p(File.dirname(pid_file))
File.write(pid_file, @pid.to_s)
end
def remove_pid_file
File.delete(pid_file) if File.exists?(pid_file)
end
end
end
end
Capybara::Webmock.port_number ||= 9292
Capybara::Webmock.pid_file ||= File.join('tmp', 'pids', 'capybara_webmock_proxy.pid')
Capybara::Webmock.kill_timeout ||= 5
Capybara::Webmock.start_timeout ||= 30
Capybara.register_driver :capybara_webmock do |app|
Capybara::Selenium::Driver.new(app, browser: :firefox, profile: Capybara::Webmock.firefox_profile)
end
Capybara.register_driver :capybara_webmock_chrome do |app|
Capybara::Selenium::Driver.new(app, browser: :chrome, options: Capybara::Webmock.chrome_options)
end
Capybara.register_driver :capybara_webmock_chrome_headless do |app|
Capybara::Selenium::Driver.new(app, browser: :chrome, options: Capybara::Webmock.chrome_headless_options)
end
Capybara.register_driver :capybara_webmock_poltergeist do |app|
Capybara::Poltergeist::Driver.new(app, phantomjs_options: Capybara::Webmock.phantomjs_options)
end
| 26.718085 | 107 | 0.609795 |
91eaff9fecf57b0b30fbe759015104fa3e0f3141 | 912 | class N < Formula
desc "Node version management"
homepage "https://github.com/tj/n"
url "https://github.com/tj/n/archive/v7.0.1.tar.gz"
sha256 "33d210287c7a3752135560f743cdc2d944048986f757c3ac1db6e738e01b7ebf"
license "MIT"
head "https://github.com/tj/n.git"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "67abc6b90563433086f1ee8579175828270501c6247497254aab6aba52665429"
sha256 cellar: :any_skip_relocation, big_sur: "9acfff0beb0b3f16c4d5ce59aeec0d62d69020f9dd2dc3457f65fd56be640e60"
sha256 cellar: :any_skip_relocation, catalina: "f21d5d3400bf1675f9b361491a7cc33d2edf779836f2e7d99454e0e8cc185c18"
sha256 cellar: :any_skip_relocation, mojave: "371646873ae44abe06dfe6637cac561b10c490be8326e6d77006da52cf50c54b"
end
def install
bin.mkdir
system "make", "PREFIX=#{prefix}", "install"
end
test do
system bin/"n", "ls"
end
end
| 36.48 | 122 | 0.769737 |
21a73da086dbdc2a1a7ea477cee56a140a7278b6 | 4,925 | require 'date'
require File.expand_path('../../../spec_helper', __FILE__)
describe "Date#strptime" do
it "returns January 1, 4713 BCE when given no arguments" do
Date.strptime.should == Date.civil(-4712, 1, 1)
end
it "uses the default format when not given a date format" do
Date.strptime("2000-04-06").should == Date.civil(2000, 4, 6)
Date.civil(2000, 4, 6).strftime.should == Date.civil(2000, 4, 6).to_s
end
it "parses a full day name" do
d = Date.today
expected_date = Date.commercial(d.cwyear, d.cweek, 4)
# strptime assumed week that start on sunday, not monday
expected_date += 7 if d.cwday == 7
Date.strptime("Thursday", "%A").should == expected_date
end
it "parses a short day name" do
d = Date.today
expected_date = Date.commercial(d.cwyear, d.cweek, 4)
# strptime assumed week that start on sunday, not monday
expected_date += 7 if d.cwday == 7
Date.strptime("Thu", "%a").should == expected_date
end
it "parses a full month name" do
d = Date.today
Date.strptime("April", "%B").should == Date.civil(d.year, 4, 1)
end
it "parses a short month name" do
d = Date.today
Date.strptime("Apr", "%b").should == Date.civil(d.year, 4, 1)
Date.strptime("Apr", "%h").should == Date.civil(d.year, 4, 1)
end
it "parses a century" do
Date.strptime("06 20", "%y %C").should == Date.civil(2006, 1, 1)
end
it "parses a month day with leading zeroes" do
d = Date.today
Date.strptime("06", "%d").should == Date.civil(d.year, d.month, 6)
end
it "parses a month day with leading spaces" do
d = Date.today
Date.strptime(" 6", "%e").should == Date.civil(d.year, d.month, 6)
end
it "parses a commercial year with leading zeroes" do
Date.strptime("2000", "%G").should == Date.civil(2000, 1, 3)
Date.strptime("2002", "%G").should == Date.civil(2001, 12, 31)
end
it "parses a commercial year with only two digits" do
Date.strptime("68", "%g").should == Date.civil(2068, 1, 2)
Date.strptime("69", "%g").should == Date.civil(1968, 12, 30)
end
it "parses a year day with leading zeroes" do
d = Date.today
if Date.gregorian_leap?(Date.today.year)
Date.strptime("097", "%j").should == Date.civil(d.year, 4, 6)
else
Date.strptime("097", "%j").should == Date.civil(d.year, 4, 7)
end
end
it "parses a month with leading zeroes" do
d = Date.today
Date.strptime("04", "%m").should == Date.civil(d.year, 4, 1)
end
it "parses a week number for a week starting on Sunday" do
Date.strptime("2010/1", "%Y/%U").should == Date.civil(2010, 1, 3)
end
# See http://redmine.ruby-lang.org/repositories/diff/ruby-19?rev=24500
it "parses a week number for a week starting on Monday" do
Date.strptime("2010/1", "%Y/%W").should == Date.civil(2010, 1, 4)
end
it "parses a commercial week day" do
Date.strptime("2008 1", "%G %u").should == Date.civil(2007, 12, 31)
end
it "parses a commercial week" do
d = Date.commercial(Date.today.cwyear,1,1)
Date.strptime("1", "%V").should == d
Date.strptime("15", "%V").should == Date.commercial(d.cwyear, 15, 1)
end
it "parses a week day" do
Date.strptime("2007 4", "%Y %w").should == Date.civil(2007, 1, 4)
end
it "parses a year in YYYY format" do
Date.strptime("2007", "%Y").should == Date.civil(2007, 1, 1)
end
it "parses a year in YY format" do
Date.strptime("00", "%y").should == Date.civil(2000, 1, 1)
end
############################
# Specs that combine stuff #
############################
it "parses a full date" do
Date.strptime("Thu Apr 6 00:00:00 2000", "%c").should == Date.civil(2000, 4, 6)
Date.strptime("Thu Apr 6 00:00:00 2000", "%a %b %e %H:%M:%S %Y").should == Date.civil(2000, 4, 6)
end
it "parses a date with slashes" do
Date.strptime("04/06/00", "%D").should == Date.civil(2000, 4, 6)
Date.strptime("04/06/00", "%m/%d/%y").should == Date.civil(2000, 4, 6)
end
it "parses a date given as YYYY-MM-DD" do
Date.strptime("2000-04-06", "%F").should == Date.civil(2000, 4, 6)
Date.strptime("2000-04-06", "%Y-%m-%d").should == Date.civil(2000, 4, 6)
end
it "parses a commercial week" do
Date.strptime(" 9-Apr-2000", "%v").should == Date.civil(2000, 4, 9)
Date.strptime(" 9-Apr-2000", "%e-%b-%Y").should == Date.civil(2000, 4, 9)
end
it "parses a date given MM/DD/YY" do
Date.strptime("04/06/00", "%x").should == Date.civil(2000, 4, 6)
Date.strptime("04/06/00", "%m/%d/%y").should == Date.civil(2000, 4, 6)
end
it "parses a date given in full notation" do
Date.strptime("Sun Apr 9 00:00:00 +00:00 2000", "%+").should == Date.civil(2000, 4, 9)
Date.strptime("Sun Apr 9 00:00:00 +00:00 2000", "%a %b %e %H:%M:%S %Z %Y").should == Date.civil(2000, 4, 9)
end
end
describe "Date.strptime" do
it "needs to be reviewed for spec completeness"
end
| 32.833333 | 112 | 0.614822 |
abe6bf8727f63b7d3f38c89a3c55f8fe97f28684 | 366 | cask 'mountain-duck' do
version '3.3.4.15443'
sha256 '6bfc4235ae7a1e7c8c7901eb0499d78dce0df07cacbd5b952743c9016b6e2703'
url "https://dist.mountainduck.io/Mountain%20Duck-#{version}.zip"
appcast "https://version.mountainduck.io/#{version.major}/macos/changelog.rss"
name 'Mountain Duck'
homepage 'https://mountainduck.io/'
app 'Mountain Duck.app'
end
| 30.5 | 80 | 0.762295 |
1a5285dba7efd774086b0bfa8168e53fc01c57d3 | 877 | require 'spec_helper'
feature 'Add an attached file' do
let(:user) { create(:user) }
let!(:work) { create(:work, user: user) }
before do
sign_in user
# stub out characterization. Travis doesn't have fits installed, and it's not relevant to the test.
allow(CharacterizeJob).to receive(:perform_later)
allow_any_instance_of(CurationConcerns::Actors::FileSetActor).to receive(:acquire_lock_for).and_yield
end
it 'updates the file' do
visit "/concern/generic_works/#{work.id}"
click_link 'Attach a File'
within('form.new_file_set') do
fill_in('Title', with: 'image.png')
attach_file('Upload a file', fixture_file_path('files/image.png'))
click_on('Attach to Generic Work')
end
visit "/concern/generic_works/#{work.id}"
within '.related_files' do
expect(page).to have_link 'image.png'
end
end
end
| 29.233333 | 105 | 0.692132 |
4aacb8f3c86d607dacaca26dab785cf850add17f | 5,283 | require 'test/unit'
require 'marc'
require 'xmlsimple'
def xml_cmp a, b
eq_all_but_zero = Object.new.instance_eval do
def ==(other)
Integer(other) == 0 ? false : true
end
self
end
a = XmlSimple.xml_in(a.to_s, 'normalisespace' => eq_all_but_zero)
b = XmlSimple.xml_in(b.to_s, 'normalisespace' => eq_all_but_zero)
a == b
end
class TestRecord < Test::Unit::TestCase
def test_constructor
r = MARC::Record.new()
assert_equal(r.class, MARC::Record)
end
def test_xml
r = get_record()
doc = r.to_xml
assert_kind_of REXML::Element, doc
assert xml_cmp("<record xmlns='http://www.loc.gov/MARC21/slim'><leader> Z 22 4500</leader><datafield tag='100' ind1='2' ind2='0'><subfield code='a'>Thomas, Dave</subfield></datafield><datafield tag='245' ind1='0' ind2='4'><subfield code='The Pragmatic Programmer'></subfield></datafield></record>", doc.to_s)
end
def test_append_field
r = get_record()
assert_equal(r.fields.length(), 2)
end
def test_iterator
r = get_record()
count = 0
r.each { |f| count += 1 }
assert_equal(count, 2)
end
def test_decode
raw = IO.read('test/one.dat')
r = MARC::Record::new_from_marc(raw)
assert_equal(r.class, MARC::Record)
assert_equal(r.leader, '00755cam 22002414a 4500')
assert_equal(r.fields.length(), 18)
assert_equal(r.find { |f| f.tag == '245' }.to_s,
'245 10 $a ActivePerl with ASP and ADO / $c Tobias Martinsson. ')
end
def test_decode_forgiving
raw = IO.read('test/one.dat')
r = MARC::Record::new_from_marc(raw, :forgiving => true)
assert_equal(r.class, MARC::Record)
assert_equal(r.leader, '00755cam 22002414a 4500')
assert_equal(r.fields.length(), 18)
assert_equal(r.find { |f| f.tag == '245' }.to_s,
'245 10 $a ActivePerl with ASP and ADO / $c Tobias Martinsson. ')
end
def test_encode
r1 = MARC::Record.new()
r1.append(MARC::DataField.new('100', '2', '0', ['a', 'Thomas, Dave']))
r1.append(MARC::DataField.new('245', '0', '0', ['a', 'Pragmatic Programmer']))
raw = r1.to_marc()
r2 = MARC::Record::new_from_marc(raw)
assert_equal(r1, r2)
end
def test_lookup_shorthand
r = get_record
assert_equal(r['100']['a'], 'Thomas, Dave')
end
def get_record
r = MARC::Record.new()
r.append(MARC::DataField.new('100', '2', '0', ['a', 'Thomas, Dave']))
r.append(MARC::DataField.new('245', '0', '4', ['The Pragmatic Programmer']))
return r
end
def test_field_index
raw = IO.read('test/random_tag_order.dat')
r = MARC::Record.new_from_marc(raw)
assert_kind_of(Array, r.fields)
assert_kind_of(Array, r.tags)
assert_equal(['001', '005', '007', '008', '010', '028', '035', '040', '050', '245', '260', '300', '500', '505', '511', '650', '700', '906', '953', '991'], r.tags.sort)
assert_kind_of(Array, r.fields('035'))
raw2 = IO.read('test/random_tag_order2.dat')
r2 = MARC::Record.new_from_marc(raw2)
assert_equal(6, r2.fields('500').length)
# Test passing an array to Record#fields
assert_equal(3, r.fields(['500', '505', '510', '511']).length)
# Test passing a Range to Record#fields
assert_equal(9, r.fields(('001'..'099')).length)
end
def test_field_index_order
raw = IO.read('test/random_tag_order.dat')
r = MARC::Record.new_from_marc(raw)
notes = ['500', '505', '511']
r.fields(('500'..'599')).each do |f|
assert_equal(notes.pop, f.tag)
end
raw2 = IO.read('test/random_tag_order2.dat')
r2 = MARC::Record.new_from_marc(raw2)
fields = ['050', '042', '010', '028', '024', '035', '041', '028', '040', '035', '008', '007', '005', '001']
r2.each_by_tag(('001'..'099')) do |f|
assert_equal(fields.pop, f.tag)
end
five_hundreds = r2.fields('500')
assert_equal(five_hundreds.first['a'], '"Contemporary blues" interpretations of previously released songs; written by Bob Dylan.')
assert_equal(five_hundreds.last['a'], 'Composer and program notes in container.')
end
# Some tests for the internal FieldMap hash, normally
# an implementation detail, but things get tricky and we need
# tests to make sure we're good. Some of these you might
# change if you change FieldMap caching implementation or contract/API.
def test_direct_change_dirties_fieldmap
# if we ask for #fields directly, and mutate it
# with it's own methods, does any cache update?
r = MARC::Record.new
assert r.fields('500').empty?
r.fields.push MARC::DataField.new('500', ' ', ' ', ['a', 'notes'])
assert !r.fields('500').empty?, "New 505 directly added to #fields is picked up"
# Do it again, make sure #[] works too
r = MARC::Record.new
assert r['500'].nil?
r.fields.push MARC::DataField.new('500', ' ', ' ', ['a', 'notes'])
assert r['500'], "New 505 directly added to #fields is picked up"
end
def test_frozen_fieldmap
r = MARC::Record.new
r.fields.push MARC::DataField.new('500', ' ', ' ', ['a', 'notes'])
r.fields.freeze
r.fields.inspect
r.fields
assert !r.fields('500').empty?
assert r.fields.instance_variable_get("@clean"), "FieldMap still marked clean"
end
end
| 33.865385 | 326 | 0.631081 |
035e1faea1db342908f1e77c18ad232652b17a07 | 1,040 | require 'spec_helper.rb'
describe 'rkhunter' do
context 'supported operating systems' do
on_supported_os.each do |os, os_facts|
context "on #{os}" do
let(:facts) { os_facts }
# config is a private class called by init.
#
context 'with default parameters' do
it { is_expected.to create_exec('propupd').with({
:command => 'rkhunter --propupd',
:creates => '/var/lib/rkhunter/db/rkhunter.dat',
:path => ['/bin', '/usr/bin']
})}
it { is_expected.to create_file('/etc/rkhunter.conf').with({
:owner => 'root',
:group => 'root',
:mode => '0640',
:validate_cmd => 'PATH=/sbin:/bin:/usr/sbin:/usr/bin rkhunter -C --configfile %'
})}
expected_content = File.read(File.join(File.dirname(__FILE__),'../files/rkhunter_conf.txt'))
it { is_expected.to create_file('/etc/rkhunter.conf').with_content(expected_content) }
end
end
end
end
end
| 32.5 | 102 | 0.560577 |
f7615ef86664feb5b6a1460eb4549f818c4a731d | 453 | cask "haroopad" do
version "0.13.2"
sha256 "97ef0a7df52daeace17ea01a1ca82dc974955c147593f251fb7c04ca0ff09064"
# bitbucket.org/rhiokim/haroopad-download/ was verified as official when first introduced to the cask
url "https://bitbucket.org/rhiokim/haroopad-download/downloads/Haroopad-v#{version}-x64.dmg"
name "Haroopad"
homepage "http://pad.haroopress.com/"
app "Haroopad.app"
zap trash: "~/Library/Application Support/Haroopad"
end
| 32.357143 | 103 | 0.774834 |
bb2876f067be59ea6d20e83ac702f29a28ce389e | 131 | class Player
attr_accessor :pieces, :name, :color
def initialize(args)
@name = args[:name]
@color = args[:color]
end
end
| 14.555556 | 37 | 0.671756 |
d562bf2480a0c46bc3491fade7c84377031db941 | 4,247 | require 'fog/compute/models/server'
module Fog
module Compute
class Fogdocker
# fog server is a docker container
class Server < Fog::Compute::Server
identity :id
attr_accessor :info
attribute :name
attribute :created
attribute :path
attribute :args
attribute :hostname
attribute :ipaddress, :aliases => 'network_settings_ipaddress'
attribute :bridge, :aliases => 'network_settings_bridge'
attribute :state_running
attribute :state_pid
attribute :cores, :aliases => 'config_cpu_shares'
attribute :memory, :aliases => 'config_memory'
attribute :hostname, :aliases => 'config_hostname'
attribute :cmd, :aliases => 'config_cmd'
attribute :entrypoint, :aliases => 'config_entrypoint'
attribute :host
attribute :image
attribute :exposed_ports, :aliases => 'config_exposed_ports'
attribute :volumes
#raw = {"ID"=>"2ce79789656e4f7474624be6496dc6d988899af30d556574389a19aade2f9650",
# "Created"=>"2014-01-16T12:42:38.081665295Z",
# "Path"=>"/bin/bash",
# "Args"=>[],
# "Config"=>{
# "Hostname"=>"2ce79789656e",
# "Domainname"=>"",
# "User"=>"",
# "Memory"=>0,
# "MemorySwap"=>0,
# "CpuShares"=>0,
# "AttachStdin"=>true,
# "AttachStdout"=>true,
# "AttachStderr"=>true,
# "PortSpecs"=>nil,
# "ExposedPorts"=>{},
# "State"=>{
# "Running"=>true,
# "Pid"=>1505,
# "ExitCode"=>0,
# "StartedAt"=>"2014-01-16T15:50:36.304626413Z",
# "FinishedAt"=>"2014-01-16T15:50:36.238743161Z",
# "Ghost"=>false},
# "Image"=>"7c8cf65e1efa9b55f9ba8c60a970fe41595e56b894c7fdb19871bd9b276ca9d3",
# "NetworkSettings"=>{
# "IPAddress"=>"172.17.0.2",
# "IPPrefixLen"=>16,
# "Gateway"=>"172.17.42.1",
# "Bridge"=>"docker0",
# "PortMapping"=>nil,
# "Ports"=>{}},
# "SysInitPath"=>"/var/lib/docker/init/dockerinit-0.7.2",
# "ResolvConfPath"=>"/etc/resolv.conf",
# "HostnamePath"=>"/var/lib/docker/containers/2ce79789656e4f7474624be6496dc6d988899af30d556574389a19aade2f9650/hostname",
# "HostsPath"=>"/var/lib/docker/containers/2ce79789656e4f7474624be6496dc6d988899af30d556574389a19aade2f9650/hosts",
# "Name"=>"/boring_engelbart",
# "Driver"=>"devicemapper",
# "Volumes"=>{},
# "VolumesRW"=>{},
# "HostConfig"=>{
# "Binds"=>nil,
# "ContainerIDFile"=>"",
# "LxcConf"=>[],
# "Privileged"=>false,
# "PortBindings"=>{},
# "Links"=>nil,
# "PublishAllPorts"=>false}
# }
def ready?
reload if state_running.nil?
state_running
end
def stopped?
!ready?
end
def mac
# TODO
end
def start(options = {})
service.container_action(:id =>id, :action => :start!)
reload
end
def stop(options = {})
action = options['force'] ? :kill : :stop
service.container_action(:id =>id, :action => action)
reload
end
def restart(options = {})
service.container_action(:id =>id, :action => :restart!)
reload
end
def commit(options = {})
service.container_commit({:id=>id}.merge(options))
end
def destroy(options = {})
service.container_action(:id =>id, :action => :kill)
service.container_delete(:id => id)
end
def save
if persisted?
service.container_update(attributes)
else
self.id = service.container_create(attributes)['id']
end
reload
end
def to_s
name
end
end
end
end
end
| 31 | 129 | 0.506004 |
038e4623f3c9a43d77d41858554b894e060be24c | 333 | require 'mxx_ru/cpp'
require 'restinio/asio_helper.rb'
MxxRu::Cpp::exe_target {
target 'sample.hello_world_sendfile'
RestinioAsioHelper.attach_propper_asio( self )
required_prj 'nodejs/http_parser_mxxru/prj.rb'
required_prj 'fmt_mxxru/prj.rb'
required_prj 'restinio/platform_specific_libs.rb'
cpp_source 'main.cpp'
}
| 22.2 | 51 | 0.786787 |
2164eb1fa396fd497c7ccff54a8f4c72253a276d | 255 | class AddMemberSelfRelationship < ActiveRecord::Migration[5.0]
def change
return if table_exists? :members_members
create_table "members_members", id: false, force: :cascade do |t|
t.integer "member_id", null: false
end
end
end
| 25.5 | 69 | 0.709804 |
39fb779ae8982a9ad58603f9b821c8780ccef019 | 88 | # desc "Explaining what the task does"
# task :kms_models do
# # Task goes here
# end
| 17.6 | 38 | 0.681818 |
08d0b1e40ffcdef5dea706d221e5a42524773172 | 1,643 | class Ragel < Formula
desc "State machine compiler"
homepage "https://www.colm.net/open-source/ragel/"
url "https://www.colm.net/files/ragel/ragel-6.10.tar.gz"
sha256 "5f156edb65d20b856d638dd9ee2dfb43285914d9aa2b6ec779dac0270cd56c3f"
bottle do
cellar :any_skip_relocation
sha256 "a402204e97c35c6a9487d2b0707e27766d9b39c9c2116d49e9c561e1d0bd54b7" => :catalina
sha256 "b9b1428abb19b6e6d8de2bccc58a059b75d7c08b38b73956bb40e764a9d0390f" => :mojave
sha256 "8dc6d7e1a3617cd31d9738c5ae595fd57ddb157266c1970646a7d5fbba85a6ae" => :high_sierra
sha256 "69d6d65c2ef3da7b829e3391fd17b1ef088b92c2baf64979707033e2a7dd8c01" => :sierra
sha256 "f4ea3a8c0476fd82000223fae69170ac9f266cd36334bd60d9d6cf4fab3273c1" => :el_capitan
sha256 "dd8469ac3e08d5d8a257ce7fc7de05de398e8521abff83eceea0741099685b38" => :yosemite
sha256 "f3663a760b85bb4beb623a7cbd3954a4cf18120c6aee5b9abdcd04974cd15621" => :x86_64_linux
end
resource "pdf" do
url "https://www.colm.net/files/ragel/ragel-guide-6.10.pdf"
sha256 "efa9cf3163640e1340157c497db03feb4bc67d918fc34bc5b28b32e57e5d3a4e"
end
def install
system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}"
system "make", "install"
doc.install resource("pdf")
end
test do
testfile = testpath/"rubytest.rl"
testfile.write <<~EOS
%%{
machine homebrew_test;
main := ( 'h' @ { puts "homebrew" }
| 't' @ { puts "test" }
)*;
}%%
data = 'ht'
%% write data;
%% write init;
%% write exec;
EOS
system bin/"ragel", "-Rs", testfile
end
end
| 35.717391 | 94 | 0.712112 |
d5cc235a21270edf1ec9c274b5f9ba4432ad6f70 | 200 | require 'spec_helper'
describe Upgrademe do
it 'has a version number' do
expect(Upgrademe::VERSION).not_to be nil
end
it 'does something useful' do
expect(false).to eq(true)
end
end
| 16.666667 | 44 | 0.71 |
e847f4885978c34cd8f0cf5487b85bef9bca3d4c | 109 | require "rspec"
require File.expand_path(File.join(File.dirname(__FILE__), "..", "lib/chromedriver/helper"))
| 36.333333 | 92 | 0.752294 |
e9151ae7a873ba1a08b77c4e822f9b37778970ba | 104 | class ContactController < ApplicationController
def index
@user = current_user
end
end
| 17.333333 | 47 | 0.701923 |
26c68a0ea5ce92c4bafb3a20e9754d7e4823def6 | 725 | require 'easy_management/builders/class_builder'
module EasyManagement
module Builders
class ManagerBuilder < ClassBuilder
protected
def class_full_name
"#{model_helper.namespace}::#{model_helper.manager_class}"
end
def superclass
EasyManagement::Managers::BaseManager
end
def setup_class
model_class = model_helper.model_constant
model_class_sym = model_helper.model_symbol
model_method = Proc.new { model_class }
model_name_method = Proc.new { model_class_sym }
self.klass.send :define_method, :model, &model_method
self.klass.send :define_method, :model_name, &model_name_method
end
end
end
end | 22.65625 | 71 | 0.689655 |
e81c7ef323b1f181759fa7e175a4f12cc5ad86f2 | 1,347 |
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "gem_sample_pruby/version"
Gem::Specification.new do |spec|
spec.name = "gem_sample_pruby"
spec.version = GemSamplePruby::VERSION
spec.authors = ["Taiki Hisamura"]
spec.email = ["[email protected]"]
spec.summary = "gem create practice"
spec.description = "gem practice"
spec.homepage = "TODO: Put your gem's website or public repo URL here."
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
# to allow pushing to a single host or delete this section to allow pushing to any host.
if spec.respond_to?(:metadata)
spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
else
raise "RubyGems 2.0 or newer is required to protect against " \
"public gem pushes."
end
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.16"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
end
| 36.405405 | 96 | 0.672606 |
ac17f81c29b8a5cb31a4d5be392d68e53edb1881 | 1,964 | require 'shopify_cli'
module ShopifyCli
module Tasks
class JsDeps < ShopifyCli::Task
include SmartProperties
INSTALL_COMMANDS = {
yarn: %w(yarn install --silent),
npm: %w(npm install --no-audit --no-optional --silent),
}.freeze
def call(ctx)
@ctx = ctx
@dir = ctx.root
CLI::UI::Frame.open("Installing dependencies with #{installer}...") do
send(installer)
end
puts CLI::UI.fmt("{{v}} Dependencies installed")
end
def installer
@installer = yarn? ? :yarn : :npm
end
def yarn?
return false unless File.exist?(File.join(@dir, 'yarn.lock'))
CLI::Kit::System.system('which', 'yarn').success?
end
def yarn
success = CLI::Kit::System.system(*INSTALL_COMMANDS[installer], chdir: @dir) do |out, err|
puts out
err.lines.each do |e|
puts e
end
end.success?
return false unless success
true
end
def npm
package_json = File.join(@dir, 'package.json')
pkg = begin
JSON.parse(File.read(package_json))
rescue Errno::ENOENT, Errno::ENOTDIR
raise(ShopifyCli::Abort, "{{x}} expected to have a file at: #{package_json}")
end
deps = %w(dependencies devDependencies).map do |key|
pkg.fetch(key, []).keys
end.flatten
CLI::UI::Spinner.spin("Installing #{deps.size} dependencies...") do |spinner|
CLI::Kit::System.system(*INSTALL_COMMANDS[installer], chdir: @dir)
spinner.update_title("#{deps.size} #{installer} dependencies installed")
end
rescue JSON::ParserError
ctx.puts(
"{{info:#{File.read(File.join(path, 'package.json'))}}} was not valid JSON. Fix this then try again",
error: true
)
raise ShopifyCli::AbortSilent
end
end
end
end
| 28.882353 | 111 | 0.564664 |
d5f16d72f71db594f2548b1d4ba83b6a0f5b6300 | 158 | class AddIsPublicToProjects < ActiveRecord::Migration[5.0]
def change
add_column :projects, :is_public, :boolean, null: false, default: false
end
end
| 26.333333 | 75 | 0.753165 |
0816e211be835f547e452d0085f14d6339e7857e | 449 | if defined? ::BENCHMARK_JOB
return
end
::BENCHMARK_JOB = 1
RSpec.shared_examples 'Benchmark Job' do
before { Rails.cache.clear }
let!(:count) { 500 }
it 'runs for 501 times' do
perform_enqueued_jobs do
(count + 1).times { |i| described_class.perform_later i }
end
p "#{described_class}-0, #{Rails.cache.read("#{described_class}-0")}"
p "#{described_class}-last, #{Rails.cache.read("#{described_class}")}"
end
end
| 22.45 | 74 | 0.665924 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.