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
|
---|---|---|---|---|---|
1abd4920cf854c270bff3abfddd8f1eb8fd317d4 | 2,333 | #!/usr/bin/env ruby
require "pry"
# Question URL: https://www.interviewcake.com/question/merging-ranges
class ProductOfOtherNumbers
def self.condense_meeting_times(meeting_time_ranges)
sorted_meetings = meeting_time_ranges.sort
start_meeting_time = sorted_meetings.first.first
end_meeting_time = sorted_meetings.first.last
condensed_meeting_times = []
sorted_meetings.each_with_index do |meeting_times, index|
next_meeting_times = sorted_meetings[index + 1]
if next_meeting_times.nil?
condensed_meeting_times << [start_meeting_time, end_meeting_time]
next
end
if next_meeting_times.first > end_meeting_time
condensed_meeting_times << [start_meeting_time, end_meeting_time]
start_meeting_time = next_meeting_times.first
end_meeting_time = [end_meeting_time, next_meeting_times.last].max
else
end_meeting_time = [end_meeting_time, next_meeting_times.last].max
next
end
end
condensed_meeting_times
end
end
if __FILE__ == $0
simple_situation = [[0, 1], [3, 5], [4, 8], [10, 12], [9, 10]]
puts "Simple situation: " + simple_situation.to_s
simple_solution = ProductOfOtherNumbers.condense_meeting_times(simple_situation)
puts "Expected solution: [[0, 1], [3, 8], [9, 12]. Solution is: #{simple_solution.to_s}"
puts "=================="
non_overlap_situation = [[1, 2], [2, 3]]
puts "Non overlap situation: " + non_overlap_situation.to_s
non_overlap_solution = ProductOfOtherNumbers.condense_meeting_times(non_overlap_situation)
puts "Expected solution: [[1, 2], [2, 3]]. Solution is: #{non_overlap_solution.to_s}"
puts "=================="
subsumed_situation = [[1, 5], [2, 3]]
puts "Subsumed situation: " + subsumed_situation.to_s
non_overlap_solution = ProductOfOtherNumbers.condense_meeting_times(subsumed_situation)
puts "Expected solution: [[1, 5]]. Solution is: #{non_overlap_solution.to_s}"
puts "=================="
fully_compacted_situation = [[1, 10], [2, 6], [3, 5], [7, 9]]
puts "Fulled compacted situation: " + fully_compacted_situation.to_s
fully_compacted_solution = ProductOfOtherNumbers.condense_meeting_times(fully_compacted_situation)
puts "Expected solution: [[1, 10]]. Solution is: #{fully_compacted_solution.to_s}"
puts "=================="
end
| 40.929825 | 100 | 0.710673 |
edc5ba9dec1f9d4c4a4139200c983deb3ea22a72 | 2,081 | require 'test_helper'
class UsersControllerTest < ActionDispatch::IntegrationTest
def setup
@user = users(:michael)
@other_user = users(:archer)
end
test "should redirect index when not logged in" do
get users_path
assert_redirected_to login_url
end
test "should get new" do
get signup_path
assert_response :success
end
test "should redirect edit when not logged in" do
get edit_user_path(@user)
assert_not flash.empty?
assert_redirected_to login_url
end
test "should redirect update when not logged in" do
patch user_path(@user), params: { user: { name: @user.name,
email: @user.email } }
assert_not flash.empty?
assert_redirected_to login_url
end
test "should not allow the admin attribute to be edited via the web" do
log_in_as(@other_user)
assert_not @other_user.admin?
patch user_path(@other_user), params: {
user: { password: @other_user.password,
password_confirmation: @other_user.password,
admin: true } }
assert_not @other_user.admin?
end
test "should redirect edit when logged in as wrong user" do
log_in_as(@other_user)
get edit_user_path(@user)
assert flash.empty?
assert_redirected_to root_url
end
test "should redirect update when logged in as wrong user" do
log_in_as(@other_user)
patch user_path(@user), params: { user: { name: @user.name,
email: @user.email } }
assert flash.empty?
assert_redirected_to root_url
end
test "should redirect destroy when not logged in" do
assert_no_difference 'User.count' do
delete user_path(@user)
end
assert_redirected_to login_url
end
test "should redirect destroy when logged in as a non-admin" do
log_in_as(@other_user)
assert_no_difference 'User.count' do
delete user_path(@user)
end
assert_redirected_to root_url
end
end
| 28.121622 | 88 | 0.644882 |
e96f459186df9b331f2e072adb84e9ea557e3120 | 1,534 | class OpenlibertyMicroprofile4 < Formula
desc "Lightweight open framework for Java (Micro Profile 4)"
homepage "https://openliberty.io"
url "https://public.dhe.ibm.com/ibmdl/export/pub/software/openliberty/runtime/release/2021-09-20_1900/openliberty-microProfile4-21.0.0.10.zip"
sha256 "f808b2ae3bb27c988e34cfb759ac0cd61dd0b0cc07ab11e316adf27cf6ca10ed"
license "EPL-1.0"
livecheck do
url "https://openliberty.io/api/builds/data"
regex(/openliberty[._-]v?(\d+(?:\.\d+)+)\.zip/i)
end
bottle do
sha256 cellar: :any_skip_relocation, x86_64_linux: "11fdd928da1b61f6fd53b14956493cc92f3d195e4bb4d1c76f9dbe0377951ed3" # linuxbrew-core
end
depends_on "openjdk"
def install
rm_rf Dir["bin/**/*.bat"]
prefix.install_metafiles
libexec.install Dir["*"]
(bin/"openliberty-microprofile4").write_env_script "#{libexec}/bin/server",
Language::Java.overridable_java_home_env
end
def caveats
<<~EOS
The home of Open Liberty Micro Profile 4 is:
#{opt_libexec}
EOS
end
test do
ENV["WLP_USER_DIR"] = testpath
begin
system bin/"openliberty-microprofile4", "start"
assert_predicate testpath/"servers/.pid/defaultServer.pid", :exist?
ensure
system bin/"openliberty-microprofile4", "stop"
end
refute_predicate testpath/"servers/.pid/defaultServer.pid", :exist?
assert_match "<feature>microProfile-4.1</feature>", (testpath/"servers/defaultServer/server.xml").read
end
end
| 31.306122 | 144 | 0.698175 |
03a5cec58f26c91a44bde0278dc7e48c852421cd | 3,723 | require_relative '../../advent';
input = @load_input[__FILE__]
class Screen
def initialize(width, height)
@width = width
@height = height
@grid = height.times.map do
width.times.map do
"."
end
end
end
attr_reader :width, :height, :grid
def toggle(x, y)
value = at(x, y)
set(x,y, value == '.' ? '#' : '.')
end
def on(x, y)
set x, y, '#'
end
def at(x, y)
grid[y][x]
end
def set(x, y, value)
grid[y][x] = value
end
def turn_on_block(width, height)
height.times do |y|
width.times do |x|
on(x,y)
end
end
end
def rotate_column(column, shift)
column_values = grid.transpose[column].rotate(-shift)
column_values.each_with_index do |value, x|
set(column, x, value)
end
end
def rotate_row(row, shift)
row_values = grid[row].rotate(-shift)
row_values.each_with_index do |value, y|
set(y, row, value)
end
end
def to_s
grid.length.times.each do |y|
grid[y].each do |cell|
print cell
end
puts
end
"<Screen height=#{height} width=#{width}>"
end
end
InstructionReader = ->(instructions, screen) {
instructions.split("\n").each do |instruction|
case instruction
when /rect/
data = /rect (\d+)x(\d+)/.match(instruction)
screen.turn_on_block(data.captures[0].to_i, data.captures[1].to_i)
when /rotate column/
data = /rotate column x=(\d+) by (\d+)/.match(instruction)
screen.rotate_column(data.captures[0].to_i, data.captures[1].to_i)
when /rotate row/
data = /rotate row y=(\d+) by (\d+)/.match(instruction)
screen.rotate_row(data.captures[0].to_i, data.captures[1].to_i)
end
end
screen
}
describe Screen do
let(:width) { 7 }
let(:height) { 3 }
let(:screen) { Screen.new(width, height) }
it 'generates a grid based on the height, width' do
screen.grid.length.must_equal height
screen.grid.each do |row|
row.length.must_equal width
end
end
it 'can toggle pixel values' do
screen.toggle(0,0)
screen.at(0,0).must_equal '#'
end
it 'can turn on pixels in blocks' do
screen.turn_on_block(2, 2)
screen.at(0,0).must_equal '#'
screen.at(0,1).must_equal '#'
screen.at(1,0).must_equal '#'
screen.at(1,1).must_equal '#'
end
it 'can rotate pixels by columns' do
screen.turn_on_block(3,2)
screen.rotate_column(1, 1)
screen.at(1,0).must_equal '.'
screen.at(1,1).must_equal '#'
screen.at(1,2).must_equal '#'
end
it 'can rotate pixels by rows' do
screen.turn_on_block(3,2)
screen.rotate_column(1, 1)
screen.rotate_row(0, 4)
screen.grid[0].join.must_equal '....#.#'
end
it 'completes all examples' do
screen.turn_on_block(3,2)
screen.rotate_column(1, 1)
screen.rotate_row(0, 4)
screen.rotate_column(1, 1)
screen.grid[0].join.must_equal '.#..#.#'
screen.grid[1].join.must_equal '#.#....'
screen.grid[2].join.must_equal '.#.....'
end
end
describe 'InstructionReader' do
let(:screen) { Screen.new(7, 3) }
it 'works with the example instructions' do
instructions = "rect 3x2\nrotate column x=1 by 1\nrotate row y=0 by 4\n" +
"rotate column x=1 by 1"
InstructionReader[instructions, screen]
screen.grid[0].join.must_equal '.#..#.#'
screen.grid[1].join.must_equal '#.#....'
screen.grid[2].join.must_equal '.#.....'
end
end
screen = Screen.new(50, 6)
InstructionReader[input, screen]
part_one = screen.grid.inject(0) do |s, row|
s += row.count {|v| v == '#' }
end
puts "Part One: #{part_one}"
puts "Part Two:"
50.times { print "-" }
puts ""
screen.to_s
50.times { print "-" }
| 20.91573 | 78 | 0.611604 |
7a0c4369e2ebbd4a145397b43ce4cb77bc0b83d0 | 1,637 | require "helper"
require "inspec/resource"
require "inspec/resources/ssh_config"
describe "Inspec::Resources::SshConfig" do
describe "ssh_config" do
it "check ssh config parsing" do
resource = load_resource("ssh_config")
_(resource.Host).must_equal "*"
_(resource.Tunnel).must_be_nil
_(resource.SendEnv).must_equal "LANG LC_*"
_(resource.HashKnownHosts).must_equal "yes"
end
it "is case insensitive" do
resource = load_resource("ssh_config")
_(resource.gssapiauthentication).must_equal "no"
_(resource.GSSAPIAuthentication).must_equal "no"
end
it "uses the first value encountered" do
resource = load_resource("ssh_config")
_(resource.HostBasedAuthentication).must_equal "yes"
end
end
describe "sshd_config" do
it "check protocol version" do
resource = load_resource("sshd_config")
_(resource.Port).must_equal "22"
_(resource.UsePAM).must_equal "yes"
_(resource.ListenAddress).must_be_nil
_(resource.HostKey).must_equal [
"/etc/ssh/ssh_host_rsa_key",
"/etc/ssh/ssh_host_dsa_key",
"/etc/ssh/ssh_host_ecdsa_key",
]
end
it "check bad path" do
resource = load_resource("sshd_config", "/etc/ssh/sshd_config_does_not_exist")
_(resource.resource_exception_message).must_equal "Can't find file: /etc/ssh/sshd_config_does_not_exist"
end
it "check cannot read" do
resource = load_resource("sshd_config", "/etc/ssh/sshd_config_empty")
_(resource.resource_exception_message).must_equal "File is empty: /etc/ssh/sshd_config_empty"
end
end
end
| 31.480769 | 110 | 0.697618 |
1c9881167fcac3d8bf89f1f212e000170839dbf7 | 20,818 | # encoding: utf-8
require 'sequel'
require 'rack/test'
require 'json'
require_relative '../../spec_helper'
require_relative '../../support/factories/organizations'
require_relative '../../../app/models/visualization/migrator'
require_relative '../../../app/controllers/admin/visualizations_controller'
def app
CartoDB::Application.new
end #app
describe Admin::VisualizationsController do
include Rack::Test::Methods
include Warden::Test::Helpers
include CacheHelper
before(:all) do
@user = FactoryGirl.create(:valid_user, private_tables_enabled: true)
@api_key = @user.api_key
@user.stubs(:should_load_common_data?).returns(false)
@db = Rails::Sequel.connection
Sequel.extension(:pagination)
CartoDB::Visualization.repository = DataRepository::Backend::Sequel.new(@db, :visualizations)
@headers = {
'CONTENT_TYPE' => 'application/json',
}
end
after(:all) do
@user.destroy
end
before(:each) do
CartoDB::NamedMapsWrapper::NamedMaps.any_instance.stubs(:get => nil, :create => true, :update => true, :delete => true)
delete_user_data @user
host! "#{@user.username}.localhost.lan"
end
describe 'GET /viz' do
it 'returns a list of visualizations' do
login_as(@user, scope: @user.username)
get "/viz", {}, @headers
last_response.status.should == 200
end
it 'returns 403 if user not logged in' do
get "/viz", {}, @headers
last_response.status.should == 302
end
end # GET /viz
describe 'GET /viz:id' do
it 'returns a visualization' do
id = factory.fetch('id')
login_as(@user, scope: @user.username)
get "/viz/#{id}", {}, @headers
last_response.status.should == 200
end
it 'redirects to the public view if visualization private' do
id = factory.fetch('id')
get "/viz/#{id}", {}, @headers
follow_redirect!
last_request.path.should =~ %r{/viz/}
end
it 'keeps the base path (table|visualization) when redirecting' do
id = table_factory.id
get "/tables/#{id}", {}, @headers
follow_redirect!
last_request.path.should =~ %r{/tables/}
end
end # GET /viz/:id
describe 'GET /tables/:id/public/table' do
it 'returns 404 for private tables' do
id = table_factory(privacy: ::UserTable::PRIVACY_PRIVATE).id
get "/tables/#{id}/public/table", {}, @headers
last_response.status.should == 404
end
end
describe 'GET /viz/:id/protected_public_map' do
it 'returns 404 for private maps' do
id = table_factory(privacy: ::UserTable::PRIVACY_PRIVATE).table_visualization.id
get "/viz/#{id}/protected_public_map", {}, @headers
last_response.status.should == 404
end
end
describe 'GET /viz/:id/protected_embed_map' do
it 'returns 404 for private maps' do
id = table_factory(privacy: ::UserTable::PRIVACY_PRIVATE).table_visualization.id
get "/viz/#{id}/protected_embed_map", {}, @headers
last_response.status.should == 404
end
end
describe 'GET /viz/:id/public_map' do
it 'returns 403 for private maps' do
id = table_factory(privacy: ::UserTable::PRIVACY_PRIVATE).table_visualization.id
get "/viz/#{id}/public_map", {}, @headers
last_response.status.should == 403
end
it 'returns proper surrogate-keys' do
id = table_factory(privacy: ::UserTable::PRIVACY_PUBLIC).table_visualization.id
get "/viz/#{id}/public_map", {}, @headers
last_response.status.should == 200
last_response.headers["Surrogate-Key"].should_not be_empty
last_response.headers["Surrogate-Key"].should include(CartoDB::SURROGATE_NAMESPACE_PUBLIC_PAGES)
end
it 'returns public map for org users' do
org = OrganizationFactory.new.new_organization(name: 'public-map-spec-org').save
user_a = create_user({username: 'user-public-map', quota_in_bytes: 123456789, table_quota: 400})
user_org = CartoDB::UserOrganization.new(org.id, user_a.id)
user_org.promote_user_to_admin
vis_id = new_table({user_id: user_a.id, privacy: ::UserTable::PRIVACY_PUBLIC}).save.reload.table_visualization.id
host! "#{org.name}.localhost.lan"
get "/viz/#{vis_id}/public_map", @headers
last_response.status.should == 200
end
it 'does not load daily mapviews stats' do
CartoDB::Visualization::Stats.expects(:mapviews).never
CartoDB::Visualization::Stats.any_instance.expects(:to_poro).never
CartoDB::Visualization.expects(:stats).never
Carto::Visualization.expects(:stats).never
id = table_factory(privacy: ::UserTable::PRIVACY_PUBLIC).table_visualization.id
get public_visualizations_public_map_url(id: id), {}, @headers
last_response.status.should == 200
end
it 'serves X-Frame-Options: DENY' do
id = table_factory(privacy: ::UserTable::PRIVACY_PUBLIC).table_visualization.id
get "/viz/#{id}/public_map", {}, @headers
last_response.status.should == 200
last_response.headers['X-Frame-Options'].should == 'DENY'
end
end
describe 'public_visualizations_show_map' do
it 'does not load daily mapviews stats' do
CartoDB::Visualization::Stats.expects(:mapviews).never
CartoDB::Visualization::Stats.any_instance.expects(:to_poro).never
CartoDB::Stats::APICalls.any_instance.expects(:get_api_calls_from_redis_source).never
CartoDB::Visualization.expects(:stats).never
Carto::Visualization.expects(:stats).never
id = table_factory(privacy: ::UserTable::PRIVACY_PUBLIC).table_visualization.id
login_as(@user, scope: @user.username)
get public_visualizations_show_map_url(id: id), {}, @headers
last_response.status.should == 200
end
end
describe 'GET /viz/:id/public' do
it 'returns public data for a table visualization' do
id = table_factory(privacy: ::UserTable::PRIVACY_PUBLIC).table_visualization.id
get "/viz/#{id}/public", {}, @headers
last_response.status.should == 200
end
it 'returns a 404 if table is private' do
id = table_factory.table_visualization.id
get "/viz/#{id}/public", {}, @headers
last_response.status.should == 404
last_response.body.should =~ %r{<title>404 Error — CartoDB</title>}
end
it "redirects to embed_map if visualization is 'derived'" do
id = table_factory(privacy: ::UserTable::PRIVACY_PUBLIC).table_visualization.id
payload = { source_visualization_id: id }
post "/api/v1/viz?api_key=#{@api_key}",
payload.to_json, @headers
last_response.status.should == 200
derived_visualization = JSON.parse(last_response.body)
id = derived_visualization.fetch('id')
get "/viz/#{id}/public", {}, @headers
last_response.status.should == 302
follow_redirect!
last_response.status.should == 200
last_request.url.should =~ %r{.*#{id}/public_map.*}
end
end # GET /viz/:id/public
describe 'GET /tables/:id/embed_map' do
it 'returns 404 for nonexisting tables when table name is used' do
get "/tables/tablethatdoesntexist/embed_map", {}, @headers
last_response.status.should == 404
end
end
describe 'GET /viz/:name/embed_map' do
it 'renders the view by passing a visualization name' do
table = table_factory(privacy: ::UserTable::PRIVACY_PUBLIC)
name = table.table_visualization.name
get "/viz/#{URI::encode(name)}/embed_map", {}, @headers
last_response.status.should == 200
last_response.headers["X-Cache-Channel"].should_not be_empty
last_response.headers["X-Cache-Channel"].should include(table.name)
last_response.headers["X-Cache-Channel"].should include(table.table_visualization.varnish_key)
last_response.headers["Surrogate-Key"].should_not be_empty
last_response.headers["Surrogate-Key"].should include(CartoDB::SURROGATE_NAMESPACE_PUBLIC_PAGES)
last_response.headers["Surrogate-Key"].should include(table.table_visualization.surrogate_key)
end
it 'renders embed map error page if visualization private' do
table = table_factory
put "/api/v1/tables/#{table.id}?api_key=#{@api_key}",
{ privacy: 0 }.to_json, @headers
name = table.table_visualization.name
name = URI::encode(name)
login_as(@user, scope: @user.username)
get "/viz/#{name}/embed_map", {}, @headers
last_response.status.should == 403
last_response.body.should =~ /cartodb-embed-error/
end
it 'renders embed map error when an exception is raised' do
login_as(@user, scope: @user.username)
get "/viz/220d2f46-b371-11e4-93f7-080027880ca6/embed_map", {}, @headers
last_response.status.should == 404
last_response.body.should =~ /404/
end
it 'doesnt serve X-Frame-Options: DENY on embedded with name' do
table = table_factory(privacy: ::UserTable::PRIVACY_PUBLIC)
name = table.table_visualization.name
get "/viz/#{URI::encode(name)}/embed_map", {}, @headers
last_response.status.should == 200
last_response.headers.include?('X-Frame-Options').should_not == true
end
end
describe 'GET /viz/:id/embed_map' do
it 'caches and serves public embed map successful responses' do
id = table_factory(privacy: ::UserTable::PRIVACY_PUBLIC).table_visualization.id
embed_redis_cache = EmbedRedisCache.new
embed_redis_cache.get(id, https=false).should == nil
get "/viz/#{id}/embed_map", {}, @headers
last_response.status.should == 200
# The https key/value pair should be differenent
embed_redis_cache.get(id, https=true).should == nil
last_response.status.should == 200
# It should be cached after the first request
embed_redis_cache.get(id, https=false).should_not be_nil
first_response = last_response
get "/viz/#{id}/embed_map", {}, @headers
last_response.status.should == 200
# Headers of both responses should be the same excluding some
remove_changing = lambda {|h| h.reject {|k, v| ['X-Request-Id', 'X-Runtime'].include?(k)} }
remove_changing.call(first_response.headers).should == remove_changing.call(last_response.headers)
first_response.body.should == last_response.body
end
it 'doesnt serve X-Frame-Options: DENY on embedded' do
id = table_factory(privacy: ::UserTable::PRIVACY_PUBLIC).table_visualization.id
get "/viz/#{id}/embed_map", {}, @headers
last_response.status.should == 200
last_response.headers.include?('X-Frame-Options').should_not == true
end
end
describe 'GET /viz/:name/track_embed' do
it 'renders the view by passing a visualization name' do
login_as(@user, scope: @user.username)
get "/viz/track_embed", {}, @headers
last_response.status.should == 200
end
it 'doesnt serve X-Frame-Options: DENY for track_embed' do
login_as(@user, scope: @user.username)
get "/viz/track_embed", {}, @headers
last_response.status.should == 200
last_response.headers.include?('X-Frame-Options').should_not == true
end
end
describe 'non existent visualization' do
it 'returns 404' do
login_as(@user, scope: @user.username)
get "/viz/220d2f46-b371-11e4-93f7-080027880ca6?api_key=#{@api_key}", {}, @headers
last_response.status.should == 404
get "/viz/220d2f46-b371-11e4-93f7-080027880ca6/public?api_key=#{@api_key}", {}, @headers
last_response.status.should == 404
get "/viz/220d2f46-b371-11e4-93f7-080027880ca6/embed_map?api_key=#{@api_key}", {}, @headers
last_response.status.should == 404
end
end # non existent visualization
describe 'org user visualization redirection' do
it 'if A shares a (shared) vis link to B with A username, performs a redirect to B username' do
db_config = Rails.configuration.database_configuration[Rails.env]
# Why not passing db_config directly to Sequel.postgres here ?
# See https://github.com/CartoDB/cartodb/issues/421
db = Sequel.postgres(
host: db_config.fetch('host'),
port: db_config.fetch('port'),
database: db_config.fetch('database'),
username: db_config.fetch('username')
)
CartoDB::Visualization.repository = DataRepository::Backend::Sequel.new(db, :visualizations)
CartoDB::UserModule::DBService.any_instance.stubs(:move_to_own_schema).returns(nil)
CartoDB::TablePrivacyManager.any_instance.stubs(
:set_from_table_privacy => nil,
:propagate_to_varnish => nil
)
::User.any_instance.stubs(
after_create: nil
)
CartoDB::UserModule::DBService.any_instance.stubs(
grant_user_in_database: nil,
grant_publicuser_in_database: nil,
set_user_privileges_at_db: nil,
set_statement_timeouts: nil,
set_user_as_organization_member: nil,
rebuild_quota_trigger: nil,
setup_organization_user_schema: nil,
set_database_search_path: nil,
cartodb_extension_version_pre_mu?: false,
load_cartodb_functions: nil,
create_schema: nil,
move_tables_to_schema: nil,
create_public_db_user: nil,
monitor_user_notification: nil,
enable_remote_db_user: nil
)
CartoDB::NamedMapsWrapper::NamedMaps.any_instance.stubs(:get => nil, :create => true, :update => true)
Table.any_instance.stubs(
:perform_cartodb_function => nil,
:update_cdb_tablemetadata => nil,
:update_table_pg_stats => nil,
:create_table_in_database! => nil,
:get_table_id => 1,
:grant_select_to_tiler_user => nil,
:cartodbfy => nil,
:set_the_geom_column! => nil
)
# --------TEST ITSELF-----------
org = Organization.new
org.name = 'vis-spec-org'
org.quota_in_bytes = 1024 ** 3
org.seats = 10
org.save
::User.any_instance.stubs(:remaining_quota).returns(1000)
user_a = create_user({username: 'user-a', quota_in_bytes: 123456789, table_quota: 400})
user_org = CartoDB::UserOrganization.new(org.id, user_a.id)
user_org.promote_user_to_admin
org.reload
user_a.reload
user_b = create_user({username: 'user-b', quota_in_bytes: 123456789, table_quota: 400, organization: org})
vis_id = factory(user_a).fetch('id')
vis = CartoDB::Visualization::Member.new(id:vis_id).fetch
vis.privacy = CartoDB::Visualization::Member::PRIVACY_PRIVATE
vis.store
login_host(user_b, org)
get CartoDB.url(self, 'public_table', {id: vis.name}, user_a)
last_response.status.should be(404)
['public_visualizations_public_map', 'public_tables_embed_map'].each { |forbidden_endpoint|
get CartoDB.url(self, forbidden_endpoint, {id: vis.name}, user_a)
follow_redirects
last_response.status.should be(403), "#{forbidden_endpoint} is #{last_response.status}"
}
perm = vis.permission
perm.set_user_permission(user_b, CartoDB::Permission::ACCESS_READONLY)
perm.save
get CartoDB.url(self, 'public_table', {id: vis.name}, user_a)
last_response.status.should == 302
# First we'll get redirected to the public map url
follow_redirect!
# Now url will get rewritten to current user
last_response.status.should == 302
url = CartoDB.base_url(org.name, user_b.username) +
CartoDB.path(self, 'public_visualizations_show', {id: "#{user_a.username}.#{vis.name}"}) + "?redirected=true"
last_response.location.should eq url
['public_visualizations_public_map', 'public_tables_embed_map'].each { |forbidden_endpoint|
get CartoDB.url(self, forbidden_endpoint, {id: vis.name}, user_a)
follow_redirects
last_response.status.should be(200), "#{forbidden_endpoint} is #{last_response.status}"
last_response.length.should >= 100
}
org.destroy
end
# @see https://github.com/CartoDB/cartodb/issues/6081
it 'If logged user navigates to legacy url from org user without org name, gets redirected properly' do
db_config = Rails.configuration.database_configuration[Rails.env]
# Why not passing db_config directly to Sequel.postgres here ?
# See https://github.com/CartoDB/cartodb/issues/421
db = Sequel.postgres(
host: db_config.fetch('host'),
port: db_config.fetch('port'),
database: db_config.fetch('database'),
username: db_config.fetch('username')
)
CartoDB::Visualization.repository = DataRepository::Backend::Sequel.new(db, :visualizations)
CartoDB::UserModule::DBService.any_instance.stubs(:move_to_own_schema).returns(nil)
CartoDB::TablePrivacyManager.any_instance.stubs(
set_from_table_privacy: nil,
propagate_to_varnish: nil
)
::User.any_instance.stubs(
after_create: nil
)
CartoDB::UserModule::DBService.any_instance.stubs(
grant_user_in_database: nil,
grant_publicuser_in_database: nil,
set_user_privileges_at_db: nil,
set_statement_timeouts: nil,
set_user_as_organization_member: nil,
rebuild_quota_trigger: nil,
setup_organization_user_schema: nil,
set_database_search_path: nil,
cartodb_extension_version_pre_mu?: false,
load_cartodb_functions: nil,
create_schema: nil,
move_tables_to_schema: nil,
create_public_db_user: nil,
monitor_user_notification: nil,
enable_remote_db_user: nil
)
CartoDB::NamedMapsWrapper::NamedMaps.any_instance.stubs(get: nil, create: true, update: true)
Table.any_instance.stubs(
perform_cartodb_function: nil,
update_cdb_tablemetadata: nil,
update_table_pg_stats: nil,
create_table_in_database!: nil,
get_table_id: 1,
grant_select_to_tiler_user: nil,
cartodbfy: nil,
set_the_geom_column!: nil
)
# --------TEST ITSELF-----------
org = Organization.new
org.name = 'vis-spec-org'
org.quota_in_bytes = 1024**3
org.seats = 10
org.save
::User.any_instance.stubs(:remaining_quota).returns(1000)
user_a = create_user(username: 'org-user-a', quota_in_bytes: 123456789, table_quota: 400)
user_org = CartoDB::UserOrganization.new(org.id, user_a.id)
user_org.promote_user_to_admin
org.reload
user_a.reload
user_b = create_user(username: 'user-b-non-org', quota_in_bytes: 123456789, table_quota: 400)
vis_id = factory(user_a).fetch('id')
vis = CartoDB::Visualization::Member.new(id: vis_id).fetch
vis.privacy = CartoDB::Visualization::Member::PRIVACY_PUBLIC
vis.store
login_host(user_b)
# dirty but effective trick, generate the url as if were for a non-org user, then replace usernames
# to respect format and just have no organization
destination_url = CartoDB.url(self, 'public_visualizations_public_map', { id: vis.name }, user_b)
.sub(user_b.username, user_a.username)
get destination_url
last_response.status.should be(302)
last_response.headers["Location"].should eq CartoDB.url(self, 'public_visualizations_public_map',
{ id: vis.id, redirected: true }, user_a)
follow_redirect!
last_response.status.should be(200)
org.destroy
end
end
describe '#index' do
before(:each) do
@user.stubs(:should_load_common_data?).returns(false)
end
it 'invokes user metadata redis caching' do
Carto::UserDbSizeCache.any_instance.expects(:update_if_old).with(@user).once
login_as(@user, scope: @user.username)
get dashboard_path, {}, @headers
end
end
def login_host(user, org = nil)
login_as(user, scope: user.username)
host! "#{org.nil? ? user.username : org.name}.localhost.lan"
end
def follow_redirects(limit = 10)
while last_response.status == 302 && (limit -= 1) > 0 do
follow_redirect!
end
end
def factory(owner=nil)
owner = @user if owner.nil?
map = Map.create(user_id: owner.id)
payload = {
name: "visualization #{rand(9999)}",
tags: ['foo', 'bar'],
map_id: map.id,
description: 'bogus',
type: 'derived'
}
with_host "#{owner.username}.localhost.lan" do
post "/api/v1/viz?api_key=#{owner.api_key}", payload.to_json
end
JSON.parse(last_response.body)
end
def table_factory(attrs = {})
new_table(attrs.merge(user_id: @user.id)).save.reload
end
end # Admin::VisualizationsController
| 35.404762 | 123 | 0.671486 |
f7765f0fb491c2ed9bf9fdb1d179f155c605efa9 | 2,327 | class OsrmBackend < Formula
desc "High performance routing engine"
homepage "http://project-osrm.org/"
url "https://github.com/Project-OSRM/osrm-backend/archive/v5.4.3.tar.gz"
sha256 "501b9302d4ae622f04305debacd2f59941409c6345056ebb272779ac375f874d"
head "https://github.com/Project-OSRM/osrm-backend.git"
bottle do
cellar :any
rebuild 1
sha256 "ba73d99520b070d69c8b973fbd395adc67c871a0866dd4b236b662b4b8f5f7cf" => :sierra
sha256 "0e3f746ad5aebf89dd08635ad6430b0b9726dea62be2543e539d9e75cebc2d25" => :el_capitan
sha256 "e5d20ef724178e01a29bd7cc68edc50654a99a8ed95c37ce7fad729ab098295b" => :yosemite
end
depends_on "cmake" => :build
depends_on "boost"
depends_on "libstxxl"
depends_on "libxml2"
depends_on "libzip"
depends_on "lua51"
depends_on "luabind"
depends_on "tbb"
def install
mkdir "build" do
system "cmake", "..", *std_cmake_args
system "make"
system "make", "install"
end
pkgshare.install "profiles"
end
test do
(testpath/"test.osm").write <<-EOS.undent
<?xml version="1.0" encoding="UTF-8"?>
<osm version="0.6">
<bounds minlat="54.0889580" minlon="12.2487570" maxlat="54.0913900" maxlon="12.2524800"/>
<node id="1" lat="54.0901746" lon="12.2482632" user="a" uid="46882" visible="true" version="1" changeset="676636" timestamp="2008-09-21T21:37:45Z"/>
<node id="2" lat="54.0906309" lon="12.2441924" user="a" uid="36744" visible="true" version="1" changeset="323878" timestamp="2008-05-03T13:39:23Z"/>
<node id="3" lat="52.0906309" lon="12.2441924" user="a" uid="36744" visible="true" version="1" changeset="323878" timestamp="2008-05-03T13:39:23Z"/>
<way id="10" user="a" uid="55988" visible="true" version="5" changeset="4142606" timestamp="2010-03-16T11:47:08Z">
<nd ref="1"/>
<nd ref="2"/>
<tag k="highway" v="unclassified"/>
</way>
</osm>
EOS
(testpath/"tiny-profile.lua").write <<-EOS.undent
function way_function (way, result)
result.forward_mode = mode.driving
result.forward_speed = 1
end
EOS
safe_system "#{bin}/osrm-extract", "test.osm", "--profile", "tiny-profile.lua"
safe_system "#{bin}/osrm-contract", "test.osrm"
assert File.exist?("#{testpath}/test.osrm"), "osrm-extract generated no output!"
end
end
| 38.147541 | 153 | 0.682424 |
ab42999a17a0c8a5ef2ed3ac0a3302a18a0e4563 | 65 | class Table2::Arg < ApplicationRecord
has_many :abundances
end
| 16.25 | 37 | 0.8 |
bb5bb988d72d0f406fc6bd94d22ada3e479a5237 | 1,352 | class PerlAT518 < Formula
desc "Highly capable, feature-rich programming language"
homepage "https://www.perl.org/"
url "https://www.cpan.org/src/5.0/perl-5.18.4.tar.gz"
sha256 "01a4e11a9a34616396c4a77b3cef51f76a297e1a2c2c490ae6138bf0351eb29f"
revision 1
bottle do
sha256 "45b388773570fd4ef892caa7a0bb0312fd05dfcb3f73245a03eed16bf9187cc9" => :catalina
sha256 "3e80537039afd47db55b42a09f34c2b1e6fc2a24581c16d09d76b5ad85997ed6" => :mojave
sha256 "4ebffdb24ede27bf2fb4f844c87f4adc962942d399c6762b3c6cf90b929fa50a" => :high_sierra
sha256 "ca240d036e5c65e2240d744848d56c60fa37c0f95f43e3ead4b34f56d8885921" => :x86_64_linux
end
keg_only :versioned_formula
def install
ENV.deparallelize if MacOS.version >= :catalina
args = %W[
-des
-Dprefix=#{prefix}
-Dman1dir=#{man1}
-Dman3dir=#{man3}
-Duseshrplib
-Duselargefiles
-Dusethreads
]
args << "-Dsed=/usr/bin/sed" if OS.mac?
system "./Configure", *args
system "make"
system "make", "install"
end
def caveats
<<~EOS
By default Perl installs modules in your HOME dir. If this is an issue run:
#{bin}/cpan o conf init
EOS
end
test do
(testpath/"test.pl").write "print 'Perl is not an acronym, but JAPH is a Perl acronym!';"
system "#{bin}/perl", "test.pl"
end
end
| 28.166667 | 94 | 0.701923 |
b9ff639acdf9ef4572a8e9eaff585c27bbc56c87 | 232 | require_relative '../spec_helper'
describe 'rails_part::default' do
let(:chef_run) { ChefSpec::SoloRunner.converge(described_recipe) }
it 'include setup' do
expect(chef_run).to include_recipe 'rails_part::setup'
end
end
| 23.2 | 68 | 0.75 |
91c267b16866fccbef79f0caabeb405a0ce8b7b8 | 124 | require "qc_dev_view_tool/version"
require "qc_dev_view_tool/renderer"
module QcDevViewTool
# Your code goes here...
end
| 17.714286 | 35 | 0.798387 |
f8d6dcae235bfb82f0f4ab689485fbded65dcf47 | 1,054 | require 'rubocop'
require 'rubocop/rspec/support'
require 'pry'
module SpecHelper
ROOT = Pathname.new(__FILE__).parent.freeze
end
# Load in Rubocop cops
require File.expand_path('lib/rubocop-airbnb')
spec_helper_glob = File.expand_path('{support,shared}/*.rb', SpecHelper::ROOT)
Dir.glob(spec_helper_glob).map(&method(:require))
RSpec.configure do |config|
config.include RuboCop::RSpec::ExpectOffense
config.order = :random
# Define spec metadata for all rspec cop spec files
cop_specs = 'spec/rubocop/cop/rspec/'
config.define_derived_metadata(file_path: /\b#{cop_specs}/) do |metadata|
# Attach metadata that signals the specified code is for an RSpec only cop
metadata[:rspec_cop] = true
end
config.expect_with :rspec do |expectations|
expectations.syntax = :expect # Disable `should`
end
config.mock_with :rspec do |mocks|
mocks.syntax = :expect # Disable `should_receive` and `stub`
end
end
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
| 27.736842 | 78 | 0.740987 |
e8d9fb0a59f3f4543acdc14e0c9b365882014472 | 7,747 | ENV['RACK_ENV'] = 'test'
require 'minitest/autorun'
require 'rack/test'
require 'fileutils'
require_relative '../cms'
class CMSTest < Minitest::Test
include Rack::Test::Methods
def app
Sinatra::Application
end
def setup
FileUtils.mkdir_p(data_path)
end
def teardown
FileUtils.rm_rf(data_path)
end
def create_file(file_name, contents='')
File.open(File.join(data_path, file_name), 'w') do |file|
file.write(contents)
end
end
def session
last_request.env["rack.session"]
end
def admin_session
{"rack.session" => { username: "admin" } }
end
def sign_in_user
post '/users/login', params={username: "admin", password: "secret"}
end
def test_index
create_file('about.txt')
create_file('changes.txt')
get '/'
assert_equal 200, last_response.status
assert_equal 'text/html;charset=utf-8', last_response['Content-Type']
assert_includes last_response.body, 'about.txt'
assert_includes last_response.body, 'changes.txt'
assert_includes last_response.body, 'New Document'
assert_includes last_response.body, 'delete'
end
def test_filename_exists
create_file('about.txt', 'This is a file based cms program.')
get '/about.txt'
assert_equal 200, last_response.status
assert_equal 'text/plain', last_response['Content-Type']
assert_includes last_response.body, 'This is a file based cms program.'
end
def test_filename_not_found
get '/doesnt_exist.txt'
assert_equal 302, last_response.status
assert_equal 'text/html;charset=utf-8', last_response['Content-Type']
get last_response['Location']
assert_equal 200, last_response.status
assert_includes last_response.body, 'doesnt_exist.txt does not exist'
get '/'
assert_equal 200, last_response.status
refute_includes last_response.body, 'doesnt_exist.txt does not exist'
end
def test_viewing_markdown_file
create_file('about.md', '# Ruby is...')
get '/about.md'
assert_equal 200, last_response.status
assert_equal 'text/html;charset=utf-8', last_response['Content-Type']
assert_includes last_response.body, '<h1>Ruby is...</h1>'
end
def test_edit_file_template
create_file('about.md')
get '/about.md/edit', {}, admin_session
assert_equal 200, last_response.status
assert_equal 'text/html;charset=utf-8', last_response['Content-Type']
assert_includes last_response.body, 'Edit contents of about.md'
assert_includes last_response.body, '<textarea'
assert_includes last_response.body, 'type="submit"'
assert_includes last_response.body, 'Save Changes'
end
def test_edit_file_template_with_signed_out_user
create_file('about.md')
get '/about.md/edit'
assert_equal 302 || 303, last_response.status
assert_equal "You must be signed in to do that.", session[:message]
end
def test_edit_file
create_file('test.txt', 'This is a test file.')
post '/test.txt/edit', params={edit_contents: "This is a test file. It's been tested."}, admin_session
assert_equal 302 || 303, last_response.status
get last_response['Location']
assert_equal 200, last_response.status
assert_includes last_response.body, 'test.txt has been updated.'
get '/'
assert_equal 200, last_response.status
refute_includes last_response.body, 'test.txt has been updated.'
get '/test.txt'
assert_equal 200, last_response.status
assert_includes last_response.body, "This is a test file. It's been tested."
end
def test_edit_file_with_signed_out_user
create_file('about.md')
post '/test.txt/edit', params={edit_contents: "This is a test file. It's been tested."}
assert_equal 302 || 303, last_response.status
assert_equal "You must be signed in to do that.", session[:message]
end
def test_new_file_template
get '/new', {}, admin_session
assert_equal 200, last_response.status
assert_includes last_response.body, 'Add a new document:'
assert_includes last_response.body, '<input'
assert_includes last_response.body, 'Create'
end
def test_new_file_template_with_signed_out_user
create_file('about.md')
get '/about.md/edit'
assert_equal 302 || 303, last_response.status
assert_equal "You must be signed in to do that.", session[:message]
end
def test_create_new_file_with_file_extension
post '/new', params={new_document: 'new_doc_test.txt'}, admin_session
assert_equal 302, last_response.status
get last_response['Location']
assert_equal 200, last_response.status
assert_includes last_response.body, 'new_doc_test.txt was created.'
get '/'
assert_equal 200, last_response.status
refute_includes last_response.body, 'new_doc_test.txt was created.'
assert_includes last_response.body, 'new_doc_test.txt'
end
def test_create_new_file_with_no_filename
post '/new', params={new_document: ''}, admin_session
assert_equal 422, last_response.status
assert_includes last_response.body, 'A name is required.'
end
def test_create_new_file_without_file_extension
post '/new', params={new_document: 'new_doc_test'}, admin_session
get last_response['Location']
assert_equal 200, last_response.status
assert_includes last_response.body, 'new_doc_test.txt'
end
def test_create_new_file_with_signed_out_user
post '/new', params={new_document: 'new_doc_test'}
assert_equal 302 || 303, last_response.status
assert_equal "You must be signed in to do that.", last_request.session[:message]
end
def test_delete_file
create_file('test_file.txt')
post '/test_file.txt/delete', {}, admin_session
assert_equal 302, last_response.status
get last_response['Location']
assert_equal 200, last_response.status
assert_includes last_response.body, 'test_file.txt was deleted.'
get '/'
assert_equal 200, last_response.status
refute_includes last_response.body, 'test_file.txt'
end
def test_delete_file_with_signed_out_user
create_file('test_file.txt')
post '/test_file.txt/delete'
assert_equal 302 || 303, last_response.status
assert_equal "You must be signed in to do that.", session[:message]
end
def test_sign_in_button_on_index_when_user_logged_out
get '/'
assert_equal 200, last_response.status
assert_includes last_response.body, 'Sign In'
end
def test_sign_in_page
get '/users/login'
assert_equal 200, last_response.status
assert_includes last_response.body, 'Username'
assert_includes last_response.body, 'Password'
assert_includes last_response.body, 'Sign In'
assert_includes last_response.body, '<input'
assert_includes last_response.body, '<button type="submit"'
end
def test_failed_login
post '/users/login', params={username: "testname", password: "password"}
assert_equal 422, last_response.status
assert_includes last_response.body, 'Invalid Credentials'
assert_includes last_response.body, 'testname'
end
def test_successful_login
sign_in_user
assert_equal 302, last_response.status
get last_response['Location']
assert_equal 200, last_response.status
assert_equal "admin", last_request.session[:username]
assert_includes last_response.body, 'Welcome!'
assert_includes last_response.body, 'Signed in as admin.'
assert_includes last_response.body, 'Sign Out'
end
def test_logout
post '/users/logout', {}, admin_session
get last_response['Location']
assert_equal 200, last_response.status
assert_nil last_request.session[:username]
assert_includes last_response.body, 'You have been signed out.'
assert_includes last_response.body, 'Sign In'
end
end
| 27.569395 | 106 | 0.731896 |
4a11c0dad8222a3cb465748a24ebcde29e8bd392 | 1,307 | # -*- encoding: utf-8 -*-
=begin
#OpenAPI Petstore
#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 4.2.0-SNAPSHOT
=end
$:.push File.expand_path("../lib", __FILE__)
require "petstore/version"
Gem::Specification.new do |s|
s.name = "petstore"
s.version = Petstore::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["OpenAPI-Generator"]
s.email = [""]
s.homepage = "https://openapi-generator.tech"
s.summary = "OpenAPI Petstore Ruby Gem"
s.description = "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\"
s.license = "Unlicense"
s.required_ruby_version = ">= 1.9"
s.add_runtime_dependency 'faraday', '>= 0.14.0'
s.add_runtime_dependency 'json', '~> 2.1', '>= 2.1.0'
s.add_development_dependency 'rspec', '~> 3.6', '>= 3.6.0'
s.files = `find *`.split("\n").uniq.sort.select { |f| !f.empty? }
s.test_files = `find spec/*`.split("\n")
s.executables = []
s.require_paths = ["lib"]
end
| 32.675 | 176 | 0.659526 |
01aabb314350ed6ec5862e2c028daf37982147b1 | 327 | module DynamoDbFramework
class MigrationScript
attr_accessor :timestamp
attr_accessor :namespace
def apply
raise 'Not implemented.'
end
def undo
raise 'Not implemented.'
end
def self.descendants
ObjectSpace.each_object(Class).select { |klass| klass < self }
end
end
end
| 17.210526 | 68 | 0.672783 |
21fd7152c959767d59ed7fae6b70583d7c4d2a38 | 511 | # frozen_string_literal: true
class PrefixConnectionWithTotalType < BaseConnection
edge_type(PrefixEdgeType)
field_class GraphQL::Cache::Field
field :total_count, Integer, null: false, cache: true
field :states, [FacetType], null: false, cache: true
field :years, [FacetType], null: false, cache: true
def total_count
object.total_count
end
def states
facet_by_key(object.aggregations.states.buckets)
end
def years
facet_by_year(object.aggregations.years.buckets)
end
end
| 22.217391 | 55 | 0.755382 |
bf4e1ab3e40b60f5e104686efb192ad4a0e41aa8 | 9,925 | require 'test_helper'
class IntegrationTest < Minitest::Test
def setup
Project.destroy_all
@project = Project.new
@state = {
name: "Clean House",
owner_id: 1,
detail: {
description: "I need to clean the house"
},
todo_lists: [{
todos: [{
text: "Take out the trash",
todo_assignments: [{
assignee_id: 2,
},{
assignee_id: 3,
}],
comments: [{
author_id: 1,
text: "Have this done by Monday",
},{
author_id: 2,
text: "I'll do my best",
}],
},{
text: "Sweep the floor"
}],
}],
}
@changes = {
name: ["Clean House", "Clean My House"],
detail: {
description: ["I need to clean the house", "I need to clean my house"],
},
todo_lists: {
0 => {
todos: {
0 => { text: ["Take out the trash", "Take out my trash"] },
2 => { text: [nil, "Another task!"], _create: '1' },
},
},
},
}
end
def test_state_setter_sets_attributes
@project.aggregate_state = { name: "Foo" }
assert_equal "Foo", @project.name
end
def test_state_getter_gets_attributes
@project.name = "Foo"
assert_equal "Foo", @project.aggregate_state[:name]
end
def test_state_setter_sets_attributes_on_has_one_associated_object
@project.aggregate_state = { detail: { description: "Foobar" }}
assert_equal "Foobar", @project.detail.try(:description)
end
def test_state_getter_gets_attributes_on_has_one_associated_object
@project.build_detail({ description: "Foobar" })
assert_equal "Foobar", @project.aggregate_state.fetch(:detail, {})[:description]
end
def test_state_getter_ignores_default_scope_attributes
@project.todo_lists.build({
todos_attributes: {
"0" => {
text: "Foo"
}
}
})
todo = @project.todo_lists.first.todos.first
c = todo.comments.build({ text: "Bar" })
# FIXME
comment_state = @project.aggregate_state[:todo_lists].first[:todos].first[:comments].first
# /fixme
assert_nil comment_state[:commentable_type]
end
def test_state_getter_ignores_has_many_through_associations
end
def test_state_setter_ignores_has_many_through_associations
end
def test_state_setter_sets_attributes_on_has_many_associated_object
@project.aggregate_state = { todo_lists: [{ todos: [{ text: "Hi" },{ text: "Bye" }] }] }
assert_equal 1, @project.todo_lists.size
assert_equal 2, @project.todo_lists.first.todos.size
assert_equal ["Hi", "Bye"], @project.todo_lists.first.todos.map(&:text)
end
def test_state_getter_rejects_id
refute @project.aggregate_state.keys.include?(:id)
end
def test_state_getter_rejects_unpopulated_associations
assert_equal 0, @project.todo_lists.size
assert_nil @project.detail
refute @project.aggregate_state.has_key?(:todo_lists)
refute @project.aggregate_state.has_key?(:detail)
end
def test_does_not_walk_associations_to_other_entities
assert_raises ActiveShepherd::AggregateMismatchError do
@project.aggregate_state = { owner: { name: "Joe Schmoe" } }
end
end
=begin
# FIXME: rails 4 is removing read only associations
def test_state_getter_does_not_walk_read_only_associations
@project.todo_lists.build.tap do |todo_list|
todo_list.todos.build({ text: "Hi" })
@project.recent_todo_list = todo_list
end
assert_nil @project.aggregate_state[:recent_todo_list]
end
def test_state_setter_does_not_walk_read_only_associations
@project.aggregate_state = { recent_todo_list: {} }
assert_nil @project.recent_todo_list
end
=end
def test_state_getter_ignores_foreign_key_relationship_to_parent_object
@project.save
@project.build_detail({ description: "Foo" })
assert_equal({ description: "Foo" }, @project.aggregate_state[:detail])
end
def test_changes_getter_ignores_foreign_key_relationship_to_parent_object
build_persisted_state
@project.todo_lists.build
assert_equal({todo_lists: { 1 => {_create: '1' }}}, @project.aggregate_changes)
end
def test_all_changes_to_associated_objects_show_up_in_aggregate_changes
build_persisted_state
@project.name = "Clean My House"
@project.detail.description = "I need to clean my house"
@project.todo_lists.first.todos.first.text = "Take out my trash"
@project.todo_lists.first.todos.build({ text: "Another task!" })
assert_equal @changes, @project.aggregate_changes
end
def test_applying_changes_shows_up_in_model_and_its_associations
build_persisted_state
@project.aggregate_state = @state
@project.save!
assert_equal "Clean House", @project.name
assert_equal "I need to clean the house", @project.detail.description
assert_equal "Take out the trash", @project.todo_lists.first.todos.first.text
assert_equal 2, @project.todo_lists.first.todos.size
@project.aggregate_changes = @changes
assert_equal "Clean My House", @project.name
assert_equal "I need to clean my house", @project.detail.description
assert_equal "Take out my trash", @project.todo_lists.first.todos.first.text
assert_equal 3, @project.todo_lists.first.todos.size
end
def test_applying_reverse_changes_invokes_apply_change_on_the_reverse_hash
build_persisted_state
@project.aggregate_changes = @changes
@project.save!
assert_equal "Clean My House", @project.name
assert_equal "I need to clean my house", @project.detail.description
assert_equal "Take out my trash", @project.todo_lists.first.todos.first.text
assert_equal 3, @project.todo_lists.first.todos.size
@project.reverse_aggregate_changes = @changes
@project.save!
assert_equal "Clean House", @project.name
assert_equal "I need to clean the house", @project.detail.description
assert_equal "Take out the trash", @project.todo_lists.first.todos.first.text
assert_equal 2, @project.todo_lists.first.todos.size
end
def test_state_getter_symbolizes_all_keys
@project.name = "Foo"
assert_equal({ name: "Foo" }, @project.aggregate_state)
end
def test_state_setter_populates_object_graph
@project.aggregate_state = @state
assert_equal @state, @project.aggregate_state
end
def test_state_setter_marks_existing_associations_for_deletion
@project.aggregate_state = @state
@project.save
assert_equal 2, @project.todo_lists.first.todos.size
new_state = Marshal.load(Marshal.dump(@state))
new_state[:todo_lists].first[:todos].first.tap do |todo|
todo[:todo_assignments].pop
todo[:comments].pop
todo[:comments].unshift({author_id: 2, text: "Brand new comment"})
end
new_state.delete(:detail)
@project.aggregate_state = new_state
@project.save
@project.reload
@project.todo_lists.first.todos.first.tap do |todo|
assert_equal 1, todo.todo_assignments.size
assert_equal 2, todo.comments.size
assert_equal ["Brand new comment", "Have this done by Monday"], todo.comments.map(&:text)
end
assert_nil @project.detail
end
def test_state_setter_resets_unsupplied_attributes_to_default
@project.aggregate_state = @state.merge(status: 5)
@project.save
new_state = Marshal.load(Marshal.dump(@state))
new_state.delete(:status)
@project.aggregate_state = new_state
assert_equal Project.new.status, @project.status
end
def state_setter_can_set_timestamps
timestamp = (1.year.ago - 15.seconds)
@project.state = { created_at: timestamp, updated_at: timestamp + 14.days }
assert_equal timestamp, @project.created_at
assert_equal timestamp + 14.days, @project.updated_at
end
def test_state_getter_respects_serialized_attributes
@project.fruit = :apple
assert_equal 'ELPPA', @project.aggregate_state[:fruit]
end
def test_state_setter_respects_serialized_attributes
@project.aggregate_state = @state
assert_equal nil, @project.fruit
@state[:fruit] = 'EGNARO'
@project.aggregate_state = @state
assert_equal :orange, @project.fruit
end
def test_state_changes_getter_and_setter_respect_serialized_attributes
build_persisted_state
@project.fruit = :banana
assert_equal [nil, 'ANANAB'], @project.aggregate_changes[:fruit]
@project.save!
assert_equal :banana, @project.reload.fruit
@project.fruit = :pear
assert_equal ['ANANAB', 'RAEP'], @project.aggregate_changes[:fruit]
@project.reload
assert_equal :banana, @project.fruit
@project.aggregate_changes = { fruit: [ 'ANANAB', 'OGNAM'] }
assert_equal :mango, @project.fruit
end
def test_changes_to_one_aggregate_do_not_include_associated_aggregate
build_persisted_state
@owner = User.create! name: 'Joe Schmoe'
@project.owner = @owner
@project.save!
@owner.reload
refute @owner.aggregate_state.has_key?(:projects)
end
private
# Test 'changes' behavior with this common background
def build_persisted_state
@project.name = "Clean House"
@project.owner_id = 1
@project.todo_lists.build({
todos_attributes: {
"0" => { text: "Take out the trash" },
"1" => { text: "Make your bed" },
},
})
@project.build_detail({ description: "I need to clean the house" })
@project.save
assert_equal({}, @project.aggregate_changes)
end
def reverse_changes
@changes = {
name: ["Clean My House", "Clean House"],
detail: {
description: ["I need to clean my house", "I need to clean the house"],
},
todo_lists: {
0 => {
todos: {
0 => { text: ["Take out my trash", "Take out the trash"] },
2 => { _destroy: '1' },
},
},
},
}
end
end
| 28.684971 | 95 | 0.68665 |
ac52e232b51d762bfabb4138e5fca673b946cb23 | 1,445 | Rails.application.routes.draw do
resources :genders
devise_for :admin_users, ActiveAdmin::Devise.config
ActiveAdmin.routes(self)
devise_for :users
root 'static_pages#index'
# resources :payments
resources :applications
resources :lodgings
resources :workshops
resources :application_settings
get '/about', to: 'static_pages#about'
get '/contact', to: 'static_pages#contact'
get '/privacy', to: 'static_pages#privacy'
get '/terms_of_service', to: 'static_pages#terms_of_use'
get '/conference_closed', to: 'static_pages#conference_closed'
get '/conference_full', to: 'static_pages#conference_full'
get '/accept_offer', to: 'static_pages#accept_offer'
get '/subscription', to: 'applications#subscription'
get 'payments', to: 'payments#index'
get 'payment_receipt', to: 'payments#payment_receipt'
post 'payment_receipt', to: 'payments#payment_receipt' # needed to address PCI gateway rqrmts
get 'payment_show', to: 'payments#payment_show', as: 'all_payments'
get 'make_payment', to: 'payments#make_payment'
post 'make_payment', to: 'payments#make_payment'
post 'run_lotto', to: 'application_settings#run_lottery'
post '/send_offer/:id', to: 'application_settings#send_offer', as: 'send_offer'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
if Rails.env.development?
mount LetterOpenerWeb::Engine, at: "/letter_opener"
end
end
| 35.243902 | 101 | 0.750173 |
abb46e52f19413a16cd758c21b864015b16ef18b | 320 | class CreateCameras < ActiveRecord::Migration
def change
create_table :cameras do |t|
t.integer :sucursal
t.integer :numcamera, default: 0
t.string :ipaddress
t.string :user
t.string :pass
t.string :tags
t.integer :status, default: 0
t.timestamps
end
end
end
| 20 | 45 | 0.63125 |
ac382594b706e6f3dd602960835fe44ef0c0c131 | 125 | require 'test_helper'
class FermentableTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| 15.625 | 47 | 0.712 |
f81a2814736cab5c1fdc44182dd7683f9ecec705 | 416 | cask 'moneymoney' do
version '2.3.3'
sha256 '67c8f64a237eea684553efbe2537912e3e1de44659e304566b42436272fff646'
url 'https://service.moneymoney-app.com/1/MoneyMoney.zip'
appcast 'https://service.moneymoney-app.com/1/Appcast.xml',
checkpoint: '7b6ca7ecbff8c4fdbdc1648b7acb578980543b77801c93a65533b4bf51202663'
name 'MoneyMoney'
homepage 'https://moneymoney-app.com/'
app 'MoneyMoney.app'
end
| 32 | 88 | 0.776442 |
01dd3aa36d40152e89f1eaf0f26e889d784d1428 | 2,548 | module ActiveRecord::Turntable
module ActiveRecordExt
module QueryCache
def self.prepended(klass)
class << klass
prepend ClassMethods.compatible_module
end
end
module ClassMethods
extend Compatibility
module V6_0
end
module V5_2
end
module V5_1
def run
result = super
pools = ActiveRecord::Base.turntable_pool_list
pools.each do |pool|
pool.enable_query_cache!
end
[*result, pools]
end
def complete(state)
caching_pool, caching_was_enabled, turntable_pools = state
super([caching_pool, caching_was_enabled])
turntable_pools.each do |pool|
pool.disable_query_cache! unless caching_was_enabled
end
end
end
module V5_0_1
def run
result = super
pools = ActiveRecord::Base.turntable_pool_list
pools.each do |pool|
pool.enable_query_cache!
end
[*result, pools]
end
def complete(state)
caching_pool, caching_was_enabled, connection_id, turntable_pools = state
super([caching_pool, caching_was_enabled, connection_id])
turntable_pools.each do |pool|
pool.disable_query_cache! unless caching_was_enabled
end
end
end
module V5_0
def run
result = super
pools = ActiveRecord::Base.turntable_pool_list
pools.each do |k|
k.connection.enable_query_cache!
end
result
end
def complete(state)
enabled, _connection_id = state
super
klasses = ActiveRecord::Base.turntable_pool_list
klasses.each do |k|
k.connection.clear_query_cache
k.connection.disable_query_cache! unless enabled
end
end
end
end
def self.install_turntable_executor_hooks(executor = ActiveSupport::Executor)
return if Util.ar_version_equals_or_later?("5.0.1")
executor.to_complete do
klasses = ActiveRecord::Base.turntable_connection_classes
klasses.each do |k|
unless k.connected? && k.connection.transaction_open?
k.clear_active_connections!
end
end
end
end
end
end
end
| 24.737864 | 85 | 0.561224 |
013d55b713de7bb6f0f2f8a632fc25f74c038115 | 5,323 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe NamespaceLimit do
let(:namespace_limit) { build(:namespace_limit) }
let(:usage_ratio) { 0.5 }
let(:namespace_storage_limit_enabled) { true }
subject { namespace_limit }
before do
stub_feature_flags(namespace_storage_limit: namespace_storage_limit_enabled)
[EE::Namespace::RootStorageSize, EE::Namespace::RootExcessStorageSize].each do |class_name|
allow_next_instance_of(class_name, namespace_limit.namespace) do |root_storage|
allow(root_storage).to receive(:usage_ratio).and_return(usage_ratio)
end
end
end
it { is_expected.to belong_to(:namespace) }
describe '#temporary_storage_increase_enabled?' do
subject { namespace_limit.temporary_storage_increase_enabled? }
context 'when date is not set' do
it { is_expected.to eq(false) }
end
context 'when temporary storage increase end date is today' do
before do
namespace_limit.temporary_storage_increase_ends_on = Date.today
end
it { is_expected.to eq(true) }
context 'when feature is disabled' do
before do
stub_feature_flags(temporary_storage_increase: false)
end
it { is_expected.to eq(false) }
end
end
context 'when temporary storage increase end date is exceeded' do
before do
namespace_limit.temporary_storage_increase_ends_on = Date.today - 1.day
end
it { is_expected.to eq(false) }
end
end
describe '#eligible_for_temporary_storage_increase?' do
subject { namespace_limit.eligible_for_temporary_storage_increase? }
context 'when usage ratio is above the threshold' do
let(:usage_ratio) { 0.5 }
it { is_expected.to eq(true) }
context 'when feature flag :temporary_storage_increase disabled' do
before do
stub_feature_flags(temporary_storage_increase: false)
end
context 'when feature flag :namespace_storage_limit disabled' do
let(:namespace_storage_limit_enabled) { false }
it { is_expected.to eq(false) }
end
it { is_expected.to eq(false) }
end
context 'when feature flag :namespace_storage_limit disabled' do
let(:namespace_storage_limit_enabled) { false }
it { is_expected.to eq(true) }
end
end
context 'when usage ratio is below the threshold' do
let(:usage_ratio) { 0.49 }
context 'when feature flag :namespace_storage_limit disabled' do
let(:namespace_storage_limit_enabled) { false }
it { is_expected.to eq(false) }
end
it { is_expected.to eq(false) }
end
end
describe 'validations' do
it { is_expected.to validate_presence_of(:namespace) }
context 'namespace_is_root_namespace' do
let(:namespace_limit) { build(:namespace_limit, namespace: namespace)}
context 'when associated namespace is root' do
let(:namespace) { build(:group, parent: nil) }
it { is_expected.to be_valid }
end
context 'when associated namespace is not root' do
let(:namespace) { build(:group, :nested) }
it 'is invalid' do
expect(subject).to be_invalid
expect(subject.errors[:namespace]).to include('must be a root namespace')
end
end
end
context 'temporary_storage_increase_set_once' do
context 'when temporary_storage_increase_ends_on was nil' do
it 'can be set' do
namespace_limit.temporary_storage_increase_ends_on = Date.today
expect(namespace_limit).to be_valid
end
end
context 'when temporary_storage_increase_ends_on is already set' do
before do
namespace_limit.update_attribute(:temporary_storage_increase_ends_on, 30.days.ago)
end
it 'can not be set again' do
namespace_limit.temporary_storage_increase_ends_on = Date.today
expect(subject).to be_invalid
expect(subject.errors[:temporary_storage_increase_ends_on]).to include('can only be set once')
end
end
end
context 'temporary_storage_increase_eligibility' do
before do
namespace_limit.temporary_storage_increase_ends_on = Date.today
end
context 'when storage usage is above threshold' do
let(:usage_ratio) { 0.5 }
it { is_expected.to be_valid }
context 'when feature flag :namespace_storage_limit disabled' do
let(:namespace_storage_limit_enabled) { false }
it { is_expected.to be_valid }
end
end
context 'when storage usage is below threshold' do
let(:usage_ratio) { 0.49 }
it 'is invalid' do
expect(namespace_limit).to be_invalid
expect(namespace_limit.errors[:temporary_storage_increase_ends_on]).to include("can only be set with more than 50% usage")
end
context 'when feature flag :namespace_storage_limit disabled' do
let(:namespace_storage_limit_enabled) { false }
it 'is invalid' do
expect(namespace_limit).to be_invalid
expect(namespace_limit.errors[:temporary_storage_increase_ends_on]).to include("can only be set with more than 50% usage")
end
end
end
end
end
end
| 29.572222 | 134 | 0.676498 |
2135f1625304180905778951efc4de4d89b6d979 | 5,255 | class Gdal < Formula
desc "Geospatial Data Abstraction Library"
homepage "https://www.gdal.org/"
url "https://download.osgeo.org/gdal/2.3.2/gdal-2.3.2.tar.xz"
sha256 "3f6d78fe8807d1d6afb7bed27394f19467840a82bc36d65e66316fa0aa9d32a4"
revision 1
bottle do
rebuild 2
sha256 "1ebee988a01554396a8088744237faa72061fa1b9e0d4c62dcef5106b746eb0b" => :mojave
sha256 "fcd1ba09e3309176f3a408a83ba0e77dbd5d97930bf7db2c1bbd1efda0d0acfa" => :high_sierra
sha256 "822726f02695989901e1008c8b9ffb725478c2799835db1d75b0f6dc74a65719" => :sierra
end
head do
url "https://github.com/OSGeo/gdal.git"
depends_on "doxygen" => :build
end
depends_on "cfitsio"
depends_on "epsilon"
depends_on "expat"
depends_on "freexl"
depends_on "geos"
depends_on "giflib"
depends_on "hdf5"
depends_on "jasper"
depends_on "jpeg"
depends_on "json-c"
depends_on "libdap"
depends_on "libgeotiff"
depends_on "libpng"
depends_on "libpq"
depends_on "libspatialite"
depends_on "libtiff"
depends_on "libxml2"
depends_on "netcdf"
depends_on "numpy"
depends_on "pcre"
depends_on "podofo"
depends_on "poppler"
depends_on "proj"
depends_on "python"
depends_on "python@2"
depends_on "sqlite" # To ensure compatibility with SpatiaLite
depends_on "unixodbc" # macOS version is not complete enough
depends_on "webp"
depends_on "xerces-c"
depends_on "xz" # get liblzma compression algorithm library from XZutils
depends_on "zstd"
def install
args = [
# Base configuration
"--prefix=#{prefix}",
"--mandir=#{man}",
"--disable-debug",
"--with-libtool",
"--with-local=#{prefix}",
"--with-opencl",
"--with-threads",
# GDAL native backends
"--with-bsb",
"--with-grib",
"--with-pam",
"--with-pcidsk=internal",
"--with-pcraster=internal",
# Homebrew backends
"--with-curl=/usr/bin/curl-config",
"--with-expat=#{Formula["expat"].prefix}",
"--with-freexl=#{Formula["freexl"].opt_prefix}",
"--with-geos=#{Formula["geos"].opt_prefix}/bin/geos-config",
"--with-geotiff=#{Formula["libgeotiff"].opt_prefix}",
"--with-gif=#{Formula["giflib"].opt_prefix}",
"--with-jpeg=#{Formula["jpeg"].opt_prefix}",
"--with-libjson-c=#{Formula["json-c"].opt_prefix}",
"--with-libtiff=#{Formula["libtiff"].opt_prefix}",
"--with-pg=#{Formula["libpq"].opt_prefix}/bin/pg_config",
"--with-png=#{Formula["libpng"].opt_prefix}",
"--with-spatialite=#{Formula["libspatialite"].opt_prefix}",
"--with-sqlite3=#{Formula["sqlite"].opt_prefix}",
"--with-static-proj4=#{Formula["proj"].opt_prefix}",
"--with-zstd=#{Formula["zstd"].opt_prefix}",
"--with-liblzma=yes",
"--with-cfitsio=/usr/local",
"--with-hdf5=/usr/local",
"--with-netcdf=/usr/local",
"--with-jasper=/usr/local",
"--with-xerces=/usr/local",
"--with-odbc=/usr/local",
"--with-dods-root=/usr/local",
"--with-epsilon=/usr/local",
"--with-webp=/usr/local",
"--with-podofo=/usr/local",
# Explicitly disable some features
"--with-armadillo=no",
"--with-qhull=no",
"--without-grass",
"--without-jpeg12",
"--without-libgrass",
"--without-mysql",
"--without-perl",
"--without-php",
"--without-python",
"--without-ruby",
# Unsupported backends are either proprietary or have no compatible version
# in Homebrew. Podofo is disabled because Poppler provides the same
# functionality and then some.
"--without-gta",
"--without-ogdi",
"--without-fme",
"--without-hdf4",
"--without-openjpeg",
"--without-fgdb",
"--without-ecw",
"--without-kakadu",
"--without-mrsid",
"--without-jp2mrsid",
"--without-mrsid_lidar",
"--without-msg",
"--without-oci",
"--without-ingres",
"--without-dwgdirect",
"--without-idb",
"--without-sde",
"--without-podofo",
"--without-rasdaman",
"--without-sosi",
]
# Work around "error: no member named 'signbit' in the global namespace"
if DevelopmentTools.clang_build_version >= 900
ENV.delete "SDKROOT"
ENV.delete "HOMEBREW_SDKROOT"
end
system "./configure", *args
system "make"
system "make", "install"
if build.stable? # GDAL 2.3 handles Python differently
cd "swig/python" do
system "python3", *Language::Python.setup_install_args(prefix)
system "python2", *Language::Python.setup_install_args(prefix)
end
bin.install Dir["swig/python/scripts/*.py"]
end
system "make", "man" if build.head?
# Force man installation dir: https://trac.osgeo.org/gdal/ticket/5092
system "make", "install-man", "INST_MAN=#{man}"
# Clean up any stray doxygen files
Dir.glob("#{bin}/*.dox") { |p| rm p }
end
test do
# basic tests to see if third-party dylibs are loading OK
system "#{bin}/gdalinfo", "--formats"
system "#{bin}/ogrinfo", "--formats"
if build.stable? # GDAL 2.3 handles Python differently
system "python3", "-c", "import gdal"
system "python2", "-c", "import gdal"
end
end
end
| 30.911765 | 93 | 0.626832 |
d56d459402cf14de60bc3df7a9cebfb1c6ddf1ee | 4,331 | require 'yaml'
class CiDeployment
attr_reader :base_path
attr_accessor :content
def initialize(path)
@base_path = path
@content = {}
end
# ci-deployment:
# ops-depls:
# target_name: concourse-ops
# pipelines:
# ops-depls-generated:
# team: my-team
# config_file: concourse/pipelines/ops-depls-generated.yml
# vars_files:
# - master-depls/concourse-ops/pipelines/credentials-ops-depls-pipeline.yml
# - ops-depls/root-deployment.yml
# ops-depls-cf-apps-generated:
# config_file: concourse/pipelines/ops-depls-cf-apps-generated.yml
# vars_files:
# - master-depls/concourse-ops/pipelines/credentials-ops-depls-pipeline.yml
# - ops-depls/root-deployment.yml
# or
# ci-deployment:
# ops-depls:
# target_name: concourse-ops
# pipelines:
# ops-depls-generated:
# team: my-team
# ops-depls-cf-apps-generated:
def overview
puts "Path CI deployment overview: #{base_path}"
Dir[base_path].select { |file| File.directory? file }.each do |path|
load_ci_deployment_from_dir(path)
end
puts "ci_deployment loaded: \n#{YAML.dump(content)}"
content
end
def self.teams(overview)
ci_deployment_details_per_root_depls = overview.map { |_, ci_deployment_details_for_root_depls| ci_deployment_details_for_root_depls }
pipelines_per_root_depls = ci_deployment_details_per_root_depls.map { |ci_deployment_details| ci_deployment_details['pipelines'] }
pipelines_and_pipeline_configs_2_tuple = pipelines_per_root_depls.inject([]) { |array, item| array + item.to_a }
defined_teams = pipelines_and_pipeline_configs_2_tuple.map { |_, pipeline_config| pipeline_config && pipeline_config['team'] }
defined_teams.compact
.uniq
end
def self.team(overview, root_deployment, pipeline_name)
ci_root_deployment = overview[root_deployment]
ci_pipelines = ci_root_deployment['pipelines'] unless ci_root_deployment.nil?
ci_pipeline_found = ci_pipelines[pipeline_name] unless ci_pipelines.nil?
ci_pipeline_found['team'] unless ci_pipeline_found.nil?
end
private
def load_ci_deployment_from_dir(path)
dir_basename = File.basename(path)
puts "Processing #{dir_basename}"
Dir[path + '/ci-deployment-overview.yml'].each do |deployment_file|
load_ci_deployment_from_file(deployment_file, dir_basename)
end
end
def load_ci_deployment_from_file(deployment_file, dir_basename)
puts "CI deployment detected in #{dir_basename}"
deployment = YAML.load_file(deployment_file)
raise "#{deployment} - Invalid deployment: expected 'ci-deployment' key as yaml root" unless deployment && deployment['ci-deployment']
begin
deployment['ci-deployment'].each do |root_deployment_name, root_deployment_details|
processes_ci_deployment_data(root_deployment_name, root_deployment_details, dir_basename)
end
rescue RuntimeError => runtime_error
raise "#{deployment_file}: #{runtime_error}"
end
end
def processes_ci_deployment_data(root_deployment_name, root_deployment_details, dir_basename)
raise 'missing keys: expecting keys target and pipelines' unless root_deployment_details
raise "Invalid deployment: expected <#{dir_basename}> - Found <#{root_deployment_name}>" if root_deployment_name != dir_basename
content[root_deployment_name] = root_deployment_details
raise 'No target defined: expecting a target_name' unless root_deployment_details['target_name']
raise 'No pipeline detected: expecting at least one pipeline' unless root_deployment_details['pipelines']
processes_pipeline_definitions(root_deployment_details)
end
def processes_pipeline_definitions(deployment_details)
deployment_details['pipelines'].each do |pipeline_name, pipeline_details|
next unless pipeline_details
unless pipeline_details_config_file?(pipeline_details)
puts "Generating default value for key config_file in #{pipeline_name}"
pipeline_details['config_file'] = "concourse/pipelines/#{pipeline_name}.yml"
end
end
end
def pipeline_details_config_file?(pipeline_details)
return false unless pipeline_details
pipeline_details.key?('config_file')
end
end
| 37.017094 | 138 | 0.734472 |
6a7354f33ecbb5a92786fc32686b0fc606a41b98 | 1,398 | module ActiveRecord
module ConnectionAdapters
module SQLServer
module Type
class Time < ActiveRecord::Type::Time
# Default fractional scale for 'time' (See https://docs.microsoft.com/en-us/sql/t-sql/data-types/time-transact-sql)
DEFAULT_FRACTIONAL_SCALE = 7
include TimeValueFractional2
def serialize(value)
value = super
return value unless value.acts_like?(:time)
time = value.to_s(:_sqlserver_time).tap do |v|
fraction = quote_fractional(value)
v << ".#{fraction}"
end
Data.new time, self
end
def deserialize(value)
value.is_a?(Data) ? super(value.value) : super
end
def type_cast_for_schema(value)
serialize(value).quoted
end
def sqlserver_type
"time(#{precision.to_i})"
end
def quoted(value)
Utils.quote_string_single(value)
end
private
def cast_value(value)
value = super
return if value.blank?
value = value.change year: 2000, month: 01, day: 01
apply_seconds_precision(value)
end
def fractional_scale
precision || DEFAULT_FRACTIONAL_SCALE
end
end
end
end
end
end
| 24.964286 | 125 | 0.550787 |
e2505ef295d07c407368ec98fa345ff33956b1a7 | 110 | require_relative "<%= name %>/version"
require_relative "<%= name %>/generator"
module <%= moduleName %>
end
| 18.333333 | 40 | 0.681818 |
0133b275cbfbdf7902add323dbb5e094fdf0a83f | 156 | actions :create, :delete
default_action :create
attribute :hint_name, kind_of: String, name_attribute: true
attribute :content, kind_of: Hash, default: {}
| 26 | 59 | 0.782051 |
6118aa06ca400747b9d320110a5ea2be1c9780bd | 1,185 | # frozen_string_literal: true
module Feedjira
class Feed
class << self
def add_common_feed_element(element_tag, options = {})
Feedjira.parsers.each do |k|
k.element(element_tag, options)
end
end
def add_common_feed_elements(element_tag, options = {})
Feedjira.parsers.each do |k|
k.elements(element_tag, options)
end
end
def add_common_feed_entry_element(element_tag, options = {})
call_on_each_feed_entry(:element, element_tag, options)
end
def add_common_feed_entry_elements(element_tag, options = {})
call_on_each_feed_entry(:elements, element_tag, options)
end
private
def call_on_each_feed_entry(method, *parameters)
Feedjira.parsers.each do |klass|
klass.sax_config.collection_elements.each_value do |value|
collection_configs = value.select do |v|
v.accessor == "entries" && v.data_class.is_a?(Class)
end
collection_configs.each do |config|
config.data_class.send(method, *parameters)
end
end
end
end
end
end
end
| 26.931818 | 68 | 0.627004 |
39b56866a48521fd6f96fba2a89986b87cac4151 | 7,110 | require 'yaml'
module EY
module Serverside
class RailsAssets
module Strategy
def self.all
{
'shared' => Shared,
'cleaning' => Cleaning,
'private' => Private,
'shifting' => Shifting,
}
end
def self.fetch(name, *args)
(all[name.to_s] || Shifting).new(*args)
end
# Precompile assets fresh every time. Shared assets are not symlinked
# and assets stay with the release that compiled them. The assets of
# the previous deploy are symlinked as into the current deploy to
# prevent errors during deploy.
#
# When no assets changes are detected, the deploy uses rsync to copy
# the previous release's assets into the current assets directory.
class Private
attr_reader :paths, :runner
def initialize(paths, runner)
@paths = paths
@runner = runner
end
def reuse
run "mkdir -p #{paths.public_assets} && rsync -aq #{previous_assets_path}/ #{paths.public_assets}"
end
# link the previous assets into the new public/last_assets/assets
# to prevent missing assets during deploy.
#
# This results in the directory structure:
# deploy_root/current/public/last_assets/assets -> deploy_root/releases/<prev>/public/assets
def prepare
last = paths.public.join('last_assets')
run "mkdir -p #{last} && ln -nfs #{previous_assets_path} #{last.join('assets')}"
yield
end
protected
def run(cmd)
runner.run cmd
end
def previous_assets_path
paths.previous_release(paths.active_release).join('public','assets')
end
end
# Basic shared assets.
# Precompiled assets go into a single shared assets directory. The
# assets directory is never cleaned, so a deploy hook should be used
# to clean assets appropriately.
#
# When no assets changes are detected, shared directory is only
# symlinked and precompile task is not run.
class Shared
attr_reader :paths, :runner
def initialize(paths, runner)
@paths = paths
@runner = runner
end
def reuse
run "mkdir -p #{shared_assets_path} && ln -nfs #{shared_assets_path} #{paths.public}"
end
def prepare
reuse
yield
end
protected
def run(cmd)
runner.run(cmd)
end
def shared_assets_path
paths.shared_assets
end
end
# Precompiled assets are shared across all deploys like Shared.
# Before compiling the active deploying assets, all assets that are not
# referenced by the manifest.yml from the previous deploy are removed.
# After cleaning, the new assets are compiled over the top. The result
# is an assets dir that contains the last assets and the current assets.
#
# When no assets changes are detected, shared directory is only
# symlinked and cleaning and precompile tasks are not run.
class Cleaning < Shared
def prepare
reuse
remove_old_assets
yield
rescue
# how do you restore back to the old assets if some have been overwritten?
# probably just deploy again I suppose.
raise
end
protected
def remove_old_assets
return unless manifest_path.readable?
Dir.chdir(shared_assets_path)
all_assets_on_disk = Dir.glob(shared_assets_path.join('**','*.*').to_s) - [manifest_path.to_s]
$stderr.puts "all_assets_on_disk #{all_assets_on_disk.inspect}"
assets_on_disk = all_assets_on_disk.reject {|a| a =~ /\.gz$/}
$stderr.puts "assets_on_disk #{assets_on_disk.inspect}"
assets_in_manifest = YAML.load_file(manifest_path.to_s).values
$stderr.puts "assets_in_manifest #{assets_in_manifest.inspect}"
remove_assets = []
(assets_on_disk - assets_in_manifest).each do |asset|
remove_assets << "'#{asset}'"
remove_assets << "'#{asset}.gz'" if all_assets_on_disk.include?("#{asset}.gz")
end
run("rm -rf #{remove_assets.join(' ')}")
end
def manifest_path
shared_assets_path.join('manifest.yml')
end
end
# The default behavior and the one used since the beginning of asset
# support in engineyard-serverside. Assets are compiled into a fresh
# shared directory. Previous shared assets are shifted to a last_assets
# directory to prevent errors during deploy.
#
# When no assets changes are detected, the two shared directories are
# symlinked into the active release without any changes.
class Shifting < Shared
# link shared/assets and shared/last_assets into public
def reuse
run "mkdir -p #{shared_assets_path} #{last_assets_path} && #{link_assets}"
end
def prepare
shift_existing_assets
yield
rescue
unshift_existing_assets
raise
end
protected
def last_assets_path
paths.shared.join('last_assets')
end
# If there are current shared assets, move them under a 'last_assets' directory.
#
# To support operations like Unicorn's hot reload, it is useful to have
# the prior release's assets as well. Otherwise, while a deploy is running,
# clients may request stale assets that you just deleted.
# Making use of this requires a properly-configured front-end HTTP server.
#
# Note: This results in the directory structure:
# deploy_root/current/public/assets -> deploy_root/shared/assets
# deploy_root/current/public/last_assets -> deploy_root/shared/last_assets
# where last_assets has an assets dir under it.
# deploy_root/shared/last_assets/assets
def shift_existing_assets
run "rm -rf #{last_assets_path} && mkdir -p #{shared_assets_path} #{last_assets_path} && mv #{shared_assets_path} #{last_assets_path.join('assets')} && mkdir -p #{shared_assets_path} && #{link_assets}"
end
# Restore shared/last_assets to shared/assets and relink them to the app public
def unshift_existing_assets
run "rm -rf #{shared_assets_path} && mv #{last_assets_path.join('assets')} #{shared_assets_path} && mkdir -p #{last_assets_path} && #{link_assets}"
end
def link_assets
"ln -nfs #{shared_assets_path} #{last_assets_path} #{paths.public}"
end
end
end
end
end
end
| 35.909091 | 213 | 0.595499 |
61681f85265b71f070229eb73d6a397189cad200 | 48 | module CocoapodsArchive
VERSION = "0.0.2"
end
| 12 | 23 | 0.729167 |
e852dfc502232d9d8d8cd4a3370d817e0fad8c2e | 988 | Refinery::Core::Engine.routes.draw do
root to: 'pages#home', via: :get
get '/pages/:id', to: 'pages#show', as: :page
namespace :pages, path: '' do
namespace :admin, path: Refinery::Core.backend_route do
scope path: :pages do
post 'preview', to: 'preview#show', as: :preview_pages
patch 'preview/*path', to: 'preview#show', as: :preview_page
end
end
end
namespace :admin, path: Refinery::Core.backend_route do
get 'pages/*path/edit', to: 'pages#edit', as: 'edit_page'
get 'pages/*path/children', to: 'pages#children', as: 'children_pages'
patch 'pages/*path', to: 'pages#update', as: 'update_page'
delete 'pages/*path', to: 'pages#destroy', as: 'delete_page'
resources :pages, except: :show do
post :update_positions, on: :collection
end
resources :pages_dialogs, only: [] do
collection do
get :link_to
end
end
resources :page_parts, only: [:new, :create, :destroy]
end
end
| 29.939394 | 74 | 0.635628 |
e28085b132f4b5a4acf6a11a2a86251cd9f63a78 | 6,958 | #-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2018 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2017 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
#-- encoding: UTF-8
# This file included as part of the acts_as_journalized plugin for
# the redMine project management software; You can redistribute it
# and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# The original copyright and license conditions are:
# Copyright (c) 2009 Steve Richert
#
# 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.
module Redmine::Acts::Journalized
# An extension module for the +has_many+ association with journals.
module Versions
# Returns all journals between (and including) the two given arguments. See documentation for
# the +at+ extension method for what arguments are valid. If either of the given arguments is
# invalid, an empty array is returned.
#
# The +between+ method preserves returns an array of journal records, preserving the order
# given by the arguments. If the +from+ value represents a journal before that of the +to+
# value, the array will be ordered from earliest to latest. The reverse is also true.
def between(from, to)
from_number = journal_at(from)
to_number = journal_at(to)
return [] if from_number.nil? || to_number.nil?
condition = (from_number == to_number) ? to_number : Range.new(*[from_number, to_number].sort)
where(version: condition)
.order("#{Journal.table_name}.version #{(from_number > to_number) ? 'DESC' : 'ASC'}")
end
# Returns all journal records created before the journal associated with the given value.
def before(value)
return [] if (version = journal_at(value)).nil?
where("#{Journal.table_name}.version < ?", version)
end
# Returns all journal records created after the journal associated with the given value.
#
# This is useful for dissociating records during use of the +reset_to!+ method.
def after(value)
return [] if (version = journal_at(value)).nil?
where("#{Journal.table_name}.version > ?", version)
end
# Returns a single journal associated with the given value. The following formats are valid:
# * A Date or Time object: When given, +to_time+ is called on the value and the last journal
# record in the history created before (or at) that time is returned.
# * A Numeric object: Typically a positive integer, these values correspond to journal numbers
# and the associated journal record is found by a journal number equal to the given value
# rounded down to the nearest integer.
# * A String: A string value represents a journal tag and the associated journal is searched
# for by a matching tag value. *Note:* Be careful with string representations of numbers.
# * A Symbol: Symbols represent association class methods on the +has_many+ journals
# association. While all of the built-in association methods require arguments, additional
# extension modules can be defined using the <tt>:extend</tt> option on the +journaled+
# method. See the +journaled+ documentation for more information.
# * A Version object: If a journal object is passed to the +at+ method, it is simply returned
# untouched.
def at(value)
case value
when Date, Time then where(["#{Journal.table_name}.created_at <= ?", value.to_time]).last
when Numeric then find_by(version: value.floor)
when Symbol then respond_to?(value) ? send(value) : nil
when Journal then value
end
end
# Returns the journal number associated with the given value. In many cases, this involves
# simply passing the value to the +at+ method and then returning the subsequent journal number.
# Hoever, for Numeric values, the journal number can be returned directly and for Date/Time
# values, a default value of 1 is given to ensure that times prior to the first journal
# still return a valid journal number (useful for rejournal).
def journal_at(value)
case value
when Date, Time then (v = at(value)) ? v.version : 1
when Numeric then value.floor
when Symbol then (v = at(value)) ? v.version : nil
when String then nil
when Journal then value.version
end
end
end
end
| 49.7 | 100 | 0.732251 |
01cddfc582a44caae5455dede3b3144bfbb7433a | 242 | # frozen_string_literal: true
DB_CONNECTION_INFO = {
user: ENV['DB_USERNAME'],
password: ENV['DB_PASSWORD'],
host: ENV['DB_HOST'] || 'localhost',
port: ENV['DB_PORT'],
database: ENV['DB_DATABASE'] || 'valkyrie_sequel_test'
}.freeze
| 26.888889 | 56 | 0.694215 |
116547e883237f7494fdb3b5bd58d4f3b2814302 | 2,635 | #
# Copyright 2014-2021 Chef Software, 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.
#
# A requirement for api.berkshelf.com that is used in berkshelf specs
# https://github.com/berkshelf/api.berkshelf.com
name "libarchive"
default_version "3.5.1"
license "BSD-2-Clause"
license_file "COPYING"
skip_transitive_dependency_licensing true
version("3.5.1") { source sha256: "9015d109ec00bb9ae1a384b172bf2fc1dff41e2c66e5a9eeddf933af9db37f5a" }
version("3.5.0") { source sha256: "fc4bc301188376adc18780d35602454cc8df6396e1b040fbcbb0d4c0469faf54" }
version("3.4.3") { source sha256: "ee1e749213c108cb60d53147f18c31a73d6717d7e3d2481c157e1b34c881ea39" }
version("3.4.2") { source sha256: "b60d58d12632ecf1e8fad7316dc82c6b9738a35625746b47ecdcaf4aed176176" }
version("3.4.1") { source sha256: "fcf87f3ad8db2e4f74f32526dee62dd1fb9894782b0a503a89c9d7a70a235191" }
version("3.4.0") { source sha256: "8643d50ed40c759f5412a3af4e353cffbce4fdf3b5cf321cb72cacf06b2d825e" }
# 3.5.1 no longer includes the "v" in the path
if version.satisfies?(">= 3.5.1")
source url: "https://github.com/libarchive/libarchive/releases/download/#{version}/libarchive-#{version}.tar.gz"
else
source url: "https://github.com/libarchive/libarchive/releases/download/v#{version}/libarchive-#{version}.tar.gz"
end
relative_path "libarchive-#{version}"
dependency "config_guess"
dependency "libxml2"
dependency "bzip2"
dependency "zlib"
dependency "liblzma"
build do
env = with_standard_compiler_flags(with_embedded_path)
update_config_guess(target: "build/autoconf/")
configure_args = [
"--prefix=#{install_dir}/embedded",
"--without-lzo2",
"--without-nettle",
"--without-expat",
"--without-iconv",
"--disable-bsdtar", # tar command line tool
"--disable-bsdcpio", # cpio command line tool
"--disable-bsdcat", # cat w/ decompression command line tool
"--without-openssl",
"--without-zstd",
"--without-lz4",
]
if s390x?
configure_args << "--disable-xattr --disable-acl"
end
configure configure_args.join(" "), env: env
make "-j #{workers}", env: env
make "-j #{workers} install", env: env
end
| 34.671053 | 115 | 0.746869 |
6ae797b434985f7e413c0f3ee12f0a852f593e10 | 621 | class CreatePartners < ActiveRecord::Migration
def change
create_table :contacts do |t|
t.string :name
t.belongs_to :donor_account
t.belongs_to :account_list
t.timestamps
end
add_index :contacts, [:donor_account_id, :account_list_id], unique: true
add_index :contacts, :account_list_id
remove_column :people, :account_list_id
# Make address polymorphic
add_column :addresses, :addressable_type, :string
rename_column :addresses, :person_id, :addressable_id
ActiveRecord::Base.connection.update("update addresses set addressable_type = 'Person'")
end
end
| 29.571429 | 92 | 0.731079 |
bb847c9d0ed7fc2af6cb7d905066a0056d720f8b | 3,272 | require 'spaceship/test_flight/build'
require_relative 'ui/ui'
module FastlaneCore
class BuildWatcher
class << self
# @return The build we waited for. This method will always return a build
def wait_for_build_processing_to_be_complete(app_id: nil, platform: nil, train_version: nil, build_version: nil, poll_interval: 10, strict_build_watch: false)
unless strict_build_watch
# First, find the train and build version we want to watch for
watched_build = watching_build(app_id: app_id, platform: platform)
UI.crash!("Could not find a build for app: #{app_id} on platform: #{platform}") if watched_build.nil?
unless watched_build.train_version == train_version && watched_build.build_version == build_version
UI.important("Started watching build #{watched_build.train_version} - #{watched_build.build_version} but expected #{train_version} - #{build_version}")
end
train_version = watched_build.train_version
build_version = watched_build.build_version
end
loop do
matched_build = matching_build(watched_train_version: train_version, watched_build_version: build_version, app_id: app_id, platform: platform)
report_status(build: matched_build)
if matched_build && matched_build.processed?
return matched_build
end
sleep(poll_interval)
end
end
private
def watching_build(app_id: nil, platform: nil)
processing_builds = Spaceship::TestFlight::Build.all_processing_builds(app_id: app_id, platform: platform, retry_count: 2)
watched_build = processing_builds.sort_by(&:upload_date).last
watched_build || Spaceship::TestFlight::Build.latest(app_id: app_id, platform: platform)
end
def matching_build(watched_train_version: nil, watched_build_version: nil, app_id: nil, platform: nil)
matched_builds = Spaceship::TestFlight::Build.builds_for_train(app_id: app_id, platform: platform, train_version: watched_train_version, retry_count: 2)
matched_builds.find { |build| build.build_version == watched_build_version }
end
def report_status(build: nil)
# Due to iTunes Connect, builds disappear from the build list altogether
# after they finished processing. Before returning this build, we have to
# wait for the build to appear in the build list again
# As this method is very often used to wait for a build, and then do something
# with it, we have to be sure that the build actually is ready
if build.nil?
UI.message("Build doesn't show up in the build list anymore, waiting for it to appear again")
elsif build.active?
UI.success("Build #{build.train_version} - #{build.build_version} is already being tested")
elsif build.ready_to_submit? || build.export_compliance_missing? || build.review_rejected?
UI.success("Successfully finished processing the build #{build.train_version} - #{build.build_version}")
else
UI.message("Waiting for iTunes Connect to finish processing the new build (#{build.train_version} - #{build.build_version})")
end
end
end
end
end
| 48.117647 | 164 | 0.702934 |
1a96a81ad66708f8e45c032737a821d3a5d12ebc | 2,512 | # Copyright (C) The Arvados Authors. All rights reserved.
#
# SPDX-License-Identifier: AGPL-3.0
Disable_update_jobs_api_method_list = {"jobs.create"=>{},
"pipeline_instances.create"=>{},
"pipeline_templates.create"=>{},
"jobs.update"=>{},
"pipeline_instances.update"=>{},
"pipeline_templates.update"=>{},
"job_tasks.create"=>{},
"job_tasks.update"=>{}}
Disable_jobs_api_method_list = {"jobs.create"=>{},
"pipeline_instances.create"=>{},
"pipeline_templates.create"=>{},
"jobs.get"=>{},
"pipeline_instances.get"=>{},
"pipeline_templates.get"=>{},
"jobs.list"=>{},
"pipeline_instances.list"=>{},
"pipeline_templates.list"=>{},
"jobs.index"=>{},
"pipeline_instances.index"=>{},
"pipeline_templates.index"=>{},
"jobs.update"=>{},
"pipeline_instances.update"=>{},
"pipeline_templates.update"=>{},
"jobs.queue"=>{},
"jobs.queue_size"=>{},
"job_tasks.create"=>{},
"job_tasks.get"=>{},
"job_tasks.list"=>{},
"job_tasks.index"=>{},
"job_tasks.update"=>{},
"jobs.show"=>{},
"pipeline_instances.show"=>{},
"pipeline_templates.show"=>{},
"job_tasks.show"=>{}}
def check_enable_legacy_jobs_api
# Create/update is permanently disabled (legacy functionality has been removed)
Rails.configuration.API.DisabledAPIs.merge! Disable_update_jobs_api_method_list
if Rails.configuration.Containers.JobsAPI.Enable == "false" ||
(Rails.configuration.Containers.JobsAPI.Enable == "auto" &&
Job.count == 0)
Rails.configuration.API.DisabledAPIs.merge! Disable_jobs_api_method_list
end
end
| 49.254902 | 81 | 0.419188 |
1de84309d15e2386c31b4eeebf98359add9ff555 | 3,762 | module Gitlab
module Satellite
class Satellite
include Gitlab::Popen
PARKING_BRANCH = "__parking_branch"
attr_accessor :project
def initialize(project)
@project = project
end
def log(message)
Gitlab::Satellite::Logger.error(message)
end
def clear_and_update!
project.ensure_satellite_exists
@repo = nil
clear_working_dir!
delete_heads!
remove_remotes!
update_from_source!
end
def create
output, status = popen(%W(git clone -- #{project.repository.path_to_repo} #{path}),
Gitlab.config.satellites.path)
log("PID: #{project.id}: git clone #{project.repository.path_to_repo} #{path}")
log("PID: #{project.id}: -> #{output}")
if status.zero?
true
else
log("Failed to create satellite for #{project.name_with_namespace}")
false
end
end
def exists?
File.exists? path
end
# * Locks the satellite
# * Changes the current directory to the satellite's working dir
# * Yields
def lock
project.ensure_satellite_exists
File.open(lock_file, "w+") do |f|
begin
f.flock File::LOCK_EX
yield
ensure
f.flock File::LOCK_UN
end
end
end
def lock_file
create_locks_dir unless File.exists?(lock_files_dir)
File.join(lock_files_dir, "satellite_#{project.id}.lock")
end
def path
File.join(Gitlab.config.satellites.path, project.path_with_namespace)
end
def repo
project.ensure_satellite_exists
@repo ||= Grit::Repo.new(path)
end
def destroy
FileUtils.rm_rf(path)
end
private
# Clear the working directory
def clear_working_dir!
repo.git.reset(hard: true)
repo.git.clean(f: true, d: true, x: true)
end
# Deletes all branches except the parking branch
#
# This ensures we have no name clashes or issues updating branches when
# working with the satellite.
def delete_heads!
heads = repo.heads.map(&:name)
# update or create the parking branch
if heads.include? PARKING_BRANCH
repo.git.checkout({}, PARKING_BRANCH)
else
repo.git.checkout(default_options({b: true}), PARKING_BRANCH)
end
# remove the parking branch from the list of heads ...
heads.delete(PARKING_BRANCH)
# ... and delete all others
heads.each { |head| repo.git.branch(default_options({D: true}), head) }
end
# Deletes all remotes except origin
#
# This ensures we have no remote name clashes or issues updating branches when
# working with the satellite.
def remove_remotes!
remotes = repo.git.remote.split(' ')
remotes.delete('origin')
remotes.each { |name| repo.git.remote(default_options,'rm', name)}
end
# Updates the satellite from bare repo
#
# Note: this will only update remote branches (i.e. origin/*)
def update_from_source!
repo.git.remote(default_options, 'set-url', :origin, project.repository.path_to_repo)
repo.git.fetch(default_options, :origin)
end
def default_options(options = {})
{raise: true, timeout: true}.merge(options)
end
# Create directory for storing
# satellites lock files
def create_locks_dir
FileUtils.mkdir_p(lock_files_dir)
end
def lock_files_dir
@lock_files_dir ||= File.join(Gitlab.config.satellites.path, "tmp")
end
end
end
end
| 26.125 | 93 | 0.600213 |
79e6426330aa586b7a77314b4c829ccf2dda3099 | 308 | # coding: utf-8
require 'numeric_with_unit/unit_definition/base'
Unit['cal'] = "4.184".to_r, 'J'
Unit['Gal'] = 'cm/s2'
Unit['dyn'] = 'g.cm/s2'
Unit['erg'] = 'g.cm2/s2'
Unit['Ba'] = 'g/(cm.s2)'
Unit['P'] = 'g/(cm.s)'
Unit['poise'] = 'g/(cm.s)'
Unit['St'] = 'cm2/s'
Unit['dyn'] = "1/100000".to_r, 'N'
| 14.666667 | 48 | 0.542208 |
261832d8299b4a5ec5e6318cd290bddaa00e44d7 | 260 | describe Issue::Error do
it "has a status and a message" do
error = Issue::Error.new(403, "Forbidden action. Request not accepted.")
expect(error.status).to eq(403)
expect(error.message).to eq("Forbidden action. Request not accepted.")
end
end
| 32.5 | 76 | 0.707692 |
ab0211352fee8ce1e34ecabb0e3c64010f33c789 | 414 | module SCSSLint
# Checks for spaces following the name of a property and before the colon
# separating the property's name from its value.
class Linter::SpaceAfterPropertyName < Linter
include LinterRegistry
def visit_prop(node)
if character_at(node.name_source_range.end_pos) != ':'
add_lint node, 'Property name should be immediately followed by a colon'
end
end
end
end
| 29.571429 | 80 | 0.727053 |
1a103f3f8ce385c644684d5108b9b84b42ad2fc6 | 732 | #
# Author:: Joshua Timberman (<[email protected]>)
# Cookbook Name:: php
# Libraries:: helpers
#
# Copyright 2013, Opscode, 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.
#
def el5_range
(0..99).to_a.map{|i| "5.#{i}"}
end
| 30.5 | 74 | 0.730874 |
1d039ff505be5b35215827ffbc4b078edab25d89 | 813 | module Dickens
class FindItem
attr_accessor :article, :dictionary, :word, :matching
def initialize(array, word)
extract = /-->(?<dic>.*)\n-->(?<w>.*)\n\n(?<a>[\W|\w|.]*)/.match(array)
@dictionary= extract[:dic]
@word= extract[:w]
@article= extract[:a].strip
@matching= (@word == word)
end
def to_s
"-->#{dictionary}\n-->#{word}\n===\n#{article}"
end
def self.parse(string,word)
out=[]
#split console output by article delimiter but preserve the delimiter info
#then slice them by pairs [delimiter, article] and join back
#then initialize FindItems
string.split(/(-->.*\n-->.*\n)/).reject(&:empty?).each_slice(2).map(&:join).each do |e|
out<<Dickens::FindItem.new(e, word)
end
out
end
end
end | 28.034483 | 93 | 0.578106 |
6ab0a35822ae294b25c9ac97bdb263c177274f91 | 640 | Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root to: 'trips#index'
get '/welcome', to: 'static#welcome'
get '/auth/github/callback', to: 'sessions#create_from_github'
resources :trip_entries, only: [:show]
resources :trips do
resources :trip_entries
end
resources :users, only: [:show]
resources :locations, only: [:new, :create]
get '/signup', to: 'users#new'
post '/signup', to: 'users#create'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
end
| 25.6 | 101 | 0.685938 |
915f5439db509e537f89d8180776b65df944f945 | 172 | # frozen_string_literal: true
module CoreExtensions
module Kafka
module BrokerPool
module AttrReaders
attr_reader :brokers
end
end
end
end
| 14.333333 | 29 | 0.69186 |
1c50ef255b87844143a3f314b08f559d4e0a3879 | 3,721 | # encoding: utf-8
require 'sinatra'
require 'sprockets'
require 'sinatra/content_for'
require 'rufus/scheduler'
require 'coffee-script'
require 'sass'
require 'json'
require 'yaml'
SCHEDULER = Rufus::Scheduler.start_new
set :root, Dir.pwd
set :sprockets, Sprockets::Environment.new(settings.root)
set :assets_prefix, '/assets'
set :digest_assets, false
['assets/javascripts', 'assets/stylesheets', 'assets/fonts', 'assets/images', 'widgets', File.expand_path('../../javascripts', __FILE__)]. each do |path|
settings.sprockets.append_path path
end
set server: 'thin', connections: [], history_file: 'history.yml'
# Persist history in tmp file at exit
at_exit do
File.open(settings.history_file, 'w') do |f|
f.puts settings.history.to_yaml
end
end
if File.exists?(settings.history_file)
set history: YAML.load_file(settings.history_file)
else
set history: {}
end
set :public_folder, File.join(settings.root, 'public')
set :views, File.join(settings.root, 'dashboards')
set :default_dashboard, nil
set :auth_token, nil
helpers Sinatra::ContentFor
helpers do
def protected!
# override with auth logic
end
end
get '/events', provides: 'text/event-stream' do
protected!
response.headers['X-Accel-Buffering'] = 'no' # Disable buffering for nginx
stream :keep_open do |out|
settings.connections << out
out << latest_events
out.callback { settings.connections.delete(out) }
end
end
get '/' do
begin
redirect "/" + (settings.default_dashboard || first_dashboard).to_s
rescue NoMethodError => e
raise Exception.new("There are no dashboards in your dashboard directory.")
end
end
get '/:dashboard' do
protected!
tilt_html_engines.each do |suffix, _|
file = File.join(settings.views, "#{params[:dashboard]}.#{suffix}")
return render(suffix.to_sym, params[:dashboard].to_sym) if File.exist? file
end
halt 404
end
get '/views/:widget?.html' do
protected!
tilt_html_engines.each do |suffix, engines|
file = File.join(settings.root, "widgets", params[:widget], "#{params[:widget]}.#{suffix}")
return engines.first.new(file).render if File.exist? file
end
end
post '/widgets/:id' do
request.body.rewind
body = JSON.parse(request.body.read)
auth_token = body.delete("auth_token")
if !settings.auth_token || settings.auth_token == auth_token
send_event(params['id'], body)
204 # response without entity body
else
status 401
"Invalid API key\n"
end
end
not_found do
send_file File.join(settings.public_folder, '404.html')
end
def development?
ENV['RACK_ENV'] == 'development'
end
def production?
ENV['RACK_ENV'] == 'production'
end
def send_event(id, body)
body[:id] = id
body[:updatedAt] ||= Time.now.to_i
event = format_event(body.to_json)
Sinatra::Application.settings.history[id] = event
Sinatra::Application.settings.connections.each { |out| out << event }
end
def format_event(body)
"data: #{body}\n\n"
end
def latest_events
settings.history.inject("") do |str, (id, body)|
str << body
end
end
def first_dashboard
files = Dir[File.join(settings.views, '*')].collect { |f| File.basename(f, '.*') }
files -= ['layout']
files.first
end
def tilt_html_engines
Tilt.mappings.select do |_, engines|
default_mime_type = engines.first.default_mime_type
default_mime_type.nil? || default_mime_type == 'text/html'
end
end
Dir[File.join(settings.root, 'lib', '**', '*.rb')].each {|file| require file }
{}.to_json # Forces your json codec to initialize (in the event that it is lazily loaded). Does this before job threads start.
job_path = ENV["JOB_PATH"] || 'jobs'
files = Dir[File.join(settings.root, job_path, '**', '/*.rb')]
files.each { |job| require(job) }
| 25.312925 | 153 | 0.708949 |
79c89025c423ccd7fb5ad230983255c6a93407e6 | 96 | Rails.application.routes.draw do
devise_for :users
root 'home#index'
resources :tasks
end
| 16 | 32 | 0.760417 |
d57344e8ef103ed3e6ff77e471b4a682d898bcc5 | 909 | # frozen_string_literal: true
module SpecSupport
module Login
def mock_logged_in_user(super_admin: false)
controller.session[::Login::SESSION_KEY] =
create(:person, ditsso_user_id: '007', super_admin: super_admin).id
end
def current_user
Person.find_by(ditsso_user_id: '007')
end
def omni_auth_log_in_as(ditsso_user_id)
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[:ditsso_internal] = OmniAuth::AuthHash.new(
provider: 'ditsso_internal',
uid: ditsso_user_id,
info: {
email: '[email protected]',
user_id: ditsso_user_id,
first_name: 'John',
last_name: 'Doe',
name: 'John Doe'
}
)
visit '/auth/ditsso_internal'
end
def omni_auth_log_in_as_super_admin
omni_auth_log_in_as create(:super_admin).ditsso_user_id
end
end
end
| 24.567568 | 75 | 0.651265 |
bb5ba78ff21d755e9ac199f0c0a02e23b54438ca | 337 | Rails.application.routes.draw do
root 'static_pages#home'
get '/help', to: 'static_pages#help'
get '/about', to: 'static_pages#about'
get '/contact', to: 'static_pages#contact'
get '/signup', to: 'users#new'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
| 33.7 | 101 | 0.688427 |
ff4826fded1aff5d1e833dcf3fbb14f15e2c9fbe | 329 | ##
# Delivers the UserMailer.deliver_mimi_welcome to the requested User by +id+
# as an asynchronous process.
#
class DeliverWelcomeJob
def initialize(user_id)
@user_id = user_id
end
def perform
if user = User.find_by_id(@user_id)
BlueLightSpecialMailer.deliver_mimi_welcome(user)
end
end
end
| 18.277778 | 76 | 0.720365 |
876b3a91783f879f7a25b0ca476e19c8f2883daf | 198 | class ApplicationController < ActionController::API
include ActionController::ImplicitRender
include ActionController::Serialization
include Acl9::ControllerExtensions
respond_to :json
end
| 24.75 | 51 | 0.838384 |
bb93e6ad65bf232614891b7d6f097dbf955666d2 | 5,994 | # Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
# stub: devise-i18n 1.7.0 ruby lib
Gem::Specification.new do |s|
s.name = "devise-i18n".freeze
s.version = "1.7.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["Christopher Dell".freeze, "mcasimir".freeze, "Jason Barnabe".freeze]
s.date = "2018-11-11"
s.description = "Translations for the devise gem".freeze
s.email = "[email protected]".freeze
s.extra_rdoc_files = [
"LICENSE.txt",
"README.md"
]
s.files = [
"VERSION",
"app/views/devise/confirmations/new.html.erb",
"app/views/devise/mailer/confirmation_instructions.html.erb",
"app/views/devise/mailer/email_changed.html.erb",
"app/views/devise/mailer/password_change.html.erb",
"app/views/devise/mailer/reset_password_instructions.html.erb",
"app/views/devise/mailer/unlock_instructions.html.erb",
"app/views/devise/passwords/edit.html.erb",
"app/views/devise/passwords/new.html.erb",
"app/views/devise/registrations/edit.html.erb",
"app/views/devise/registrations/new.html.erb",
"app/views/devise/sessions/new.html.erb",
"app/views/devise/shared/_links.html.erb",
"app/views/devise/unlocks/new.html.erb",
"lib/devise-i18n.rb",
"lib/devise-i18n/railtie.rb",
"lib/generators/devise/i18n/locale_generator.rb",
"lib/generators/devise/i18n/views_generator.rb",
"lib/generators/devise/templates/simple_form_for/confirmations/new.html.erb",
"lib/generators/devise/templates/simple_form_for/passwords/edit.html.erb",
"lib/generators/devise/templates/simple_form_for/passwords/new.html.erb",
"lib/generators/devise/templates/simple_form_for/registrations/edit.html.erb",
"lib/generators/devise/templates/simple_form_for/registrations/new.html.erb",
"lib/generators/devise/templates/simple_form_for/sessions/new.html.erb",
"lib/generators/devise/templates/simple_form_for/unlocks/new.html.erb",
"rails/locales/af.yml",
"rails/locales/ar.yml",
"rails/locales/az.yml",
"rails/locales/be.yml",
"rails/locales/bg.yml",
"rails/locales/bn.yml",
"rails/locales/bs.yml",
"rails/locales/ca.yml",
"rails/locales/cs.yml",
"rails/locales/da.yml",
"rails/locales/de-CH.yml",
"rails/locales/de.yml",
"rails/locales/el.yml",
"rails/locales/en-GB.yml",
"rails/locales/en.yml",
"rails/locales/es-MX.yml",
"rails/locales/es.yml",
"rails/locales/et.yml",
"rails/locales/fa.yml",
"rails/locales/fi.yml",
"rails/locales/fr-CA.yml",
"rails/locales/fr.yml",
"rails/locales/ha.yml",
"rails/locales/he.yml",
"rails/locales/hr.yml",
"rails/locales/hu.yml",
"rails/locales/id.yml",
"rails/locales/ig.yml",
"rails/locales/is.yml",
"rails/locales/it.yml",
"rails/locales/ja.yml",
"rails/locales/ka.yml",
"rails/locales/ko.yml",
"rails/locales/lo-LA.yml",
"rails/locales/lt.yml",
"rails/locales/lv.yml",
"rails/locales/ms.yml",
"rails/locales/nb.yml",
"rails/locales/nl.yml",
"rails/locales/nn-NO.yml",
"rails/locales/no.yml",
"rails/locales/pap-AW.yml",
"rails/locales/pap-CW.yml",
"rails/locales/pl.yml",
"rails/locales/pt-BR.yml",
"rails/locales/pt.yml",
"rails/locales/ro.yml",
"rails/locales/ru.yml",
"rails/locales/si.yml",
"rails/locales/sk.yml",
"rails/locales/sl.yml",
"rails/locales/sq.yml",
"rails/locales/sr-RS.yml",
"rails/locales/sr.yml",
"rails/locales/sv.yml",
"rails/locales/th.yml",
"rails/locales/tl.yml",
"rails/locales/tr.yml",
"rails/locales/uk.yml",
"rails/locales/ur.yml",
"rails/locales/vi.yml",
"rails/locales/yo.yml",
"rails/locales/zh-CN.yml",
"rails/locales/zh-HK.yml",
"rails/locales/zh-TW.yml",
"rails/locales/zh-YUE.yml"
]
s.homepage = "http://github.com/tigrish/devise-i18n".freeze
s.licenses = ["MIT".freeze]
s.rubygems_version = "2.7.6".freeze
s.summary = "Translations for the devise gem".freeze
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<devise>.freeze, [">= 4.5"])
s.add_development_dependency(%q<rspec>.freeze, [">= 2.8.0"])
s.add_development_dependency(%q<rspec-rails>.freeze, [">= 0"])
s.add_development_dependency(%q<bundler>.freeze, ["~> 1.2"])
s.add_development_dependency(%q<jeweler>.freeze, ["> 1.6.4"])
s.add_development_dependency(%q<i18n-spec>.freeze, ["~> 0.6.0"])
s.add_development_dependency(%q<localeapp>.freeze, [">= 0"])
s.add_development_dependency(%q<railties>.freeze, [">= 0"])
s.add_development_dependency(%q<activemodel>.freeze, [">= 0"])
else
s.add_dependency(%q<devise>.freeze, [">= 4.5"])
s.add_dependency(%q<rspec>.freeze, [">= 2.8.0"])
s.add_dependency(%q<rspec-rails>.freeze, [">= 0"])
s.add_dependency(%q<bundler>.freeze, ["~> 1.2"])
s.add_dependency(%q<jeweler>.freeze, ["> 1.6.4"])
s.add_dependency(%q<i18n-spec>.freeze, ["~> 0.6.0"])
s.add_dependency(%q<localeapp>.freeze, [">= 0"])
s.add_dependency(%q<railties>.freeze, [">= 0"])
s.add_dependency(%q<activemodel>.freeze, [">= 0"])
end
else
s.add_dependency(%q<devise>.freeze, [">= 4.5"])
s.add_dependency(%q<rspec>.freeze, [">= 2.8.0"])
s.add_dependency(%q<rspec-rails>.freeze, [">= 0"])
s.add_dependency(%q<bundler>.freeze, ["~> 1.2"])
s.add_dependency(%q<jeweler>.freeze, ["> 1.6.4"])
s.add_dependency(%q<i18n-spec>.freeze, ["~> 0.6.0"])
s.add_dependency(%q<localeapp>.freeze, [">= 0"])
s.add_dependency(%q<railties>.freeze, [">= 0"])
s.add_dependency(%q<activemodel>.freeze, [">= 0"])
end
end
| 38.423077 | 112 | 0.655322 |
ff39089fad569b3f6f79831da4ebdeeaafdb6f86 | 71,155 | # -*- coding: binary -*-
#
# Rex
#
#
# Project
#
require 'msf/core/opt_condition'
require 'optparse'
module Msf
module Ui
module Console
module CommandDispatcher
###
#
# Command dispatcher for core framework commands, such as module loading,
# session interaction, and other general things.
#
###
class Core
include Msf::Ui::Console::CommandDispatcher
include Msf::Ui::Console::CommandDispatcher::Common
include Msf::Ui::Console::ModuleOptionTabCompletion
# Session command options
@@sessions_opts = Rex::Parser::Arguments.new(
"-c" => [ true, "Run a command on the session given with -i, or all" ],
"-C" => [ true, "Run a Meterpreter Command on the session given with -i, or all" ],
"-h" => [ false, "Help banner" ],
"-i" => [ true, "Interact with the supplied session ID" ],
"-l" => [ false, "List all active sessions" ],
"-v" => [ false, "List all active sessions in verbose mode" ],
"-d" => [ false, "List all inactive sessions" ],
"-q" => [ false, "Quiet mode" ],
"-k" => [ true, "Terminate sessions by session ID and/or range" ],
"-K" => [ false, "Terminate all sessions" ],
"-s" => [ true, "Run a script or module on the session given with -i, or all" ],
"-u" => [ true, "Upgrade a shell to a meterpreter session on many platforms" ],
"-t" => [ true, "Set a response timeout (default: 15)" ],
"-S" => [ true, "Row search filter." ],
"-x" => [ false, "Show extended information in the session table" ],
"-n" => [ true, "Name or rename a session by ID" ])
@@threads_opts = Rex::Parser::Arguments.new(
"-h" => [ false, "Help banner." ],
"-k" => [ true, "Terminate the specified thread ID." ],
"-K" => [ false, "Terminate all non-critical threads." ],
"-i" => [ true, "Lists detailed information about a thread." ],
"-l" => [ false, "List all background threads." ],
"-v" => [ false, "Print more detailed info. Use with -i and -l" ])
@@tip_opts = Rex::Parser::Arguments.new(
"-h" => [ false, "Help banner." ])
@@debug_opts = Rex::Parser::Arguments.new(
"-h" => [ false, "Help banner." ],
"-d" => [ false, "Display the Datastore Information." ],
"-c" => [ false, "Display command history." ],
"-e" => [ false, "Display the most recent Error and Stack Trace." ],
"-l" => [ false, "Display the most recent logs." ],
"-v" => [ false, "Display versions and install info." ])
@@connect_opts = Rex::Parser::Arguments.new(
"-h" => [ false, "Help banner." ],
"-p" => [ true, "List of proxies to use." ],
"-C" => [ false, "Try to use CRLF for EOL sequence." ],
"-c" => [ true, "Specify which Comm to use." ],
"-i" => [ true, "Send the contents of a file." ],
"-P" => [ true, "Specify source port." ],
"-S" => [ true, "Specify source address." ],
"-s" => [ false, "Connect with SSL." ],
"-u" => [ false, "Switch to a UDP socket." ],
"-w" => [ true, "Specify connect timeout." ],
"-z" => [ false, "Just try to connect, then return." ])
@@search_opts = Rex::Parser::Arguments.new(
"-h" => [ false, "Help banner." ],
"-S" => [ true, "Row search filter." ])
@@history_opts = Rex::Parser::Arguments.new(
"-h" => [ false, "Help banner." ],
"-a" => [ false, "Show all commands in history." ],
"-n" => [ true, "Show the last n commands." ],
"-c" => [ false, "Clear command history and history file." ])
# Returns the list of commands supported by this command dispatcher
def commands
{
"?" => "Help menu",
"banner" => "Display an awesome metasploit banner",
"cd" => "Change the current working directory",
"connect" => "Communicate with a host",
"color" => "Toggle color",
"debug" => "Display information useful for debugging",
"exit" => "Exit the console",
"features" => "Display the list of not yet released features that can be opted in to",
"get" => "Gets the value of a context-specific variable",
"getg" => "Gets the value of a global variable",
"grep" => "Grep the output of another command",
"help" => "Help menu",
"history" => "Show command history",
"load" => "Load a framework plugin",
"quit" => "Exit the console",
"repeat" => "Repeat a list of commands",
"route" => "Route traffic through a session",
"save" => "Saves the active datastores",
"sessions" => "Dump session listings and display information about sessions",
"set" => "Sets a context-specific variable to a value",
"setg" => "Sets a global variable to a value",
"sleep" => "Do nothing for the specified number of seconds",
"tips" => "Show a list of useful productivity tips",
"threads" => "View and manipulate background threads",
"unload" => "Unload a framework plugin",
"unset" => "Unsets one or more context-specific variables",
"unsetg" => "Unsets one or more global variables",
"version" => "Show the framework and console library version numbers",
"spool" => "Write console output into a file as well the screen"
}
end
#
# Initializes the datastore cache
#
def initialize(driver)
super
@cache_payloads = nil
@previous_module = nil
@previous_target = nil
@history_limit = 100
end
def deprecated_commands
['tip']
end
#
# Returns the name of the command dispatcher.
#
def name
"Core"
end
def cmd_color_help
print_line "Usage: color <'true'|'false'|'auto'>"
print_line
print_line "Enable or disable color output."
print_line
end
def cmd_color(*args)
case args[0]
when "auto"
driver.output.auto_color
when "true"
driver.output.enable_color
when "false"
driver.output.disable_color
else
cmd_color_help
return
end
end
#
# Tab completion for the color command
#
# @param str [String] the string currently being typed before tab was hit
# @param words [Array<String>] the previously completed words on the command line. words is always
# at least 1 when tab completion has reached this stage since the command itself has been completed
#
def cmd_color_tabs(str, words)
return [] if words.length > 1
%w[auto true false]
end
def cmd_cd_help
print_line "Usage: cd <directory>"
print_line
print_line "Change the current working directory"
print_line
end
#
# Change the current working directory
#
def cmd_cd(*args)
if(args.length == 0)
print_error("No path specified")
return
end
begin
Dir.chdir(args.join(" ").strip)
rescue ::Exception
print_error("The specified path does not exist")
end
end
def cmd_cd_tabs(str, words)
tab_complete_directory(str, words)
end
def cmd_banner_help
print_line "Usage: banner"
print_line
print_line "Print a stunning ascii art banner along with version information and module counts"
print_line
end
#
# Display one of the fabulous banners.
#
def cmd_banner(*args)
banner = "%cya" + Banner.to_s + "%clr\n\n"
stats = framework.stats
version = "%yelmetasploit v#{Metasploit::Framework::VERSION}%clr",
exp_aux_pos = "#{stats.num_exploits} exploits - #{stats.num_auxiliary} auxiliary - #{stats.num_post} post",
pay_enc_nop = "#{stats.num_payloads} payloads - #{stats.num_encoders} encoders - #{stats.num_nops} nops",
eva = "#{stats.num_evasion} evasion",
padding = 48
banner << (" =[ %-#{padding+8}s]\n" % version)
banner << ("+ -- --=[ %-#{padding}s]\n" % exp_aux_pos)
banner << ("+ -- --=[ %-#{padding}s]\n" % pay_enc_nop)
banner << ("+ -- --=[ %-#{padding}s]\n" % eva)
banner << "\n"
banner << Msf::Serializer::ReadableText.word_wrap("Metasploit tip: #{Tip.sample}\n", indent = 0, cols = 60)
# Display the banner
print_line(banner)
end
def cmd_tips_help
print_line "Usage: tips [options]"
print_line
print_line "Print a useful list of productivity tips on how to use Metasploit"
print @@tip_opts.usage
end
alias cmd_tip_help cmd_tips_help
#
# Display useful productivity tips to the user.
#
def cmd_tips(*args)
if args.include?("-h")
cmd_tip_help
else
tbl = Table.new(
Table::Style::Default,
'Columns' => %w[Id Tip]
)
Tip.all.each_with_index do |tip, index|
tbl << [ index, tip ]
end
print(tbl.to_s)
end
end
alias cmd_tip cmd_tips
def cmd_debug_help
print_line "Usage: debug [options]"
print_line
print_line("Print a set of information in a Markdown format to be included when opening an Issue on Github. " +
"This information helps us fix problems you encounter and should be included when you open a new issue: " +
Debug.issue_link)
print @@debug_opts.usage
end
#
# Display information useful for debugging errors.
#
def cmd_debug(*args)
if args.empty?
print_line Debug.all(framework, driver)
return
end
if args.include?("-h")
cmd_debug_help
else
output = ""
@@debug_opts.parse(args) do |opt|
case opt
when '-d'
output << Debug.datastore(framework, driver)
when '-c'
output << Debug.history(driver)
when '-e'
output << Debug.errors
when '-l'
output << Debug.logs
when '-v'
output << Debug.versions(framework)
end
end
if output.empty?
print_line("Valid argument was not given.")
cmd_debug_help
else
output = Debug.preamble + output
print_line output
end
end
end
def cmd_connect_help
print_line "Usage: connect [options] <host> <port>"
print_line
print_line "Communicate with a host, similar to interacting via netcat, taking advantage of"
print_line "any configured session pivoting."
print @@connect_opts.usage
end
#
# Talk to a host
#
def cmd_connect(*args)
if args.length < 2 or args.include?("-h")
cmd_connect_help
return false
end
crlf = false
commval = nil
fileval = nil
proxies = nil
srcaddr = nil
srcport = nil
ssl = false
udp = false
cto = nil
justconn = false
aidx = 0
@@connect_opts.parse(args) do |opt, idx, val|
case opt
when "-C"
crlf = true
aidx = idx + 1
when "-c"
commval = val
aidx = idx + 2
when "-i"
fileval = val
aidx = idx + 2
when "-P"
srcport = val
aidx = idx + 2
when "-p"
proxies = val
aidx = idx + 2
when "-S"
srcaddr = val
aidx = idx + 2
when "-s"
ssl = true
aidx = idx + 1
when "-w"
cto = val.to_i
aidx = idx + 2
when "-u"
udp = true
aidx = idx + 1
when "-z"
justconn = true
aidx = idx + 1
end
end
commval = "Local" if commval =~ /local/i
if fileval
begin
raise "Not a file" if File.ftype(fileval) != "file"
infile = ::File.open(fileval)
rescue
print_error("Can't read from '#{fileval}': #{$!}")
return false
end
end
args = args[aidx .. -1]
if args.length < 2
print_error("You must specify a host and port")
return false
end
host = args[0]
port = args[1]
comm = nil
if commval
begin
if Rex::Socket::Comm.const_defined?(commval)
comm = Rex::Socket::Comm.const_get(commval)
end
rescue NameError
end
if not comm
session = framework.sessions.get(commval)
if session.kind_of?(Msf::Session::Comm)
comm = session
end
end
if not comm
print_error("Invalid comm '#{commval}' selected")
return false
end
end
begin
klass = udp ? ::Rex::Socket::Udp : ::Rex::Socket::Tcp
sock = klass.create({
'Comm' => comm,
'Proxies' => proxies,
'SSL' => ssl,
'PeerHost' => host,
'PeerPort' => port,
'LocalHost' => srcaddr,
'LocalPort' => srcport,
'Timeout' => cto,
'Context' => {
'Msf' => framework
}
})
rescue
print_error("Unable to connect: #{$!}")
return false
end
_, lhost, lport = sock.getlocalname()
print_status("Connected to #{host}:#{port} (via: #{lhost}:#{lport})")
if justconn
sock.close
infile.close if infile
return true
end
cin = infile || driver.input
cout = driver.output
begin
# Console -> Network
c2n = framework.threads.spawn("ConnectConsole2Network", false, cin, sock) do |input, output|
while true
begin
res = input.gets
break if not res
if crlf and (res =~ /^\n$/ or res =~ /[^\r]\n$/)
res.gsub!(/\n$/, "\r\n")
end
output.write res
rescue ::EOFError, ::IOError
break
end
end
end
# Network -> Console
n2c = framework.threads.spawn("ConnectNetwork2Console", false, sock, cout, c2n) do |input, output, cthr|
while true
begin
res = input.read(65535)
break if not res
output.print res
rescue ::EOFError, ::IOError
break
end
end
Thread.kill(cthr)
end
c2n.join
rescue ::Interrupt
c2n.kill
n2c.kill
end
c2n.join
n2c.join
sock.close rescue nil
infile.close if infile
true
end
#
# Instructs the driver to stop executing.
#
def cmd_exit(*args)
forced = false
forced = true if (args[0] and args[0] =~ /-y/i)
if(framework.sessions.length > 0 and not forced)
print_status("You have active sessions open, to exit anyway type \"exit -y\"")
return
elsif(driver.confirm_exit and not forced)
print("Are you sure you want to exit Metasploit? [y/N]: ")
response = gets.downcase.chomp
if(response == "y" || response == "yes")
driver.stop
else
return
end
end
driver.stop
end
alias cmd_quit cmd_exit
def cmd_features_help
print_line <<~CMD_FEATURE_HELP
Enable or disable unreleased features that Metasploit supports
Usage:
features set feature_name [true/false]
features print
Subcommands:
set - Enable or disable a given feature
print - show all available features and their current configuration
Examples:
View available features:
features print
Enable a feature:
features set new_feature true
Disable a feature:
features set new_feature false
CMD_FEATURE_HELP
end
#
# This method handles the features command which allows a user to opt into enabling
# features that are not yet released to everyone by default.
#
def cmd_features(*args)
args << 'print' if args.empty?
action, *rest = args
case action
when 'set'
feature_name, value = rest
unless framework.features.exists?(feature_name)
print_warning("Feature name '#{feature_name}' is not available. Either it has been removed, integrated by default, or does not exist in this version of Metasploit.")
print_warning("Currently supported features: #{framework.features.names.join(', ')}") if framework.features.all.any?
print_warning('There are currently no features to toggle.') if framework.features.all.empty?
return
end
unless %w[true false].include?(value)
print_warning('Please specify true or false to configure this feature.')
return
end
framework.features.set(feature_name, value == 'true')
print_line("#{feature_name} => #{value}")
# Reload the current module, as feature flags may impact the available module options etc
driver.run_single("reload") if driver.active_module
when 'print'
if framework.features.all.empty?
print_line 'There are no features to enable at this time. Either the features have been removed, or integrated by default.'
return
end
features_table = Table.new(
Table::Style::Default,
'Header' => 'Features table',
'Prefix' => "\n",
'Postfix' => "\n",
'Columns' => [
'#',
'Name',
'Enabled',
'Description',
]
)
framework.features.all.each.with_index do |feature, index|
features_table << [
index,
feature[:name],
feature[:enabled].to_s,
feature[:description]
]
end
print_line features_table.to_s
else
cmd_features_help
end
rescue StandardError => e
elog(e)
print_error(e.message)
end
#
# Tab completion for the features command
#
# @param str [String] the string currently being typed before tab was hit
# @param words [Array<String>] the previously completed words on the command line. words is always
# at least 1 when tab completion has reached this stage since the command itself has been completed
def cmd_features_tabs(_str, words)
if words.length == 1
return %w[set print]
end
_command_name, action, *rest = words
ret = []
case action
when 'set'
feature_name, _value = rest
if framework.features.exists?(feature_name)
ret += %w[true false]
else
ret += framework.features.names
end
end
ret
end
def cmd_history(*args)
length = Readline::HISTORY.length
if length < @history_limit
limit = length
else
limit = @history_limit
end
@@history_opts.parse(args) do |opt, idx, val|
case opt
when '-a'
limit = length
when '-n'
return cmd_history_help unless val && val.match(/\A[-+]?\d+\z/)
if length < val.to_i
limit = length
else
limit = val.to_i
end
when '-c'
if Readline::HISTORY.respond_to?(:clear)
Readline::HISTORY.clear
elsif defined?(RbReadline)
RbReadline.clear_history
else
print_error('Could not clear history, skipping file')
return false
end
# Portable file truncation?
if File.writable?(Msf::Config.history_file)
File.write(Msf::Config.history_file, '')
end
print_good('Command history and history file cleared')
return true
when '-h'
cmd_history_help
return false
end
end
start = length - limit
pad_len = length.to_s.length
(start..length-1).each do |pos|
cmd_num = (pos + 1).to_s
print_line "#{cmd_num.ljust(pad_len)} #{Readline::HISTORY[pos]}"
end
end
def cmd_history_help
print_line "Usage: history [options]"
print_line
print_line "Shows the command history."
print_line
print_line "If -n is not set, only the last #{@history_limit} commands will be shown."
print_line 'If -c is specified, the command history and history file will be cleared.'
print_line 'Start commands with a space to avoid saving them to history.'
print @@history_opts.usage
end
def cmd_history_tabs(str, words)
return [] if words.length > 1
@@history_opts.fmt.keys
end
def cmd_sleep_help
print_line "Usage: sleep <seconds>"
print_line
print_line "Do nothing the specified number of seconds. This is useful in rc scripts."
print_line
end
#
# Causes process to pause for the specified number of seconds
#
def cmd_sleep(*args)
return if not (args and args.length == 1)
Rex::ThreadSafe.sleep(args[0].to_f)
end
def cmd_threads_help
print_line "Usage: threads [options]"
print_line
print_line "Background thread management."
print_line @@threads_opts.usage()
end
#
# Displays and manages running background threads
#
def cmd_threads(*args)
# Make the default behavior listing all jobs if there were no options
# or the only option is the verbose flag
if (args.length == 0 or args == ["-v"])
args.unshift("-l")
end
verbose = false
dump_list = false
dump_info = false
thread_id = nil
# Parse the command options
@@threads_opts.parse(args) { |opt, idx, val|
case opt
when "-v"
verbose = true
when "-l"
dump_list = true
# Terminate the supplied thread id
when "-k"
val = val.to_i
if not framework.threads[val]
print_error("No such thread")
else
print_line("Terminating thread: #{val}...")
framework.threads.kill(val)
end
when "-K"
print_line("Killing all non-critical threads...")
framework.threads.each_index do |i|
t = framework.threads[i]
next if not t
next if t[:tm_crit]
framework.threads.kill(i)
end
when "-i"
# Defer printing anything until the end of option parsing
# so we can check for the verbose flag.
dump_info = true
thread_id = val.to_i
when "-h"
cmd_threads_help
return false
end
}
if (dump_list)
tbl = Table.new(
Table::Style::Default,
'Header' => "Background Threads",
'Prefix' => "\n",
'Postfix' => "\n",
'Columns' =>
[
'ID',
'Status',
'Critical',
'Name',
'Started'
]
)
framework.threads.each_index do |i|
t = framework.threads[i]
next if not t
tbl << [ i.to_s, t.status || "dead", t[:tm_crit] ? "True" : "False", t[:tm_name].to_s, t[:tm_time].to_s ]
end
print(tbl.to_s)
end
if (dump_info)
thread = framework.threads[thread_id]
if (thread)
output = "\n"
output += " ID: #{thread_id}\n"
output += "Name: #{thread[:tm_name]}\n"
output += "Info: #{thread.status || "dead"}\n"
output += "Crit: #{thread[:tm_crit] ? "True" : "False"}\n"
output += "Time: #{thread[:tm_time].to_s}\n"
if (verbose)
output += "\n"
output += "Thread Source\n"
output += "=============\n"
thread[:tm_call].each do |c|
output += " #{c.to_s}\n"
end
output += "\n"
end
print(output + "\n")
else
print_line("Invalid Thread ID")
end
end
end
#
# Tab completion for the threads command
#
# @param str [String] the string currently being typed before tab was hit
# @param words [Array<String>] the previously completed words on the command line. words is always
# at least 1 when tab completion has reached this stage since the command itself has been completed
def cmd_threads_tabs(str, words)
if words.length == 1
return @@threads_opts.fmt.keys
end
if words.length == 2 and (@@threads_opts.fmt[words[1]] || [false])[0]
return framework.threads.each_index.map{ |idx| idx.to_s }
end
[]
end
def cmd_load_help
print_line "Usage: load <option> [var=val var=val ...]"
print_line
print_line "Loads a plugin from the supplied path."
print_line "For a list of built-in plugins, do: load -l"
print_line "For a list of loaded plugins, do: load -s"
print_line "The optional var=val options are custom parameters that can be passed to plugins."
print_line
end
def list_plugins
plugin_directories = {
'Framework' => Msf::Config.plugin_directory,
'User' => Msf::Config.user_plugin_directory
}
plugin_directories.each do |type, plugin_directory|
items = Dir.entries(plugin_directory).keep_if { |n| n.match(/^.+\.rb$/)}
next if items.empty?
print_status("Available #{type} plugins:")
items.each do |item|
print_line(" * #{item.split('.').first}")
end
print_line
end
end
def load_plugin(args)
path = args[0]
opts = {
'LocalInput' => driver.input,
'LocalOutput' => driver.output,
'ConsoleDriver' => driver
}
# Parse any extra options that should be passed to the plugin
args.each { |opt|
k, v = opt.split(/\=/)
opts[k] = v if (k and v)
}
# If no absolute path was supplied, check the base and user plugin directories
if (path !~ /#{File::SEPARATOR}/)
plugin_file_name = path
# If the plugin isn't in the user directory (~/.msf3/plugins/), use the base
path = Msf::Config.user_plugin_directory + File::SEPARATOR + plugin_file_name
if not File.exist?( path + ".rb" )
# If the following "path" doesn't exist it will be caught when we attempt to load
path = Msf::Config.plugin_directory + File::SEPARATOR + plugin_file_name
end
end
# Load that plugin!
begin
if (inst = framework.plugins.load(path, opts))
print_status("Successfully loaded plugin: #{inst.name}")
end
rescue ::Exception => e
elog("Error loading plugin #{path}", error: e)
print_error("Failed to load plugin from #{path}: #{e}")
end
end
#
# Loads a plugin from the supplied path. If no absolute path is supplied,
# the framework root plugin directory is used.
#
def cmd_load(*args)
case args[0]
when '-l'
list_plugins
when '-h', nil, ''
cmd_load_help
when '-s'
framework.plugins.each{ |p| print_line p.name }
else
load_plugin(args)
end
end
#
# Tab completion for the load command
#
# @param str [String] the string currently being typed before tab was hit
# @param words [Array<String>] the previously completed words on the command line. words is always
# at least 1 when tab completion has reached this stage since the command itself has been completed
def cmd_load_tabs(str, words)
tabs = []
if (not words[1] or not words[1].match(/^\//))
# then let's start tab completion in the scripts/resource directories
begin
[
Msf::Config.user_plugin_directory,
Msf::Config.plugin_directory
].each do |dir|
next if not ::File.exist? dir
tabs += ::Dir.new(dir).find_all { |e|
path = dir + File::SEPARATOR + e
::File.file?(path) and File.readable?(path)
}
end
rescue Exception
end
else
tabs += tab_complete_filenames(str,words)
end
return tabs.map{|e| e.sub(/\.rb/, '')} - framework.plugins.map(&:name)
end
def cmd_route_help
print_line "Route traffic destined to a given subnet through a supplied session."
print_line
print_line "Usage:"
print_line " route [add/remove] subnet netmask [comm/sid]"
print_line " route [add/remove] cidr [comm/sid]"
print_line " route [get] <host or network>"
print_line " route [flush]"
print_line " route [print]"
print_line
print_line "Subcommands:"
print_line " add - make a new route"
print_line " remove - delete a route; 'del' is an alias"
print_line " flush - remove all routes"
print_line " get - display the route for a given target"
print_line " print - show all active routes"
print_line
print_line "Examples:"
print_line " Add a route for all hosts from 192.168.0.0 to 192.168.0.255 through session 1"
print_line " route add 192.168.0.0 255.255.255.0 1"
print_line " route add 192.168.0.0/24 1"
print_line
print_line " Delete the above route"
print_line " route remove 192.168.0.0/24 1"
print_line " route del 192.168.0.0 255.255.255.0 1"
print_line
print_line " Display the route that would be used for the given host or network"
print_line " route get 192.168.0.11"
print_line
end
#
# This method handles the route command which allows a user to specify
# which session a given subnet should route through.
#
def cmd_route(*args)
begin
args << 'print' if args.length == 0
action = args.shift
case action
when "add", "remove", "del"
subnet = args.shift
subnet, cidr_mask = subnet.split("/")
if Rex::Socket.is_ip_addr?(args.first)
netmask = args.shift
elsif Rex::Socket.is_ip_addr?(subnet)
netmask = Rex::Socket.addr_ctoa(cidr_mask, v6: Rex::Socket.is_ipv6?(subnet))
end
netmask = args.shift if netmask.nil?
gateway_name = args.shift
if (subnet.nil? || netmask.nil? || gateway_name.nil?)
print_error("Missing arguments to route #{action}.")
return false
end
case gateway_name
when /local/i
gateway = Rex::Socket::Comm::Local
when /^(-1|[0-9]+)$/
session = framework.sessions.get(gateway_name)
if session.kind_of?(Msf::Session::Comm)
gateway = session
elsif session.nil?
print_error("Not a session: #{gateway_name}")
return false
else
print_error("Cannot route through the specified session (not a Comm)")
return false
end
else
print_error("Invalid gateway")
return false
end
msg = "Route "
if action == "remove" or action == "del"
worked = Rex::Socket::SwitchBoard.remove_route(subnet, netmask, gateway)
msg << (worked ? "removed" : "not found")
else
worked = Rex::Socket::SwitchBoard.add_route(subnet, netmask, gateway)
msg << (worked ? "added" : "already exists")
end
print_status(msg)
when "get"
if (args.length == 0)
print_error("You must supply an IP address.")
return false
end
comm = Rex::Socket::SwitchBoard.best_comm(args[0])
if ((comm) and
(comm.kind_of?(Msf::Session)))
print_line("#{args[0]} routes through: Session #{comm.sid}")
else
print_line("#{args[0]} routes through: Local")
end
when "flush"
Rex::Socket::SwitchBoard.flush_routes
when "print"
# IPv4 Table
tbl_ipv4 = Table.new(
Table::Style::Default,
'Header' => "IPv4 Active Routing Table",
'Prefix' => "\n",
'Postfix' => "\n",
'Columns' =>
[
'Subnet',
'Netmask',
'Gateway',
],
'ColProps' =>
{
'Subnet' => { 'MaxWidth' => 17 },
'Netmask' => { 'MaxWidth' => 17 },
})
# IPv6 Table
tbl_ipv6 = Table.new(
Table::Style::Default,
'Header' => "IPv6 Active Routing Table",
'Prefix' => "\n",
'Postfix' => "\n",
'Columns' =>
[
'Subnet',
'Netmask',
'Gateway',
],
'ColProps' =>
{
'Subnet' => { 'MaxWidth' => 17 },
'Netmask' => { 'MaxWidth' => 17 },
})
# Populate Route Tables
Rex::Socket::SwitchBoard.each { |route|
if (route.comm.kind_of?(Msf::Session))
gw = "Session #{route.comm.sid}"
else
gw = route.comm.name.split(/::/)[-1]
end
tbl_ipv4 << [ route.subnet, route.netmask, gw ] if Rex::Socket.is_ipv4?(route.netmask)
tbl_ipv6 << [ route.subnet, route.netmask, gw ] if Rex::Socket.is_ipv6?(route.netmask)
}
# Print Route Tables
print(tbl_ipv4.to_s) if tbl_ipv4.rows.length > 0
print(tbl_ipv6.to_s) if tbl_ipv6.rows.length > 0
if (tbl_ipv4.rows.length + tbl_ipv6.rows.length) < 1
print_status("There are currently no routes defined.")
elsif (tbl_ipv4.rows.length < 1) && (tbl_ipv6.rows.length > 0)
print_status("There are currently no IPv4 routes defined.")
elsif (tbl_ipv4.rows.length > 0) && (tbl_ipv6.rows.length < 1)
print_status("There are currently no IPv6 routes defined.")
end
else
cmd_route_help
end
rescue => error
elog(error)
print_error(error.message)
end
end
#
# Tab completion for the route command
#
# @param str [String] the string currently being typed before tab was hit
# @param words [Array<String>] the previously completed words on the command line. words is always
# at least 1 when tab completion has reached this stage since the command itself has been completed
def cmd_route_tabs(str, words)
if words.length == 1
return %w{add remove get flush print}
end
ret = []
case words[1]
when "remove", "del"
Rex::Socket::SwitchBoard.each { |route|
case words.length
when 2
ret << route.subnet
when 3
if route.subnet == words[2]
ret << route.netmask
end
when 4
if route.subnet == words[2]
ret << route.comm.sid.to_s if route.comm.kind_of? Msf::Session
end
end
}
ret
when "add"
# We can't really complete the subnet and netmask args without
# diving pretty deep into all sessions, so just be content with
# completing sids for the last arg
if words.length == 4
ret = framework.sessions.keys.map { |k| k.to_s }
end
# The "get" command takes one arg, but we can't complete it either...
end
ret
end
def cmd_save_help
print_line "Usage: save"
print_line
print_line "Save the active datastore contents to disk for automatic use across restarts of the console"
print_line
print_line "The configuration is stored in #{Msf::Config.config_file}"
print_line
end
#
# Saves the active datastore contents to disk for automatic use across
# restarts of the console.
#
def cmd_save(*args)
# Save the console config
driver.save_config
begin
FeatureManager.instance.save_config
rescue StandardException => e
elog(e)
end
# Save the framework's datastore
begin
framework.save_config
if (active_module)
active_module.save_config
end
rescue
log_error("Save failed: #{$!}")
return false
end
print_line("Saved configuration to: #{Msf::Config.config_file}")
end
def cmd_spool_help
print_line "Usage: spool <off>|<filename>"
print_line
print_line "Example:"
print_line " spool /tmp/console.log"
print_line
end
def cmd_spool_tabs(str, words)
tab_complete_filenames(str, words)
end
def cmd_spool(*args)
if args.include?('-h') or args.empty?
cmd_spool_help
return
end
color = driver.output.config[:color]
if args[0] == "off"
driver.init_ui(driver.input, Rex::Ui::Text::Output::Stdio.new)
msg = "Spooling is now disabled"
else
driver.init_ui(driver.input, Rex::Ui::Text::Output::Tee.new(args[0]))
msg = "Spooling to file #{args[0]}..."
end
# Restore color
driver.output.config[:color] = color
print_status(msg)
end
def cmd_sessions_help
print_line('Usage: sessions [options] or sessions [id]')
print_line
print_line('Active session manipulation and interaction.')
print(@@sessions_opts.usage)
print_line
print_line('Many options allow specifying session ranges using commas and dashes.')
print_line('For example: sessions -s checkvm -i 1,3-5 or sessions -k 1-2,5,6')
print_line
end
#
# Provides an interface to the sessions currently active in the framework.
#
def cmd_sessions(*args)
begin
method = nil
quiet = false
show_active = false
show_inactive = false
show_extended = false
verbose = false
sid = nil
cmds = []
script = nil
response_timeout = 15
search_term = nil
session_name = nil
# any arguments that don't correspond to an option or option arg will
# be put in here
extra = []
if args.length == 1 && args[0] =~ /-?\d+/
method = 'interact'
sid = args[0].to_i
else
# Parse the command options
@@sessions_opts.parse(args) do |opt, idx, val|
case opt
when "-q"
quiet = true
# Run a command on all sessions, or the session given with -i
when "-c"
method = 'cmd'
cmds << val if val
when "-C"
method = 'meterp-cmd'
cmds << val if val
# Display the list of inactive sessions
when "-d"
show_inactive = true
method = 'list_inactive'
when "-x"
show_extended = true
when "-v"
verbose = true
# Do something with the supplied session identifier instead of
# all sessions.
when "-i"
sid = val
# Display the list of active sessions
when "-l"
show_active = true
method = 'list'
when "-k"
method = 'kill'
sid = val || false
when "-K"
method = 'killall'
# Run a script or module on specified sessions
when "-s"
unless script
method = 'script'
script = val
end
# Upload and exec to the specific command session
when "-u"
method = 'upexec'
sid = val || false
# Search for specific session
when "-S", "--search"
search_term = val
# Display help banner
when "-h"
cmd_sessions_help
return false
when "-t"
if val.to_s =~ /^\d+$/
response_timeout = val.to_i
end
when "-n", "--name"
method = 'name'
session_name = val
else
extra << val
end
end
end
if !method && sid
method = 'interact'
end
unless sid.nil? || method == 'interact'
session_list = build_range_array(sid)
if session_list.blank?
print_error("Please specify valid session identifier(s)")
return false
end
end
if show_inactive && !framework.db.active
print_warning("Database not connected; list of inactive sessions unavailable")
end
last_known_timeout = nil
# Now, perform the actual method
case method
when 'cmd'
if cmds.length < 1
print_error("No command specified!")
return false
end
cmds.each do |cmd|
if sid
sessions = session_list
else
sessions = framework.sessions.keys.sort
end
if sessions.blank?
print_error("Please specify valid session identifier(s) using -i")
return false
end
sessions.each do |s|
session = verify_session(s)
next unless session
print_status("Running '#{cmd}' on #{session.type} session #{s} (#{session.session_host})")
if session.respond_to?(:response_timeout)
last_known_timeout = session.response_timeout
session.response_timeout = response_timeout
end
begin
if session.type == 'meterpreter'
# If session.sys is nil, dont even try..
unless session.sys
print_error("Session #{s} does not have stdapi loaded, skipping...")
next
end
c, c_args = cmd.split(' ', 2)
begin
process = session.sys.process.execute(c, c_args,
{
'Channelized' => true,
'Subshell' => true,
'Hidden' => true
})
if process && process.channel
data = process.channel.read
print_line(data) if data
end
rescue ::Rex::Post::Meterpreter::RequestError
print_error("Failed: #{$!.class} #{$!}")
rescue Rex::TimeoutError
print_error("Operation timed out")
end
elsif session.type == 'shell' || session.type == 'powershell'
output = session.shell_command(cmd)
print_line(output) if output
end
ensure
# Restore timeout for each session
if session.respond_to?(:response_timeout) && last_known_timeout
session.response_timeout = last_known_timeout
end
end
# If the session isn't a meterpreter or shell type, it
# could be a VNC session (which can't run commands) or
# something custom (which we don't know how to run
# commands on), so don't bother.
end
end
when 'meterp-cmd'
if cmds.length < 1
print_error("No command specified!")
return false
end
if sid
sessions = session_list
else
sessions = framework.sessions.keys.sort
end
if sessions.blank?
print_error("Please specify valid session identifier(s) using -i")
return false
end
cmds.each do |cmd|
sessions.each do |session|
session = verify_session(session)
unless session.type == 'meterpreter'
print_error "Session ##{session.sid} is not a Meterpreter shell. Skipping..."
next
end
next unless session
print_status("Running '#{cmd}' on #{session.type} session #{session.sid} (#{session.session_host})")
if session.respond_to?(:response_timeout)
last_known_timeout = session.response_timeout
session.response_timeout = response_timeout
end
output = session.run_cmd(cmd, driver.output)
end
end
when 'kill'
print_status("Killing the following session(s): #{session_list.join(', ')}")
session_list.each do |sess_id|
session = framework.sessions.get(sess_id)
if session
if session.respond_to?(:response_timeout)
last_known_timeout = session.response_timeout
session.response_timeout = response_timeout
end
print_status("Killing session #{sess_id}")
begin
session.kill
ensure
if session.respond_to?(:response_timeout) && last_known_timeout
session.response_timeout = last_known_timeout
end
end
else
print_error("Invalid session identifier: #{sess_id}")
end
end
when 'killall'
print_status("Killing all sessions...")
framework.sessions.each_sorted do |s|
session = framework.sessions.get(s)
if session
if session.respond_to?(:response_timeout)
last_known_timeout = session.response_timeout
session.response_timeout = response_timeout
end
begin
session.kill
ensure
if session.respond_to?(:response_timeout) && last_known_timeout
session.response_timeout = last_known_timeout
end
end
end
end
when 'interact'
while sid
session = verify_session(sid)
if session
if session.respond_to?(:response_timeout)
last_known_timeout = session.response_timeout
session.response_timeout = response_timeout
end
print_status("Starting interaction with #{session.name}...\n") unless quiet
begin
self.active_session = session
sid = session.interact(driver.input.dup, driver.output)
self.active_session = nil
driver.input.reset_tab_completion if driver.input.supports_readline
ensure
if session.respond_to?(:response_timeout) && last_known_timeout
session.response_timeout = last_known_timeout
end
end
else
sid = nil
end
end
when 'script'
unless script
print_error("No script or module specified!")
return false
end
sessions = sid ? session_list : framework.sessions.keys.sort
sessions.each do |sess_id|
session = verify_session(sess_id, true)
# @TODO: Not interactive sessions can or cannot have scripts run on them?
if session == false # specifically looking for false
# if verify_session returned false, sess_id is valid, but not interactive
session = framework.sessions.get(sess_id)
end
if session
if session.respond_to?(:response_timeout)
last_known_timeout = session.response_timeout
session.response_timeout = response_timeout
end
begin
print_status("Session #{sess_id} (#{session.session_host}):")
print_status("Running #{script} on #{session.type} session" +
" #{sess_id} (#{session.session_host})")
begin
session.execute_script(script, *extra)
rescue ::Exception => e
log_error("Error executing script or module: #{e.class} #{e}")
end
ensure
if session.respond_to?(:response_timeout) && last_known_timeout
session.response_timeout = last_known_timeout
end
end
else
print_error("Invalid session identifier: #{sess_id}")
end
end
when 'upexec'
print_status("Executing 'post/multi/manage/shell_to_meterpreter' on " +
"session(s): #{session_list}")
session_list.each do |sess_id|
session = verify_session(sess_id)
if session
if session.respond_to?(:response_timeout)
last_known_timeout = session.response_timeout
session.response_timeout = response_timeout
end
begin
session.init_ui(driver.input, driver.output)
session.execute_script('post/multi/manage/shell_to_meterpreter')
session.reset_ui
ensure
if session.respond_to?(:response_timeout) && last_known_timeout
session.response_timeout = last_known_timeout
end
end
end
if session_list.count > 1
print_status("Sleeping 5 seconds to allow the previous handler to finish..")
sleep(5)
end
end
when 'list', 'list_inactive', nil
print_line
print(Serializer::ReadableText.dump_sessions(framework, show_active: show_active, show_inactive: show_inactive, show_extended: show_extended, verbose: verbose, search_term: search_term))
print_line
when 'name'
if session_name.blank?
print_error('Please specify a valid session name')
return false
end
sessions = sid ? session_list : nil
if sessions.nil? || sessions.empty?
print_error("Please specify valid session identifier(s) using -i")
return false
end
sessions.each do |s|
if framework.sessions[s].respond_to?(:name=)
framework.sessions[s].name = session_name
print_status("Session #{s} named to #{session_name}")
else
print_error("Session #{s} cannot be named")
end
end
end
rescue IOError, EOFError, Rex::StreamClosedError
print_status("Session stream closed.")
rescue ::Interrupt
raise $!
rescue ::Exception
log_error("Session manipulation failed: #{$!} #{$!.backtrace.inspect}")
end
# Reset the active session
self.active_session = nil
true
end
#
# Tab completion for the sessions command
#
# @param str [String] the string currently being typed before tab was hit
# @param words [Array<String>] the previously completed words on the command line. words is always
# at least 1 when tab completion has reached this stage since the command itself has been completed
def cmd_sessions_tabs(str, words)
if words.length == 1
return @@sessions_opts.fmt.keys
end
case words[-1]
when "-i", "-k", "-u"
return framework.sessions.keys.map { |k| k.to_s }
when "-c"
# Can't really complete commands hehe
when "-s"
# XXX: Complete scripts
end
[]
end
def cmd_set_help
print_line "Usage: set [option] [value]"
print_line
print_line "Set the given option to value. If value is omitted, print the current value."
print_line "If both are omitted, print options that are currently set."
print_line
print_line "If run from a module context, this will set the value in the module's"
print_line "datastore. Use -g to operate on the global datastore."
print_line
print_line "If setting a PAYLOAD, this command can take an index from `show payloads'."
print_line
end
#
# Sets a name to a value in a context aware environment.
#
def cmd_set(*args)
# Figure out if these are global variables
global = false
if (args[0] == '-g')
args.shift
global = true
end
# Decide if this is an append operation
append = false
if (args[0] == '-a')
args.shift
append = true
end
# Determine which data store we're operating on
if (active_module and global == false)
datastore = active_module.datastore
else
global = true
datastore = self.framework.datastore
end
# Dump the contents of the active datastore if no args were supplied
if (args.length == 0)
# If we aren't dumping the global data store, then go ahead and
# dump it first
if (!global)
print("\n" +
Msf::Serializer::ReadableText.dump_datastore(
"Global", framework.datastore))
end
# Dump the active datastore
print("\n" +
Msf::Serializer::ReadableText.dump_datastore(
(global) ? "Global" : "Module: #{active_module.refname}",
datastore) + "\n")
return true
elsif (args.length == 1)
if (not datastore[args[0]].nil?)
print_line("#{args[0]} => #{datastore[args[0]]}")
return true
else
print_error("Unknown variable")
cmd_set_help
return false
end
end
# Set the supplied name to the supplied value
name = args[0]
value = args[1, args.length-1].join(' ')
# Set PAYLOAD
if name.upcase == 'PAYLOAD' && active_module && (active_module.exploit? || active_module.evasion?)
value = trim_path(value, 'payload')
index_from_list(payload_show_results, value) do |mod|
return false unless mod && mod.respond_to?(:first)
# [name, class] from payload_show_results
value = mod.first
end
end
# If the driver indicates that the value is not valid, bust out.
if (driver.on_variable_set(global, name, value) == false)
print_error("The value specified for #{name} is not valid.")
return false
end
# Save the old value before changing it, in case we need to compare it
old_value = datastore[name]
begin
if append
datastore[name] = datastore[name] + value
else
datastore[name] = value
end
rescue Msf::OptionValidateError => e
print_error(e.message)
elog('Exception encountered in cmd_set', error: e)
end
# Set PAYLOAD from TARGET
if name.upcase == 'TARGET' && active_module && (active_module.exploit? || active_module.evasion?)
active_module.import_target_defaults
end
# If the new SSL value already set in datastore[name] is different from the old value, warn the user
if name.casecmp('SSL') == 0 && datastore[name] != old_value
print_warning("Changing the SSL option's value may require changing RPORT!")
end
print_line("#{name} => #{datastore[name]}")
end
def payload_show_results
Msf::Ui::Console::CommandDispatcher::Modules.class_variable_get(:@@payload_show_results)
end
#
# Tab completion for the set command
#
# @param str [String] the string currently being typed before tab was hit
# @param words [Array<String>] the previously completed words on the command line. words is always
# at least 1 when tab completion has reached this stage since the command itself has been completed
def cmd_set_tabs(str, words)
# A value has already been specified
return [] if words.length > 2
# A value needs to be specified
if words.length == 2
return tab_complete_option_values(active_module, str, words, opt: words[1])
end
tab_complete_option_names(active_module, str, words)
end
def cmd_setg_help
print_line "Usage: setg [option] [value]"
print_line
print_line "Exactly like set -g, set a value in the global datastore."
print_line
end
#
# Tab completion for the unset command
#
# @param str [String] the string currently being typed before tab was hit
# @param words [Array<String>] the previously completed words on the command
# line. `words` is always at least 1 when tab completion has reached this
# stage since the command itself has been completed.
def cmd_unset_tabs(str, words)
tab_complete_datastore_names(active_module, str, words)
end
#
# Sets the supplied variables in the global datastore.
#
def cmd_setg(*args)
args.unshift('-g')
cmd_set(*args)
end
#
# Tab completion for the setg command
#
# @param str [String] the string currently being typed before tab was hit
# @param words [Array<String>] the previously completed words on the command line. words is always
# at least 1 when tab completion has reached this stage since the command itself has been completed
def cmd_setg_tabs(str, words)
cmd_set_tabs(str, words)
end
def cmd_unload_help
print_line "Usage: unload <plugin name>"
print_line
print_line "Unloads a plugin by its symbolic name. Use 'show plugins' to see a list of"
print_line "currently loaded plugins."
print_line
end
#
# Unloads a plugin by its name.
#
def cmd_unload(*args)
if (args.length == 0)
cmd_unload_help
return false
end
# Find a plugin within the plugins array
plugin = framework.plugins.find { |p| p.name.downcase == args[0].downcase }
# Unload the plugin if it matches the name we're searching for
if plugin
print("Unloading plugin #{args[0]}...")
framework.plugins.unload(plugin)
print_line("unloaded.")
end
end
#
# Tab completion for the unload command
#
# @param str [String] the string currently being typed before tab was hit
# @param words [Array<String>] the previously completed words on the command line. words is always
# at least 1 when tab completion has reached this stage since the command itself has been completed
def cmd_unload_tabs(str, words)
return [] if words.length > 1
tabs = []
framework.plugins.each { |k| tabs.push(k.name) }
return tabs
end
def cmd_get_help
print_line "Usage: get var1 [var2 ...]"
print_line
print_line "The get command is used to get the value of one or more variables."
print_line
end
#
# Gets a value if it's been set.
#
def cmd_get(*args)
# Figure out if these are global variables
global = false
if (args[0] == '-g')
args.shift
global = true
end
# No arguments? No cookie.
if args.empty?
global ? cmd_getg_help : cmd_get_help
return false
end
# Determine which data store we're operating on
if (active_module && !global)
datastore = active_module.datastore
else
datastore = framework.datastore
end
args.each { |var| print_line("#{var} => #{datastore[var]}") }
end
#
# Tab completion for the get command
#
# @param str [String] the string currently being typed before tab was hit
# @param words [Array<String>] the previously completed words on the command line. words is always
# at least 1 when tab completion has reached this stage since the command itself has been completed
def cmd_get_tabs(str, words)
datastore = active_module ? active_module.datastore : self.framework.datastore
datastore.keys
end
def cmd_getg_help
print_line "Usage: getg var1 [var2 ...]"
print_line
print_line "Exactly like get -g, get global variables"
print_line
end
#
# Gets variables in the global data store.
#
def cmd_getg(*args)
args.unshift('-g')
cmd_get(*args)
end
#
# Tab completion for the getg command
#
# @param str [String] the string currently being typed before tab was hit
# @param words [Array<String>] the previously completed words on the command line. words is always
# at least 1 when tab completion has reached this stage since the command itself has been completed
def cmd_getg_tabs(str, words)
self.framework.datastore.keys
end
def cmd_unset_help
print_line "Usage: unset [-g] var1 var2 var3 ..."
print_line
print_line "The unset command is used to unset one or more variables."
print_line "To flush all entires, specify 'all' as the variable name."
print_line "With -g, operates on global datastore variables."
print_line
end
#
# Unsets a value if it's been set.
#
def cmd_unset(*args)
# Figure out if these are global variables
global = false
if (args[0] == '-g')
args.shift
global = true
end
# Determine which data store we're operating on
if (active_module and global == false)
datastore = active_module.datastore
else
datastore = framework.datastore
end
# No arguments? No cookie.
if (args.length == 0)
cmd_unset_help
return false
end
# If all was specified, then flush all of the entries
if args[0] == 'all'
print_line("Flushing datastore...")
# Re-import default options into the module's datastore
if (active_module and global == false)
active_module.import_defaults
# Or simply clear the global datastore
else
datastore.clear
end
return true
end
while ((val = args.shift))
if (driver.on_variable_unset(global, val) == false)
print_error("The variable #{val} cannot be unset at this time.")
next
end
print_line("Unsetting #{val}...")
datastore.delete(val)
end
end
def cmd_unsetg_help
print_line "Usage: unsetg var1 [var2 ...]"
print_line
print_line "Exactly like unset -g, unset global variables, or all"
print_line
end
#
# Unsets variables in the global data store.
#
def cmd_unsetg(*args)
args.unshift('-g')
cmd_unset(*args)
end
#
# Tab completion for the unsetg command
#
# @param str [String] the string currently being typed before tab was hit
# @param words [Array<String>] the previously completed words on the command line. words is always
# at least 1 when tab completion has reached this stage since the command itself has been completed
def cmd_unsetg_tabs(str, words)
self.framework.datastore.keys
end
alias cmd_unsetg_help cmd_unset_help
#
# Returns the revision of the framework and console library
#
def cmd_version(*args)
print_line("Framework: #{Msf::Framework::Version}")
print_line("Console : #{Msf::Framework::Version}")
end
def cmd_grep_help
cmd_grep '-h'
end
#
# Greps the output of another console command, usage is similar the shell grep command
# grep [options] pattern other_cmd [other command's args], similar to the shell's grep [options] pattern file
# however it also includes -k to keep lines and -s to skip lines. grep -k 5 is useful for keeping table headers
#
# @param args [Array<String>] Args to the grep command minimally including a pattern & a command to search
# @return [String,nil] Results matching the regular expression given
def cmd_grep(*args)
match_mods = {:insensitive => false}
output_mods = {:count => false, :invert => false}
opts = OptionParser.new do |opts|
opts.banner = "Usage: grep [OPTIONS] [--] PATTERN CMD..."
opts.separator "Grep the results of a console command (similar to Linux grep command)"
opts.separator ""
opts.on '-m num', '--max-count num', 'Stop after num matches.', Integer do |max|
match_mods[:max] = max
end
opts.on '-A num', '--after-context num', 'Show num lines of output after a match.', Integer do |num|
output_mods[:after] = num
end
opts.on '-B num', '--before-context num', 'Show num lines of output before a match.', Integer do |num|
output_mods[:before] = num
end
opts.on '-C num', '--context num', 'Show num lines of output around a match.', Integer do |num|
output_mods[:before] = output_mods[:after] = num
end
opts.on '-v', '--[no-]invert-match', 'Invert match.' do |invert|
match_mods[:invert] = invert
end
opts.on '-i', '--[no-]ignore-case', 'Ignore case.' do |insensitive|
match_mods[:insensitive] = insensitive
end
opts.on '-c', '--count', 'Only print a count of matching lines.' do |count|
output_mods[:count] = count
end
opts.on '-k num', '--keep-header num', 'Keep (include) num lines at start of output', Integer do |num|
output_mods[:keep] = num
end
opts.on '-s num', '--skip-header num', 'Skip num lines of output before attempting match.', Integer do |num|
output_mods[:skip] = num
end
opts.on '-h', '--help', 'Help banner.' do
return print(remove_lines(opts.help, '--generate-completions'))
end
# Internal use
opts.on '--generate-completions str', 'Return possible tab completions for given string.' do |str|
return opts.candidate str
end
end
# OptionParser#order allows us to take the rest of the line for the command
pattern, *rest = opts.order(args)
cmd = Shellwords.shelljoin(rest)
return print(opts.help) if !pattern || cmd.empty?
rx = Regexp.new(pattern, match_mods[:insensitive])
# redirect output after saving the old one and getting a new output buffer to use for redirect
orig_output = driver.output
# we use a rex buffer but add a write method to the instance, which is
# required in order to be valid $stdout
temp_output = Rex::Ui::Text::Output::Buffer.new
temp_output.extend Rex::Ui::Text::Output::Buffer::Stdout
driver.init_ui(driver.input, temp_output)
# run the desired command to be grepped
driver.run_single(cmd)
# restore original output
driver.init_ui(driver.input, orig_output)
# dump the command's output so we can grep it
cmd_output = temp_output.dump_buffer
# Bail if the command failed
if cmd_output =~ /Unknown command:/
print_error("Unknown command: '#{rest[0]}'.")
return false
end
# put lines into an array so we can access them more easily and split('\n') doesn't work on the output obj.
all_lines = cmd_output.lines.select {|line| line}
# control matching based on remaining match_mods (:insensitive was already handled)
if match_mods[:invert]
statement = 'not line =~ rx'
else
statement = 'line =~ rx'
end
our_lines = []
count = 0
all_lines.each_with_index do |line, line_num|
next if (output_mods[:skip] and line_num < output_mods[:skip])
our_lines << line if (output_mods[:keep] and line_num < output_mods[:keep])
# we don't wan't to keep processing if we have a :max and we've reached it already (not counting skips/keeps)
break if match_mods[:max] and count >= match_mods[:max]
if eval statement
count += 1
# we might get a -A/after and a -B/before at the same time
our_lines += retrieve_grep_lines(all_lines,line_num,output_mods[:before], output_mods[:after])
end
end
# now control output based on remaining output_mods such as :count
return print_status(count.to_s) if output_mods[:count]
our_lines.each {|line| print line}
end
#
# Tab completion for the grep command
#
# @param str [String] the string currently being typed before tab was hit
# @param words [Array<String>] the previously completed words on the command line. words is always
# at least 1 when tab completion has reached this stage since the command itself has been completed
def cmd_grep_tabs(str, words)
str = '-' if str.empty? # default to use grep's options
tabs = cmd_grep '--generate-completions', str
# if not an opt, use normal tab comp.
# @todo uncomment out next line when tab_completion normalization is complete RM7649 or
# replace with new code that permits "nested" tab completion
# tabs = driver.get_all_commands if (str and str =~ /\w/)
tabs
end
def cmd_repeat_help
cmd_repeat '-h'
end
#
# Repeats (loops) a given list of commands
#
def cmd_repeat(*args)
looper = method :loop
opts = OptionParser.new do |opts|
opts.banner = 'Usage: repeat [OPTIONS] COMMAND...'
opts.separator 'Repeat (loop) a ;-separated list of msfconsole commands indefinitely, or for a'
opts.separator 'number of iterations or a certain amount of time.'
opts.separator ''
opts.on '-t SECONDS', '--time SECONDS', 'Number of seconds to repeat COMMAND...', Integer do |n|
looper = ->(&block) do
# While CLOCK_MONOTONIC is a Linux thing, Ruby emulates it for *BSD, MacOS, and Windows
ending_time = Process.clock_gettime(Process::CLOCK_MONOTONIC, :second) + n
while Process.clock_gettime(Process::CLOCK_MONOTONIC, :second) < ending_time
block.call
end
end
end
opts.on '-n TIMES', '--number TIMES', 'Number of times to repeat COMMAND..', Integer do |n|
looper = n.method(:times)
end
opts.on '-h', '--help', 'Help banner.' do
return print(remove_lines(opts.help, '--generate-completions'))
end
# Internal use
opts.on '--generate-completions str', 'Return possible tab completions for given string.' do |str|
return opts.candidate str
end
end
cmds = opts.order(args).slice_when do |prev, _|
# If the last character of a shellword was a ';' it's probably to
# delineate commands and we can remove it
prev[-1] == ';' && prev[-1] = ''
end.map do |c|
Shellwords.shelljoin(c)
end
# Print help if we have no commands, or all the commands are empty
return cmd_repeat '-h' if cmds.all? &:empty?
begin
looper.call do
cmds.each do |c|
driver.run_single c, propagate_errors: true
end
end
rescue ::Exception
# Stop looping on exception
nil
end
end
# Almost the exact same as grep
def cmd_repeat_tabs(str, words)
str = '-' if str.empty? # default to use repeat's options
tabs = cmd_repeat '--generate-completions', str
# if not an opt, use normal tab comp.
# @todo uncomment out next line when tab_completion normalization is complete RM7649 or
# replace with new code that permits "nested" tab completion
# tabs = driver.get_all_commands if (str and str =~ /\w/)
tabs
end
protected
#
# verifies that a given session_id is valid and that the session is interactive.
# The various return values allow the caller to make better decisions on what
# action can & should be taken depending on the capabilities of the session
# and the caller's objective while making it simple to use in the nominal case
# where the caller needs session_id to match an interactive session
#
# @param session_id [String] A session id, which is an integer as a string
# @param quiet [Boolean] True means the method will produce no error messages
# @return [session] if the given session_id is valid and session is interactive
# @return [false] if the given session_id is valid, but not interactive
# @return [nil] if the given session_id is not valid at all
def verify_session(session_id, quiet = false)
session = framework.sessions.get(session_id)
if session
if session.interactive?
session
else
print_error("Session #{session_id} is non-interactive.") unless quiet
false
end
else
print_error("Invalid session identifier: #{session_id}") unless quiet
nil
end
end
#
# Returns an array of lines at the provided line number plus any before and/or after lines requested
# from all_lines by supplying the +before+ and/or +after+ parameters which are always positive
#
# @param all_lines [Array<String>] An array of all lines being considered for matching
# @param line_num [Integer] The line number in all_lines which has satisifed the match
# @param after [Integer] The number of lines after the match line to include (should always be positive)
# @param before [Integer] The number of lines before the match line to include (should always be positive)
# @return [Array<String>] Array of lines including the line at line_num and any +before+ and/or +after+
def retrieve_grep_lines(all_lines,line_num, before = nil, after = nil)
after = after.to_i.abs
before = before.to_i.abs
start = line_num - before
start = 0 if start < 0
finish = line_num + after
all_lines.slice(start..finish)
end
end
end end end end
| 30.356229 | 192 | 0.598862 |
28261815845a4b6b7e8a14138db5d41387f04fcf | 44 | class Legacyteacher < ApplicationRecord
end
| 14.666667 | 39 | 0.863636 |
7916db960a2037aca3547f324028fb16ae3247e4 | 4,079 | # frozen_string_literal: true
RSpec.describe "bundle add" do
before :each do
build_repo2 do
build_gem "foo", "1.1"
build_gem "foo", "2.0"
build_gem "baz", "1.2.3"
build_gem "bar", "0.12.3"
build_gem "cat", "0.12.3.pre"
build_gem "dog", "1.1.3.pre"
end
install_gemfile <<-G
source "file://#{gem_repo2}"
gem "weakling", "~> 0.0.1"
G
end
describe "without version specified" do
it "version requirement becomes ~> major.minor.patch when resolved version is < 1.0" do
bundle "add 'bar'"
expect(bundled_app("Gemfile").read).to match(/gem "bar", "~> 0.12.3"/)
expect(the_bundle).to include_gems "bar 0.12.3"
end
it "version requirement becomes ~> major.minor when resolved version is > 1.0" do
bundle "add 'baz'"
expect(bundled_app("Gemfile").read).to match(/gem "baz", "~> 1.2"/)
expect(the_bundle).to include_gems "baz 1.2.3"
end
it "version requirement becomes ~> major.minor.patch.pre when resolved version is < 1.0" do
bundle "add 'cat'"
expect(bundled_app("Gemfile").read).to match(/gem "cat", "~> 0.12.3.pre"/)
expect(the_bundle).to include_gems "cat 0.12.3.pre"
end
it "version requirement becomes ~> major.minor.pre when resolved version is > 1.0.pre" do
bundle "add 'dog'"
expect(bundled_app("Gemfile").read).to match(/gem "dog", "~> 1.1.pre"/)
expect(the_bundle).to include_gems "dog 1.1.3.pre"
end
end
describe "with --version" do
it "adds dependency of specified version and runs install" do
bundle "add 'foo' --version='~> 1.0'"
expect(bundled_app("Gemfile").read).to match(/gem "foo", "~> 1.0"/)
expect(the_bundle).to include_gems "foo 1.1"
end
it "adds multiple version constraints when specified" do
bundle "add 'foo' --version='< 3.0, > 1.1'"
expect(bundled_app("Gemfile").read).to match(/gem "foo", "< 3.0", "> 1.1"/)
expect(the_bundle).to include_gems "foo 2.0"
end
end
describe "with --group" do
it "adds dependency for the specified group" do
bundle "add 'foo' --group='development'"
expect(bundled_app("Gemfile").read).to match(/gem "foo", "~> 2.0", :group => \[:development\]/)
expect(the_bundle).to include_gems "foo 2.0"
end
it "adds dependency to more than one group" do
bundle "add 'foo' --group='development, test'"
expect(bundled_app("Gemfile").read).to match(/gem "foo", "~> 2.0", :groups => \[:development, :test\]/)
expect(the_bundle).to include_gems "foo 2.0"
end
end
describe "with --source" do
it "adds dependency with specified source" do
bundle "add 'foo' --source='file://#{gem_repo2}'"
expect(bundled_app("Gemfile").read).to match(%r{gem "foo", "~> 2.0", :source => "file:\/\/#{gem_repo2}"})
expect(the_bundle).to include_gems "foo 2.0"
end
end
it "using combination of short form options works like long form" do
bundle "add 'foo' -s='file://#{gem_repo2}' -g='development' -v='~>1.0'"
expect(bundled_app("Gemfile").read).to include %(gem "foo", "~> 1.0", :group => [:development], :source => "file://#{gem_repo2}")
expect(the_bundle).to include_gems "foo 1.1"
end
it "shows error message when version is not formatted correctly" do
bundle "add 'foo' -v='~>1 . 0'"
expect(out).to match("Invalid gem requirement pattern '~>1 . 0'")
end
it "shows error message when gem cannot be found" do
bundle "add 'werk_it'"
expect(out).to match("Could not find gem 'werk_it' in")
bundle "add 'werk_it' -s='file://#{gem_repo2}'"
expect(out).to match("Could not find gem 'werk_it' in rubygems repository")
end
it "shows error message when source cannot be reached" do
bundle "add 'baz' --source='http://badhostasdf'"
expect(out).to include("Could not reach host badhostasdf. Check your network connection and try again.")
bundle "add 'baz' --source='file://does/not/exist'"
expect(out).to include("Could not fetch specs from file://does/not/exist/")
end
end
| 37.422018 | 133 | 0.632018 |
26805b2bb8b4967fb3d63bbea009fb53677f9339 | 364 | # Custom Type: Razor - Tag
Puppet::Type.newtype(:razor_tag) do
@doc = "Razor Tag"
ensurable
newparam(:name, :namevar => true) do
desc "The tag name"
end
newproperty(:rule, :array_matching => :all) do
desc "The tag rule (Array)"
end
# This is not support by Puppet (<= 3.7)...
# autorequire(:class) do
# 'razor'
# end
end | 18.2 | 48 | 0.601648 |
bf0069f57659109e0d111b49c22878050c27eb66 | 978 | require 'yaml'
module JCov::Commands
# the check command
class Check
def initialize(args, options)
config = JCov::Configuration.new(options)
if config.filename
puts "Using configuration file: #{config.filename}"
else
puts "No configuration file! Using defaults."
end
puts config
end
end
# the run command
class Run
def initialize(args, options)
# default to no color unless we're on a tty
options.default :color => $stdout.tty?
options.default :coverage => true
options.args = args
config = JCov::Configuration.new(options)
runner = JCov::Runner.new(config)
runner.run
abort "Test Failures! :(" if runner.failure_count > 0
if options.report
JCov::Reporter::HTMLReporter.new(runner.coverage).report
end
reporter = JCov::Reporter::ConsoleReporter.new(runner.coverage)
abort unless reporter.report
end
end
end
| 20.375 | 69 | 0.643149 |
6292b2217322d8ca85ba1996abc6dfc404750315 | 4,192 | require('capybara/rspec')
require('./app')
Capybara.app = Sinatra::Application
set(:show_exceptions, false)
require('launchy')
describe('home page path', {:type => :feature}) do
it('allows a user to view the homepage') do
visit('/')
expect(page).to have_content('Welcome to Survey Galore')
end
end
describe('add a new survey', {:type => :feature}) do
it('allows the user to add a survey') do
visit('/')
click_link('Add new survey')
fill_in("name", :with => 'cat')
click_button('Add survey')
expect(page).to have_content('CAT')
end
end
describe('view single survey instance path', {:type => :feature}) do
it('allows the user to view a single survey') do
visit('/')
click_link('Add new survey')
fill_in("name", :with => 'cat')
click_button('Add survey')
expect(page).to have_content('CAT')
click_link("CAT")
expect(page).to have_content('Individual survey page')
end
end
describe('update a surveys name path', {:type => :feature}) do
it('allows the user to update the survey name') do
visit('/')
click_link('Add new survey')
fill_in("name", :with => 'cat')
click_button('Add survey')
expect(page).to have_content('CAT')
click_link("CAT")
click_link("Update")
fill_in('name', :with => 'DOG')
click_button('Update')
expect(page).to have_content('DOG')
end
end
describe('delete a survey', {:type => :feature}) do
it('allows the user to delete a survey') do
visit('/')
click_link('Add new survey')
fill_in("name", :with => 'CAT')
click_button('Add survey')
expect(page).to have_content('CAT')
click_link("CAT")
click_link("Update")
click_button('Delete')
expect(page).to have_content('Current Surveys in Database')
end
end
describe('add a new question', {:type => :feature}) do
it('allows the user to add a question') do
visit('/')
click_link('Add new survey')
fill_in("name", :with => 'cat')
click_button('Add survey')
expect(page).to have_content('CAT')
visit('/')
click_link('Add new question')
fill_in("description", :with => "Do you like cats?")
click_button('Add question')
expect(page).to have_content('Do you like cats?')
end
end
describe('view single question path', {:type => :feature}) do
it('allows a user to view a single question') do
visit('/')
click_link('Add new survey')
fill_in("name", :with => 'cat')
click_button('Add survey')
expect(page).to have_content('CAT')
visit('/')
click_link('Add new question')
fill_in("description", :with => "Do you like cats?")
click_button('Add question')
expect(page).to have_content('Do you like cats?')
click_link('Do you like cats?')
expect(page).to have_content("Individual question page")
end
end
describe('edit a question path', {:type => :feature}) do
it('allows the user to edit the contents of a question') do
visit('/')
click_link('Add new survey')
fill_in("name", :with => 'cat')
click_button('Add survey')
expect(page).to have_content('CAT')
visit('/')
click_link('Add new question')
fill_in("description", :with => "Do you like cats?")
click_button('Add question')
expect(page).to have_content('Do you like cats?')
click_link('Do you like cats?')
expect(page).to have_content("Individual question page")
fill_in('description', :with => "Do you hate cats?")
click_button('Update')
expect(page).to have_content('Do you hate cats?')
end
end
describe('remove a question path', {:type => :feature}) do
it('allows the user to edit the contents of the question') do
visit('/')
click_link('Add new survey')
fill_in("name", :with => 'cat')
click_button('Add survey')
expect(page).to have_content('CAT')
visit('/')
click_link('Add new question')
fill_in("description", :with => "Do you like cats?")
click_button('Add question')
expect(page).to have_content('Do you like cats?')
click_link('Do you like cats?')
expect(page).to have_content("Individual question page")
click_button('Delete')
expect(page).to have_content('Current Questions in Database')
end
end
| 30.823529 | 68 | 0.650048 |
7982b841e35d45c3c81d47b676995a54c58f0728 | 5,698 | require 'dependency'
require 'dependencies'
require 'requirement'
require 'requirements'
require 'requirements/ld64_dependency'
require 'set'
## A dependency is a formula that another formula needs to install.
## A requirement is something other than a formula that another formula
## needs to be present. This includes external language modules,
## command-line tools in the path, or any arbitrary predicate.
##
## The `depends_on` method in the formula DSL is used to declare
## dependencies and requirements.
# This class is used by `depends_on` in the formula DSL to turn dependency
# specifications into the proper kinds of dependencies and requirements.
class DependencyCollector
# Define the languages that we can handle as external dependencies.
LANGUAGE_MODULES = Set[
:chicken, :jruby, :lua, :node, :ocaml, :perl, :python, :rbx, :ruby
].freeze
CACHE = {}
attr_reader :deps, :requirements
def initialize
@deps = Dependencies.new
@requirements = ComparableSet.new
end
def add(spec)
case dep = fetch(spec)
when Dependency
@deps << dep
when Requirement
@requirements << dep
end
dep
end
def fetch(spec)
CACHE.fetch(cache_key(spec)) { |key| CACHE[key] = build(spec) }
end
def cache_key(spec)
if Resource === spec && spec.download_strategy == CurlDownloadStrategy
File.extname(spec.url)
else
spec
end
end
def build(spec)
spec, tags = case spec
when Hash then destructure_spec_hash(spec)
else spec
end
parse_spec(spec, Array(tags))
end
private
def destructure_spec_hash(spec)
spec.each { |o| return o }
end
def parse_spec(spec, tags)
case spec
when String
parse_string_spec(spec, tags)
when Resource
resource_dep(spec, tags)
when Symbol
parse_symbol_spec(spec, tags)
when Requirement, Dependency
spec
when Class
parse_class_spec(spec, tags)
else
raise TypeError, "Unsupported type #{spec.class} for #{spec.inspect}"
end
end
def parse_string_spec(spec, tags)
if tags.empty?
Dependency.new(spec, tags)
elsif (tag = tags.first) && LANGUAGE_MODULES.include?(tag)
LanguageModuleDependency.new(tag, spec)
elsif HOMEBREW_TAP_FORMULA_REGEX === spec
TapDependency.new(spec, tags)
else
Dependency.new(spec, tags)
end
end
def parse_symbol_spec(spec, tags)
case spec
when :autoconf, :automake, :bsdmake, :libtool, :libltdl
# Xcode no longer provides autotools or some other build tools
autotools_dep(spec, tags)
when :x11 then X11Dependency.new(spec.to_s, tags)
when *X11Dependency::Proxy::PACKAGES
x11_dep(spec, tags)
when :cairo, :pixman
# We no longer use X11 psuedo-deps for cairo or pixman,
# so just return a standard formula dependency.
Dependency.new(spec.to_s, tags)
when :xcode then XcodeDependency.new(tags)
when :macos then MinimumMacOSRequirement.new(tags)
when :mysql then MysqlDependency.new(tags)
when :postgresql then PostgresqlDependency.new(tags)
when :fortran then FortranDependency.new(tags)
when :mpi then MPIDependency.new(*tags)
when :tex then TeXDependency.new(tags)
when :clt then CLTDependency.new(tags)
when :arch then ArchRequirement.new(tags)
when :hg then MercurialDependency.new(tags)
# python2 is deprecated
when :python, :python2 then PythonDependency.new(tags)
when :python3 then Python3Dependency.new(tags)
# Tiger's ld is too old to properly link some software
when :ld64 then LD64Dependency.new if MacOS.version < :leopard
when :ant then ant_dep(spec, tags)
else
raise "Unsupported special dependency #{spec.inspect}"
end
end
def parse_class_spec(spec, tags)
if spec < Requirement
spec.new(tags)
else
raise TypeError, "#{spec.inspect} is not a Requirement subclass"
end
end
def x11_dep(spec, tags)
if MacOS.version >= :mountain_lion
Dependency.new(spec.to_s, tags)
else
X11Dependency::Proxy.for(spec.to_s, tags)
end
end
def autotools_dep(spec, tags)
return if MacOS::Xcode.provides_autotools?
if spec == :libltdl
spec = :libtool
tags << :run
end
tags << :build unless tags.include? :run
Dependency.new(spec.to_s, tags)
end
def ant_dep(spec, tags)
if MacOS.version >= :mavericks
tags << :build
Dependency.new(spec.to_s, tags)
end
end
def resource_dep(spec, tags)
tags << :build
strategy = spec.download_strategy
case
when strategy <= CurlDownloadStrategy
parse_url_spec(spec.url, tags)
when strategy <= GitDownloadStrategy
GitDependency.new(tags)
when strategy <= MercurialDownloadStrategy
MercurialDependency.new(tags)
when strategy <= FossilDownloadStrategy
Dependency.new("fossil", tags)
when strategy <= BazaarDownloadStrategy
Dependency.new("bazaar", tags)
when strategy <= CVSDownloadStrategy
Dependency.new("cvs", tags) unless MacOS::Xcode.provides_cvs?
when strategy < AbstractDownloadStrategy
# allow unknown strategies to pass through
else
raise TypeError,
"#{strategy.inspect} is not an AbstractDownloadStrategy subclass"
end
end
def parse_url_spec(url, tags)
case File.extname(url)
when '.xz' then Dependency.new('xz', tags)
when '.lz' then Dependency.new('lzip', tags)
when '.rar' then Dependency.new('unrar', tags)
when '.7z' then Dependency.new('p7zip', tags)
end
end
end
| 28.348259 | 75 | 0.675325 |
7978f93cb5e03959fcf1d3b9d82d9c9bd8a6f156 | 429 | class ProtoJ::Utils
def self.to_sorted_hash(hash)
if hash.is_a? Hash
hash = Hash[hash.sort]
hash.each_pair do |k,v|
hash[k] = to_sorted_hash(v)
end
return hash
elsif hash.is_a? Array
return hash.collect do |item|
to_sorted_hash(item)
end
else
return hash
end
end
def self.to_sorted_json(json)
to_sorted_hash(JSON.parse(json)).to_json
end
end
| 19.5 | 44 | 0.624709 |
6210b0570c32d71d28f03eed45692ee402c348ac | 57 | module Net
module SSHD
VERSION = '0.0.1'
end
end
| 9.5 | 21 | 0.614035 |
086bf3cbe13ef7674071750c0a02542480452a64 | 4,806 | require 'pathname'
Puppet::Type.newtype(:dsc_xscsrserverupdate) do
require Pathname.new(__FILE__).dirname + '../../' + 'puppet/type/base_dsc'
require Pathname.new(__FILE__).dirname + '../../puppet_x/puppetlabs/dsc_type_helpers'
@doc = %q{
The DSC xSCSRServerUpdate resource type.
Automatically generated from
'xSCSR/DSCResources/MSFT_xSCSRServerUpdate/MSFT_xSCSRServerUpdate.schema.mof'
To learn more about PowerShell Desired State Configuration, please
visit https://technet.microsoft.com/en-us/library/dn249912.aspx.
For more information about built-in DSC Resources, please visit
https://technet.microsoft.com/en-us/library/dn249921.aspx.
For more information about xDsc Resources, please visit
https://github.com/PowerShell/DscResources.
}
validate do
fail('dsc_ensure is a required attribute') if self[:dsc_ensure].nil?
end
def dscmeta_resource_friendly_name; 'xSCSRServerUpdate' end
def dscmeta_resource_name; 'MSFT_xSCSRServerUpdate' end
def dscmeta_module_name; 'xSCSR' end
def dscmeta_module_version; '1.3.0.0' end
newparam(:name, :namevar => true ) do
end
ensurable do
newvalue(:exists?) { provider.exists? }
newvalue(:present) { provider.create }
newvalue(:absent) { provider.destroy }
defaultto { :present }
end
# Name: PsDscRunAsCredential
# Type: MSFT_Credential
# IsMandatory: False
# Values: None
newparam(:dsc_psdscrunascredential) do
def mof_type; 'MSFT_Credential' end
def mof_is_embedded?; true end
desc "PsDscRunAsCredential"
validate do |value|
unless value.kind_of?(Hash)
fail("Invalid value '#{value}'. Should be a hash")
end
PuppetX::Dsc::TypeHelpers.validate_MSFT_Credential("Credential", value)
end
end
# Name: Ensure
# Type: string
# IsMandatory: True
# Values: ["Present", "Absent"]
newparam(:dsc_ensure) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "Ensure - An enumerated value that describes if the update is expected to be installed on the machine.\nPresent {default} \nAbsent \n Valid values are Present, Absent."
isrequired
validate do |value|
resource[:ensure] = value.downcase
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
unless ['Present', 'present', 'Absent', 'absent'].include?(value)
fail("Invalid value '#{value}'. Valid values are Present, Absent")
end
end
end
# Name: SourcePath
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_sourcepath) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "SourcePath - UNC path to the root of the source files for installation."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: SourceFolder
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_sourcefolder) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "SourceFolder - Folder within the source path containing the source files for installation."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: SetupCredential
# Type: MSFT_Credential
# IsMandatory: False
# Values: None
newparam(:dsc_setupcredential) do
def mof_type; 'MSFT_Credential' end
def mof_is_embedded?; true end
desc "SetupCredential - Credential to be used to perform the installation."
validate do |value|
unless value.kind_of?(Hash)
fail("Invalid value '#{value}'. Should be a hash")
end
PuppetX::Dsc::TypeHelpers.validate_MSFT_Credential("SetupCredential", value)
end
end
# Name: Update
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_update) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "Update - Display name of the update."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
def builddepends
pending_relations = super()
PuppetX::Dsc::TypeHelpers.ensure_reboot_relationship(self, pending_relations)
end
end
Puppet::Type.type(:dsc_xscsrserverupdate).provide :powershell, :parent => Puppet::Type.type(:base_dsc).provider(:powershell) do
confine :true => (Gem::Version.new(Facter.value(:powershell_version)) >= Gem::Version.new('5.0.10586.117'))
defaultfor :operatingsystem => :windows
mk_resource_methods
end
| 31.618421 | 180 | 0.674573 |
e9ee81ccb3e192e5a4cec4aad56b3482640c7f60 | 319 | class Item < ActiveRecord::Base
belongs_to :category
has_many :purchase_items
has_many :purchases, through: :purchase_items
validates :name, :price, :category_id, presence: true
validates :name, uniqueness: true
validates :name, uniqueness: { scope: :category, message: "unique name within category" }
end
| 35.444444 | 91 | 0.755486 |
5d8a08e8aee20708ddbdc0f1ac0f423e9a4048f3 | 1,044 | require 'rubygems'
Gem::Specification.new do |spec|
spec.name = 'win32-api'
spec.version = '1.10.1'
spec.authors = ['Daniel J. Berger', 'Park Heesob', 'Hiroshi Hatake']
spec.license = 'Artistic-2.0'
spec.email = '[email protected]'
spec.homepage = 'http://github.com/cosmo0920/win32-api'
spec.summary = 'A superior replacement for Win32API'
spec.test_files = Dir['test/test*']
spec.extensions = ['ext/extconf.rb']
spec.files = Dir['**/*'].reject{ |f| f.include?('git') }
spec.required_ruby_version = '>= 1.8.2'
spec.extra_rdoc_files = ['CHANGES', 'MANIFEST', 'ext/win32/api.c']
spec.add_development_dependency('test-unit', '>= 2.5.0')
spec.add_development_dependency('rake')
spec.description = <<-EOF
The Win32::API library is meant as a replacement for the Win32API
library that ships as part of the standard library. It contains several
advantages over Win32API, including callback support, raw function
pointers, an additional string type, and more.
EOF
end
| 37.285714 | 75 | 0.679119 |
91442c2d4cfdba546b70019cc759845d3aa6e8b4 | 2,041 | # Reader - fgdc to internal data structure
# unpack fgdc map projection - general vertical near-side perspective projection
# History:
# Stan Smith 2018-10-03 refactor mdJson projection object
# Stan Smith 2017-10-16 original script
require 'nokogiri'
require 'adiwg/mdtranslator/internal/internal_metadata_obj'
require_relative 'projection_common'
module ADIWG
module Mdtranslator
module Readers
module Fgdc
module GeneralVerticalProjection
def self.unpack(xParams, hProjection, hResponseObj)
# map projection 4.1.2.1.6 (gvnsp) - General Vertical Near-sided Perspective
unless xParams.empty?
paramCount = 0
# -> ReferenceSystemParameters.projection.heightOfProspectivePointAboveSurface
paramCount += ProjectionCommon.unpackHeightAS(xParams, hProjection)
# -> ReferenceSystemParameters.projection.longitudeOfProjectionCenter
paramCount += ProjectionCommon.unpackLongPC(xParams, hProjection)
# -> ReferenceSystemParameters.projection.latitudeOfProjectionCenter
paramCount += ProjectionCommon.unpackLatPC(xParams, hProjection)
# -> ReferenceSystemParameters.projection.falseEasting
# -> ReferenceSystemParameters.projection.falseNorthing
paramCount += ProjectionCommon.unpackFalseNE(xParams, hProjection)
# add distance units
# verify parameter count
if paramCount == 5
return hProjection
else
hResponseObj[:readerExecutionMessages] <<
'WARNING: General Vertical Near-side perspective projection is missing one or more parameters'
end
end
return nil
end
end
end
end
end
end
| 35.189655 | 121 | 0.603136 |
1d05337980d3accfeee207311474c3c45fe21b69 | 254,597 | # Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'date'
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 SheetsV4
# The response when updating a range of values in a spreadsheet.
class UpdateValuesResponse
include Google::Apis::Core::Hashable
# Data within a range of the spreadsheet.
# Corresponds to the JSON property `updatedData`
# @return [Google::Apis::SheetsV4::ValueRange]
attr_accessor :updated_data
# The number of rows where at least one cell in the row was updated.
# Corresponds to the JSON property `updatedRows`
# @return [Fixnum]
attr_accessor :updated_rows
# The number of columns where at least one cell in the column was updated.
# Corresponds to the JSON property `updatedColumns`
# @return [Fixnum]
attr_accessor :updated_columns
# The spreadsheet the updates were applied to.
# Corresponds to the JSON property `spreadsheetId`
# @return [String]
attr_accessor :spreadsheet_id
# The range (in A1 notation) that updates were applied to.
# Corresponds to the JSON property `updatedRange`
# @return [String]
attr_accessor :updated_range
# The number of cells updated.
# Corresponds to the JSON property `updatedCells`
# @return [Fixnum]
attr_accessor :updated_cells
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@updated_data = args[:updated_data] if args.key?(:updated_data)
@updated_rows = args[:updated_rows] if args.key?(:updated_rows)
@updated_columns = args[:updated_columns] if args.key?(:updated_columns)
@spreadsheet_id = args[:spreadsheet_id] if args.key?(:spreadsheet_id)
@updated_range = args[:updated_range] if args.key?(:updated_range)
@updated_cells = args[:updated_cells] if args.key?(:updated_cells)
end
end
# The definition of how a value in a pivot table should be calculated.
class PivotValue
include Google::Apis::Core::Hashable
# The column offset of the source range that this value reads from.
# For example, if the source was `C10:E15`, a `sourceColumnOffset` of `0`
# means this value refers to column `C`, whereas the offset `1` would
# refer to column `D`.
# Corresponds to the JSON property `sourceColumnOffset`
# @return [Fixnum]
attr_accessor :source_column_offset
# A name to use for the value. This is only used if formula was set.
# Otherwise, the column name is used.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# A custom formula to calculate the value. The formula must start
# with an `=` character.
# Corresponds to the JSON property `formula`
# @return [String]
attr_accessor :formula
# A function to summarize the value.
# If formula is set, the only supported values are
# SUM and
# CUSTOM.
# If sourceColumnOffset is set, then `CUSTOM`
# is not supported.
# Corresponds to the JSON property `summarizeFunction`
# @return [String]
attr_accessor :summarize_function
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@source_column_offset = args[:source_column_offset] if args.key?(:source_column_offset)
@name = args[:name] if args.key?(:name)
@formula = args[:formula] if args.key?(:formula)
@summarize_function = args[:summarize_function] if args.key?(:summarize_function)
end
end
# An error in a cell.
class ErrorValue
include Google::Apis::Core::Hashable
# A message with more information about the error
# (in the spreadsheet's locale).
# Corresponds to the JSON property `message`
# @return [String]
attr_accessor :message
# The type of error.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@message = args[:message] if args.key?(:message)
@type = args[:type] if args.key?(:type)
end
end
# The request to copy a sheet across spreadsheets.
class CopySheetToAnotherSpreadsheetRequest
include Google::Apis::Core::Hashable
# The ID of the spreadsheet to copy the sheet to.
# Corresponds to the JSON property `destinationSpreadsheetId`
# @return [String]
attr_accessor :destination_spreadsheet_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@destination_spreadsheet_id = args[:destination_spreadsheet_id] if args.key?(:destination_spreadsheet_id)
end
end
# Information about which values in a pivot group should be used for sorting.
class PivotGroupSortValueBucket
include Google::Apis::Core::Hashable
# Determines the bucket from which values are chosen to sort.
# For example, in a pivot table with one row group & two column groups,
# the row group can list up to two values. The first value corresponds
# to a value within the first column group, and the second value
# corresponds to a value in the second column group. If no values
# are listed, this would indicate that the row should be sorted according
# to the "Grand Total" over the column groups. If a single value is listed,
# this would correspond to using the "Total" of that bucket.
# Corresponds to the JSON property `buckets`
# @return [Array<Google::Apis::SheetsV4::ExtendedValue>]
attr_accessor :buckets
# The offset in the PivotTable.values list which the values in this
# grouping should be sorted by.
# Corresponds to the JSON property `valuesIndex`
# @return [Fixnum]
attr_accessor :values_index
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@buckets = args[:buckets] if args.key?(:buckets)
@values_index = args[:values_index] if args.key?(:values_index)
end
end
# The position of an embedded object such as a chart.
class EmbeddedObjectPosition
include Google::Apis::Core::Hashable
# If true, the embedded object will be put on a new sheet whose ID
# is chosen for you. Used only when writing.
# Corresponds to the JSON property `newSheet`
# @return [Boolean]
attr_accessor :new_sheet
alias_method :new_sheet?, :new_sheet
# The sheet this is on. Set only if the embedded object
# is on its own sheet. Must be non-negative.
# Corresponds to the JSON property `sheetId`
# @return [Fixnum]
attr_accessor :sheet_id
# The location an object is overlaid on top of a grid.
# Corresponds to the JSON property `overlayPosition`
# @return [Google::Apis::SheetsV4::OverlayPosition]
attr_accessor :overlay_position
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@new_sheet = args[:new_sheet] if args.key?(:new_sheet)
@sheet_id = args[:sheet_id] if args.key?(:sheet_id)
@overlay_position = args[:overlay_position] if args.key?(:overlay_position)
end
end
# Deletes the protected range with the given ID.
class DeleteProtectedRangeRequest
include Google::Apis::Core::Hashable
# The ID of the protected range to delete.
# Corresponds to the JSON property `protectedRangeId`
# @return [Fixnum]
attr_accessor :protected_range_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@protected_range_id = args[:protected_range_id] if args.key?(:protected_range_id)
end
end
# Fills in more data based on existing data.
class AutoFillRequest
include Google::Apis::Core::Hashable
# True if we should generate data with the "alternate" series.
# This differs based on the type and amount of source data.
# Corresponds to the JSON property `useAlternateSeries`
# @return [Boolean]
attr_accessor :use_alternate_series
alias_method :use_alternate_series?, :use_alternate_series
# A combination of a source range and how to extend that source.
# Corresponds to the JSON property `sourceAndDestination`
# @return [Google::Apis::SheetsV4::SourceAndDestination]
attr_accessor :source_and_destination
# A range on a sheet.
# All indexes are zero-based.
# Indexes are half open, e.g the start index is inclusive
# and the end index is exclusive -- [start_index, end_index).
# Missing indexes indicate the range is unbounded on that side.
# For example, if `"Sheet1"` is sheet ID 0, then:
# `Sheet1!A1:A1 == sheet_id: 0,
# start_row_index: 0, end_row_index: 1,
# start_column_index: 0, end_column_index: 1`
# `Sheet1!A3:B4 == sheet_id: 0,
# start_row_index: 2, end_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A:B == sheet_id: 0,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A5:B == sheet_id: 0,
# start_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1 == sheet_id:0`
# The start index must always be less than or equal to the end index.
# If the start index equals the end index, then the range is empty.
# Empty ranges are typically not meaningful and are usually rendered in the
# UI as `#REF!`.
# Corresponds to the JSON property `range`
# @return [Google::Apis::SheetsV4::GridRange]
attr_accessor :range
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@use_alternate_series = args[:use_alternate_series] if args.key?(:use_alternate_series)
@source_and_destination = args[:source_and_destination] if args.key?(:source_and_destination)
@range = args[:range] if args.key?(:range)
end
end
# A rule that applies a gradient color scale format, based on
# the interpolation points listed. The format of a cell will vary
# based on its contents as compared to the values of the interpolation
# points.
class GradientRule
include Google::Apis::Core::Hashable
# A single interpolation point on a gradient conditional format.
# These pin the gradient color scale according to the color,
# type and value chosen.
# Corresponds to the JSON property `minpoint`
# @return [Google::Apis::SheetsV4::InterpolationPoint]
attr_accessor :minpoint
# A single interpolation point on a gradient conditional format.
# These pin the gradient color scale according to the color,
# type and value chosen.
# Corresponds to the JSON property `maxpoint`
# @return [Google::Apis::SheetsV4::InterpolationPoint]
attr_accessor :maxpoint
# A single interpolation point on a gradient conditional format.
# These pin the gradient color scale according to the color,
# type and value chosen.
# Corresponds to the JSON property `midpoint`
# @return [Google::Apis::SheetsV4::InterpolationPoint]
attr_accessor :midpoint
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@minpoint = args[:minpoint] if args.key?(:minpoint)
@maxpoint = args[:maxpoint] if args.key?(:maxpoint)
@midpoint = args[:midpoint] if args.key?(:midpoint)
end
end
# Sets the basic filter associated with a sheet.
class SetBasicFilterRequest
include Google::Apis::Core::Hashable
# The default filter associated with a sheet.
# Corresponds to the JSON property `filter`
# @return [Google::Apis::SheetsV4::BasicFilter]
attr_accessor :filter
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@filter = args[:filter] if args.key?(:filter)
end
end
# The request for clearing a range of values in a spreadsheet.
class ClearValuesRequest
include Google::Apis::Core::Hashable
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
end
end
# A single interpolation point on a gradient conditional format.
# These pin the gradient color scale according to the color,
# type and value chosen.
class InterpolationPoint
include Google::Apis::Core::Hashable
# Represents a color in the RGBA color space. This representation is designed
# for simplicity of conversion to/from color representations in various
# languages over compactness; for example, the fields of this representation
# can be trivially provided to the constructor of "java.awt.Color" in Java; it
# can also be trivially provided to UIColor's "+colorWithRed:green:blue:alpha"
# method in iOS; and, with just a little work, it can be easily formatted into
# a CSS "rgba()" string in JavaScript, as well. Here are some examples:
# Example (Java):
# import com.google.type.Color;
# // ...
# public static java.awt.Color fromProto(Color protocolor) `
# float alpha = protocolor.hasAlpha()
# ? protocolor.getAlpha().getValue()
# : 1.0;
# return new java.awt.Color(
# protocolor.getRed(),
# protocolor.getGreen(),
# protocolor.getBlue(),
# alpha);
# `
# public static Color toProto(java.awt.Color color) `
# float red = (float) color.getRed();
# float green = (float) color.getGreen();
# float blue = (float) color.getBlue();
# float denominator = 255.0;
# Color.Builder resultBuilder =
# Color
# .newBuilder()
# .setRed(red / denominator)
# .setGreen(green / denominator)
# .setBlue(blue / denominator);
# int alpha = color.getAlpha();
# if (alpha != 255) `
# result.setAlpha(
# FloatValue
# .newBuilder()
# .setValue(((float) alpha) / denominator)
# .build());
# `
# return resultBuilder.build();
# `
# // ...
# Example (iOS / Obj-C):
# // ...
# static UIColor* fromProto(Color* protocolor) `
# float red = [protocolor red];
# float green = [protocolor green];
# float blue = [protocolor blue];
# FloatValue* alpha_wrapper = [protocolor alpha];
# float alpha = 1.0;
# if (alpha_wrapper != nil) `
# alpha = [alpha_wrapper value];
# `
# return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
# `
# static Color* toProto(UIColor* color) `
# CGFloat red, green, blue, alpha;
# if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) `
# return nil;
# `
# Color* result = [Color alloc] init];
# [result setRed:red];
# [result setGreen:green];
# [result setBlue:blue];
# if (alpha <= 0.9999) `
# [result setAlpha:floatWrapperWithValue(alpha)];
# `
# [result autorelease];
# return result;
# `
# // ...
# Example (JavaScript):
# // ...
# var protoToCssColor = function(rgb_color) `
# var redFrac = rgb_color.red || 0.0;
# var greenFrac = rgb_color.green || 0.0;
# var blueFrac = rgb_color.blue || 0.0;
# var red = Math.floor(redFrac * 255);
# var green = Math.floor(greenFrac * 255);
# var blue = Math.floor(blueFrac * 255);
# if (!('alpha' in rgb_color)) `
# return rgbToCssColor_(red, green, blue);
# `
# var alphaFrac = rgb_color.alpha.value || 0.0;
# var rgbParams = [red, green, blue].join(',');
# return ['rgba(', rgbParams, ',', alphaFrac, ')'].join('');
# `;
# var rgbToCssColor_ = function(red, green, blue) `
# var rgbNumber = new Number((red << 16) | (green << 8) | blue);
# var hexString = rgbNumber.toString(16);
# var missingZeros = 6 - hexString.length;
# var resultBuilder = ['#'];
# for (var i = 0; i < missingZeros; i++) `
# resultBuilder.push('0');
# `
# resultBuilder.push(hexString);
# return resultBuilder.join('');
# `;
# // ...
# Corresponds to the JSON property `color`
# @return [Google::Apis::SheetsV4::Color]
attr_accessor :color
# How the value should be interpreted.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
# The value this interpolation point uses. May be a formula.
# Unused if type is MIN or
# MAX.
# Corresponds to the JSON property `value`
# @return [String]
attr_accessor :value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@color = args[:color] if args.key?(:color)
@type = args[:type] if args.key?(:type)
@value = args[:value] if args.key?(:value)
end
end
# The result of the find/replace.
class FindReplaceResponse
include Google::Apis::Core::Hashable
# The number of non-formula cells changed.
# Corresponds to the JSON property `valuesChanged`
# @return [Fixnum]
attr_accessor :values_changed
# The number of occurrences (possibly multiple within a cell) changed.
# For example, if replacing `"e"` with `"o"` in `"Google Sheets"`, this would
# be `"3"` because `"Google Sheets"` -> `"Googlo Shoots"`.
# Corresponds to the JSON property `occurrencesChanged`
# @return [Fixnum]
attr_accessor :occurrences_changed
# The number of rows changed.
# Corresponds to the JSON property `rowsChanged`
# @return [Fixnum]
attr_accessor :rows_changed
# The number of sheets changed.
# Corresponds to the JSON property `sheetsChanged`
# @return [Fixnum]
attr_accessor :sheets_changed
# The number of formula cells changed.
# Corresponds to the JSON property `formulasChanged`
# @return [Fixnum]
attr_accessor :formulas_changed
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@values_changed = args[:values_changed] if args.key?(:values_changed)
@occurrences_changed = args[:occurrences_changed] if args.key?(:occurrences_changed)
@rows_changed = args[:rows_changed] if args.key?(:rows_changed)
@sheets_changed = args[:sheets_changed] if args.key?(:sheets_changed)
@formulas_changed = args[:formulas_changed] if args.key?(:formulas_changed)
end
end
# Deletes the embedded object with the given ID.
class DeleteEmbeddedObjectRequest
include Google::Apis::Core::Hashable
# The ID of the embedded object to delete.
# Corresponds to the JSON property `objectId`
# @return [Fixnum]
attr_accessor :object_id_prop
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@object_id_prop = args[:object_id_prop] if args.key?(:object_id_prop)
end
end
# Deletes the requested sheet.
class DeleteSheetRequest
include Google::Apis::Core::Hashable
# The ID of the sheet to delete.
# Corresponds to the JSON property `sheetId`
# @return [Fixnum]
attr_accessor :sheet_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@sheet_id = args[:sheet_id] if args.key?(:sheet_id)
end
end
# Duplicates a particular filter view.
class DuplicateFilterViewRequest
include Google::Apis::Core::Hashable
# The ID of the filter being duplicated.
# Corresponds to the JSON property `filterId`
# @return [Fixnum]
attr_accessor :filter_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@filter_id = args[:filter_id] if args.key?(:filter_id)
end
end
# The result of updating a conditional format rule.
class UpdateConditionalFormatRuleResponse
include Google::Apis::Core::Hashable
# The old index of the rule. Not set if a rule was replaced
# (because it is the same as new_index).
# Corresponds to the JSON property `oldIndex`
# @return [Fixnum]
attr_accessor :old_index
# A rule describing a conditional format.
# Corresponds to the JSON property `newRule`
# @return [Google::Apis::SheetsV4::ConditionalFormatRule]
attr_accessor :new_rule
# A rule describing a conditional format.
# Corresponds to the JSON property `oldRule`
# @return [Google::Apis::SheetsV4::ConditionalFormatRule]
attr_accessor :old_rule
# The index of the new rule.
# Corresponds to the JSON property `newIndex`
# @return [Fixnum]
attr_accessor :new_index
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@old_index = args[:old_index] if args.key?(:old_index)
@new_rule = args[:new_rule] if args.key?(:new_rule)
@old_rule = args[:old_rule] if args.key?(:old_rule)
@new_index = args[:new_index] if args.key?(:new_index)
end
end
# The value of the condition.
class ConditionValue
include Google::Apis::Core::Hashable
# A relative date (based on the current date).
# Valid only if the type is
# DATE_BEFORE,
# DATE_AFTER,
# DATE_ON_OR_BEFORE or
# DATE_ON_OR_AFTER.
# Relative dates are not supported in data validation.
# They are supported only in conditional formatting and
# conditional filters.
# Corresponds to the JSON property `relativeDate`
# @return [String]
attr_accessor :relative_date
# A value the condition is based on.
# The value will be parsed as if the user typed into a cell.
# Formulas are supported (and must begin with an `=`).
# Corresponds to the JSON property `userEnteredValue`
# @return [String]
attr_accessor :user_entered_value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@relative_date = args[:relative_date] if args.key?(:relative_date)
@user_entered_value = args[:user_entered_value] if args.key?(:user_entered_value)
end
end
# Duplicates the contents of a sheet.
class DuplicateSheetRequest
include Google::Apis::Core::Hashable
# The name of the new sheet. If empty, a new name is chosen for you.
# Corresponds to the JSON property `newSheetName`
# @return [String]
attr_accessor :new_sheet_name
# The sheet to duplicate.
# Corresponds to the JSON property `sourceSheetId`
# @return [Fixnum]
attr_accessor :source_sheet_id
# If set, the ID of the new sheet. If not set, an ID is chosen.
# If set, the ID must not conflict with any existing sheet ID.
# If set, it must be non-negative.
# Corresponds to the JSON property `newSheetId`
# @return [Fixnum]
attr_accessor :new_sheet_id
# The zero-based index where the new sheet should be inserted.
# The index of all sheets after this are incremented.
# Corresponds to the JSON property `insertSheetIndex`
# @return [Fixnum]
attr_accessor :insert_sheet_index
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@new_sheet_name = args[:new_sheet_name] if args.key?(:new_sheet_name)
@source_sheet_id = args[:source_sheet_id] if args.key?(:source_sheet_id)
@new_sheet_id = args[:new_sheet_id] if args.key?(:new_sheet_id)
@insert_sheet_index = args[:insert_sheet_index] if args.key?(:insert_sheet_index)
end
end
# The kinds of value that a cell in a spreadsheet can have.
class ExtendedValue
include Google::Apis::Core::Hashable
# An error in a cell.
# Corresponds to the JSON property `errorValue`
# @return [Google::Apis::SheetsV4::ErrorValue]
attr_accessor :error_value
# Represents a string value.
# Leading single quotes are not included. For example, if the user typed
# `'123` into the UI, this would be represented as a `stringValue` of
# `"123"`.
# Corresponds to the JSON property `stringValue`
# @return [String]
attr_accessor :string_value
# Represents a boolean value.
# Corresponds to the JSON property `boolValue`
# @return [Boolean]
attr_accessor :bool_value
alias_method :bool_value?, :bool_value
# Represents a formula.
# Corresponds to the JSON property `formulaValue`
# @return [String]
attr_accessor :formula_value
# Represents a double value.
# Note: Dates, Times and DateTimes are represented as doubles in
# "serial number" format.
# Corresponds to the JSON property `numberValue`
# @return [Float]
attr_accessor :number_value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@error_value = args[:error_value] if args.key?(:error_value)
@string_value = args[:string_value] if args.key?(:string_value)
@bool_value = args[:bool_value] if args.key?(:bool_value)
@formula_value = args[:formula_value] if args.key?(:formula_value)
@number_value = args[:number_value] if args.key?(:number_value)
end
end
# Adds a chart to a sheet in the spreadsheet.
class AddChartRequest
include Google::Apis::Core::Hashable
# A chart embedded in a sheet.
# Corresponds to the JSON property `chart`
# @return [Google::Apis::SheetsV4::EmbeddedChart]
attr_accessor :chart
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@chart = args[:chart] if args.key?(:chart)
end
end
# Resource that represents a spreadsheet.
class Spreadsheet
include Google::Apis::Core::Hashable
# Properties of a spreadsheet.
# Corresponds to the JSON property `properties`
# @return [Google::Apis::SheetsV4::SpreadsheetProperties]
attr_accessor :properties
# The ID of the spreadsheet.
# This field is read-only.
# Corresponds to the JSON property `spreadsheetId`
# @return [String]
attr_accessor :spreadsheet_id
# The sheets that are part of a spreadsheet.
# Corresponds to the JSON property `sheets`
# @return [Array<Google::Apis::SheetsV4::Sheet>]
attr_accessor :sheets
# The named ranges defined in a spreadsheet.
# Corresponds to the JSON property `namedRanges`
# @return [Array<Google::Apis::SheetsV4::NamedRange>]
attr_accessor :named_ranges
# The url of the spreadsheet.
# This field is read-only.
# Corresponds to the JSON property `spreadsheetUrl`
# @return [String]
attr_accessor :spreadsheet_url
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@properties = args[:properties] if args.key?(:properties)
@spreadsheet_id = args[:spreadsheet_id] if args.key?(:spreadsheet_id)
@sheets = args[:sheets] if args.key?(:sheets)
@named_ranges = args[:named_ranges] if args.key?(:named_ranges)
@spreadsheet_url = args[:spreadsheet_url] if args.key?(:spreadsheet_url)
end
end
# The response when updating a range of values in a spreadsheet.
class BatchClearValuesResponse
include Google::Apis::Core::Hashable
# The ranges that were cleared, in A1 notation.
# (If the requests were for an unbounded range or a ranger larger
# than the bounds of the sheet, this will be the actual ranges
# that were cleared, bounded to the sheet's limits.)
# Corresponds to the JSON property `clearedRanges`
# @return [Array<String>]
attr_accessor :cleared_ranges
# The spreadsheet the updates were applied to.
# Corresponds to the JSON property `spreadsheetId`
# @return [String]
attr_accessor :spreadsheet_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@cleared_ranges = args[:cleared_ranges] if args.key?(:cleared_ranges)
@spreadsheet_id = args[:spreadsheet_id] if args.key?(:spreadsheet_id)
end
end
# A banded (alternating colors) range in a sheet.
class BandedRange
include Google::Apis::Core::Hashable
# A range on a sheet.
# All indexes are zero-based.
# Indexes are half open, e.g the start index is inclusive
# and the end index is exclusive -- [start_index, end_index).
# Missing indexes indicate the range is unbounded on that side.
# For example, if `"Sheet1"` is sheet ID 0, then:
# `Sheet1!A1:A1 == sheet_id: 0,
# start_row_index: 0, end_row_index: 1,
# start_column_index: 0, end_column_index: 1`
# `Sheet1!A3:B4 == sheet_id: 0,
# start_row_index: 2, end_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A:B == sheet_id: 0,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A5:B == sheet_id: 0,
# start_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1 == sheet_id:0`
# The start index must always be less than or equal to the end index.
# If the start index equals the end index, then the range is empty.
# Empty ranges are typically not meaningful and are usually rendered in the
# UI as `#REF!`.
# Corresponds to the JSON property `range`
# @return [Google::Apis::SheetsV4::GridRange]
attr_accessor :range
# The id of the banded range.
# Corresponds to the JSON property `bandedRangeId`
# @return [Fixnum]
attr_accessor :banded_range_id
# Properties referring a single dimension (either row or column). If both
# BandedRange.row_properties and BandedRange.column_properties are
# set, the fill colors are applied to cells according to the following rules:
# * header_color and footer_color take priority over band colors.
# * first_band_color takes priority over second_band_color.
# * row_properties takes priority over column_properties.
# For example, the first row color takes priority over the first column
# color, but the first column color takes priority over the second row color.
# Similarly, the row header takes priority over the column header in the
# top left cell, but the column header takes priority over the first row
# color if the row header is not set.
# Corresponds to the JSON property `rowProperties`
# @return [Google::Apis::SheetsV4::BandingProperties]
attr_accessor :row_properties
# Properties referring a single dimension (either row or column). If both
# BandedRange.row_properties and BandedRange.column_properties are
# set, the fill colors are applied to cells according to the following rules:
# * header_color and footer_color take priority over band colors.
# * first_band_color takes priority over second_band_color.
# * row_properties takes priority over column_properties.
# For example, the first row color takes priority over the first column
# color, but the first column color takes priority over the second row color.
# Similarly, the row header takes priority over the column header in the
# top left cell, but the column header takes priority over the first row
# color if the row header is not set.
# Corresponds to the JSON property `columnProperties`
# @return [Google::Apis::SheetsV4::BandingProperties]
attr_accessor :column_properties
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@range = args[:range] if args.key?(:range)
@banded_range_id = args[:banded_range_id] if args.key?(:banded_range_id)
@row_properties = args[:row_properties] if args.key?(:row_properties)
@column_properties = args[:column_properties] if args.key?(:column_properties)
end
end
# Updates an existing protected range with the specified
# protectedRangeId.
class UpdateProtectedRangeRequest
include Google::Apis::Core::Hashable
# A protected range.
# Corresponds to the JSON property `protectedRange`
# @return [Google::Apis::SheetsV4::ProtectedRange]
attr_accessor :protected_range
# The fields that should be updated. At least one field must be specified.
# The root `protectedRange` is implied and should not be specified.
# A single `"*"` can be used as short-hand for listing every field.
# Corresponds to the JSON property `fields`
# @return [String]
attr_accessor :fields
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@protected_range = args[:protected_range] if args.key?(:protected_range)
@fields = args[:fields] if args.key?(:fields)
end
end
# The format of a run of text in a cell.
# Absent values indicate that the field isn't specified.
class TextFormat
include Google::Apis::Core::Hashable
# The font family.
# Corresponds to the JSON property `fontFamily`
# @return [String]
attr_accessor :font_family
# True if the text has a strikethrough.
# Corresponds to the JSON property `strikethrough`
# @return [Boolean]
attr_accessor :strikethrough
alias_method :strikethrough?, :strikethrough
# True if the text is italicized.
# Corresponds to the JSON property `italic`
# @return [Boolean]
attr_accessor :italic
alias_method :italic?, :italic
# The size of the font.
# Corresponds to the JSON property `fontSize`
# @return [Fixnum]
attr_accessor :font_size
# True if the text is underlined.
# Corresponds to the JSON property `underline`
# @return [Boolean]
attr_accessor :underline
alias_method :underline?, :underline
# True if the text is bold.
# Corresponds to the JSON property `bold`
# @return [Boolean]
attr_accessor :bold
alias_method :bold?, :bold
# Represents a color in the RGBA color space. This representation is designed
# for simplicity of conversion to/from color representations in various
# languages over compactness; for example, the fields of this representation
# can be trivially provided to the constructor of "java.awt.Color" in Java; it
# can also be trivially provided to UIColor's "+colorWithRed:green:blue:alpha"
# method in iOS; and, with just a little work, it can be easily formatted into
# a CSS "rgba()" string in JavaScript, as well. Here are some examples:
# Example (Java):
# import com.google.type.Color;
# // ...
# public static java.awt.Color fromProto(Color protocolor) `
# float alpha = protocolor.hasAlpha()
# ? protocolor.getAlpha().getValue()
# : 1.0;
# return new java.awt.Color(
# protocolor.getRed(),
# protocolor.getGreen(),
# protocolor.getBlue(),
# alpha);
# `
# public static Color toProto(java.awt.Color color) `
# float red = (float) color.getRed();
# float green = (float) color.getGreen();
# float blue = (float) color.getBlue();
# float denominator = 255.0;
# Color.Builder resultBuilder =
# Color
# .newBuilder()
# .setRed(red / denominator)
# .setGreen(green / denominator)
# .setBlue(blue / denominator);
# int alpha = color.getAlpha();
# if (alpha != 255) `
# result.setAlpha(
# FloatValue
# .newBuilder()
# .setValue(((float) alpha) / denominator)
# .build());
# `
# return resultBuilder.build();
# `
# // ...
# Example (iOS / Obj-C):
# // ...
# static UIColor* fromProto(Color* protocolor) `
# float red = [protocolor red];
# float green = [protocolor green];
# float blue = [protocolor blue];
# FloatValue* alpha_wrapper = [protocolor alpha];
# float alpha = 1.0;
# if (alpha_wrapper != nil) `
# alpha = [alpha_wrapper value];
# `
# return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
# `
# static Color* toProto(UIColor* color) `
# CGFloat red, green, blue, alpha;
# if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) `
# return nil;
# `
# Color* result = [Color alloc] init];
# [result setRed:red];
# [result setGreen:green];
# [result setBlue:blue];
# if (alpha <= 0.9999) `
# [result setAlpha:floatWrapperWithValue(alpha)];
# `
# [result autorelease];
# return result;
# `
# // ...
# Example (JavaScript):
# // ...
# var protoToCssColor = function(rgb_color) `
# var redFrac = rgb_color.red || 0.0;
# var greenFrac = rgb_color.green || 0.0;
# var blueFrac = rgb_color.blue || 0.0;
# var red = Math.floor(redFrac * 255);
# var green = Math.floor(greenFrac * 255);
# var blue = Math.floor(blueFrac * 255);
# if (!('alpha' in rgb_color)) `
# return rgbToCssColor_(red, green, blue);
# `
# var alphaFrac = rgb_color.alpha.value || 0.0;
# var rgbParams = [red, green, blue].join(',');
# return ['rgba(', rgbParams, ',', alphaFrac, ')'].join('');
# `;
# var rgbToCssColor_ = function(red, green, blue) `
# var rgbNumber = new Number((red << 16) | (green << 8) | blue);
# var hexString = rgbNumber.toString(16);
# var missingZeros = 6 - hexString.length;
# var resultBuilder = ['#'];
# for (var i = 0; i < missingZeros; i++) `
# resultBuilder.push('0');
# `
# resultBuilder.push(hexString);
# return resultBuilder.join('');
# `;
# // ...
# Corresponds to the JSON property `foregroundColor`
# @return [Google::Apis::SheetsV4::Color]
attr_accessor :foreground_color
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@font_family = args[:font_family] if args.key?(:font_family)
@strikethrough = args[:strikethrough] if args.key?(:strikethrough)
@italic = args[:italic] if args.key?(:italic)
@font_size = args[:font_size] if args.key?(:font_size)
@underline = args[:underline] if args.key?(:underline)
@bold = args[:bold] if args.key?(:bold)
@foreground_color = args[:foreground_color] if args.key?(:foreground_color)
end
end
# The result of adding a sheet.
class AddSheetResponse
include Google::Apis::Core::Hashable
# Properties of a sheet.
# Corresponds to the JSON property `properties`
# @return [Google::Apis::SheetsV4::SheetProperties]
attr_accessor :properties
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@properties = args[:properties] if args.key?(:properties)
end
end
# The result of adding a filter view.
class AddFilterViewResponse
include Google::Apis::Core::Hashable
# A filter view.
# Corresponds to the JSON property `filter`
# @return [Google::Apis::SheetsV4::FilterView]
attr_accessor :filter
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@filter = args[:filter] if args.key?(:filter)
end
end
# Properties of a spreadsheet.
class SpreadsheetProperties
include Google::Apis::Core::Hashable
# The locale of the spreadsheet in one of the following formats:
# * an ISO 639-1 language code such as `en`
# * an ISO 639-2 language code such as `fil`, if no 639-1 code exists
# * a combination of the ISO language code and country code, such as `en_US`
# Note: when updating this field, not all locales/languages are supported.
# Corresponds to the JSON property `locale`
# @return [String]
attr_accessor :locale
# The amount of time to wait before volatile functions are recalculated.
# Corresponds to the JSON property `autoRecalc`
# @return [String]
attr_accessor :auto_recalc
# The format of a cell.
# Corresponds to the JSON property `defaultFormat`
# @return [Google::Apis::SheetsV4::CellFormat]
attr_accessor :default_format
# The title of the spreadsheet.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
# The time zone of the spreadsheet, in CLDR format such as
# `America/New_York`. If the time zone isn't recognized, this may
# be a custom time zone such as `GMT-07:00`.
# Corresponds to the JSON property `timeZone`
# @return [String]
attr_accessor :time_zone
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@locale = args[:locale] if args.key?(:locale)
@auto_recalc = args[:auto_recalc] if args.key?(:auto_recalc)
@default_format = args[:default_format] if args.key?(:default_format)
@title = args[:title] if args.key?(:title)
@time_zone = args[:time_zone] if args.key?(:time_zone)
end
end
# The location an object is overlaid on top of a grid.
class OverlayPosition
include Google::Apis::Core::Hashable
# The width of the object, in pixels. Defaults to 600.
# Corresponds to the JSON property `widthPixels`
# @return [Fixnum]
attr_accessor :width_pixels
# The horizontal offset, in pixels, that the object is offset
# from the anchor cell.
# Corresponds to the JSON property `offsetXPixels`
# @return [Fixnum]
attr_accessor :offset_x_pixels
# A coordinate in a sheet.
# All indexes are zero-based.
# Corresponds to the JSON property `anchorCell`
# @return [Google::Apis::SheetsV4::GridCoordinate]
attr_accessor :anchor_cell
# The vertical offset, in pixels, that the object is offset
# from the anchor cell.
# Corresponds to the JSON property `offsetYPixels`
# @return [Fixnum]
attr_accessor :offset_y_pixels
# The height of the object, in pixels. Defaults to 371.
# Corresponds to the JSON property `heightPixels`
# @return [Fixnum]
attr_accessor :height_pixels
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@width_pixels = args[:width_pixels] if args.key?(:width_pixels)
@offset_x_pixels = args[:offset_x_pixels] if args.key?(:offset_x_pixels)
@anchor_cell = args[:anchor_cell] if args.key?(:anchor_cell)
@offset_y_pixels = args[:offset_y_pixels] if args.key?(:offset_y_pixels)
@height_pixels = args[:height_pixels] if args.key?(:height_pixels)
end
end
# Updates all cells in the range to the values in the given Cell object.
# Only the fields listed in the fields field are updated; others are
# unchanged.
# If writing a cell with a formula, the formula's ranges will automatically
# increment for each field in the range.
# For example, if writing a cell with formula `=A1` into range B2:C4,
# B2 would be `=A1`, B3 would be `=A2`, B4 would be `=A3`,
# C2 would be `=B1`, C3 would be `=B2`, C4 would be `=B3`.
# To keep the formula's ranges static, use the `$` indicator.
# For example, use the formula `=$A$1` to prevent both the row and the
# column from incrementing.
class RepeatCellRequest
include Google::Apis::Core::Hashable
# A range on a sheet.
# All indexes are zero-based.
# Indexes are half open, e.g the start index is inclusive
# and the end index is exclusive -- [start_index, end_index).
# Missing indexes indicate the range is unbounded on that side.
# For example, if `"Sheet1"` is sheet ID 0, then:
# `Sheet1!A1:A1 == sheet_id: 0,
# start_row_index: 0, end_row_index: 1,
# start_column_index: 0, end_column_index: 1`
# `Sheet1!A3:B4 == sheet_id: 0,
# start_row_index: 2, end_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A:B == sheet_id: 0,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A5:B == sheet_id: 0,
# start_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1 == sheet_id:0`
# The start index must always be less than or equal to the end index.
# If the start index equals the end index, then the range is empty.
# Empty ranges are typically not meaningful and are usually rendered in the
# UI as `#REF!`.
# Corresponds to the JSON property `range`
# @return [Google::Apis::SheetsV4::GridRange]
attr_accessor :range
# The fields that should be updated. At least one field must be specified.
# The root `cell` is implied and should not be specified.
# A single `"*"` can be used as short-hand for listing every field.
# Corresponds to the JSON property `fields`
# @return [String]
attr_accessor :fields
# Data about a specific cell.
# Corresponds to the JSON property `cell`
# @return [Google::Apis::SheetsV4::CellData]
attr_accessor :cell
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@range = args[:range] if args.key?(:range)
@fields = args[:fields] if args.key?(:fields)
@cell = args[:cell] if args.key?(:cell)
end
end
# The result of adding a chart to a spreadsheet.
class AddChartResponse
include Google::Apis::Core::Hashable
# A chart embedded in a sheet.
# Corresponds to the JSON property `chart`
# @return [Google::Apis::SheetsV4::EmbeddedChart]
attr_accessor :chart
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@chart = args[:chart] if args.key?(:chart)
end
end
# Inserts rows or columns in a sheet at a particular index.
class InsertDimensionRequest
include Google::Apis::Core::Hashable
# Whether dimension properties should be extended from the dimensions
# before or after the newly inserted dimensions.
# True to inherit from the dimensions before (in which case the start
# index must be greater than 0), and false to inherit from the dimensions
# after.
# For example, if row index 0 has red background and row index 1
# has a green background, then inserting 2 rows at index 1 can inherit
# either the green or red background. If `inheritFromBefore` is true,
# the two new rows will be red (because the row before the insertion point
# was red), whereas if `inheritFromBefore` is false, the two new rows will
# be green (because the row after the insertion point was green).
# Corresponds to the JSON property `inheritFromBefore`
# @return [Boolean]
attr_accessor :inherit_from_before
alias_method :inherit_from_before?, :inherit_from_before
# A range along a single dimension on a sheet.
# All indexes are zero-based.
# Indexes are half open: the start index is inclusive
# and the end index is exclusive.
# Missing indexes indicate the range is unbounded on that side.
# Corresponds to the JSON property `range`
# @return [Google::Apis::SheetsV4::DimensionRange]
attr_accessor :range
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@inherit_from_before = args[:inherit_from_before] if args.key?(:inherit_from_before)
@range = args[:range] if args.key?(:range)
end
end
# Updates properties of a spreadsheet.
class UpdateSpreadsheetPropertiesRequest
include Google::Apis::Core::Hashable
# The fields that should be updated. At least one field must be specified.
# The root 'properties' is implied and should not be specified.
# A single `"*"` can be used as short-hand for listing every field.
# Corresponds to the JSON property `fields`
# @return [String]
attr_accessor :fields
# Properties of a spreadsheet.
# Corresponds to the JSON property `properties`
# @return [Google::Apis::SheetsV4::SpreadsheetProperties]
attr_accessor :properties
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@fields = args[:fields] if args.key?(:fields)
@properties = args[:properties] if args.key?(:properties)
end
end
# The request for updating more than one range of values in a spreadsheet.
class BatchUpdateValuesRequest
include Google::Apis::Core::Hashable
# How the input data should be interpreted.
# Corresponds to the JSON property `valueInputOption`
# @return [String]
attr_accessor :value_input_option
# The new values to apply to the spreadsheet.
# Corresponds to the JSON property `data`
# @return [Array<Google::Apis::SheetsV4::ValueRange>]
attr_accessor :data
# Determines how dates, times, and durations in the response should be
# rendered. This is ignored if response_value_render_option is
# FORMATTED_VALUE.
# The default dateTime render option is [DateTimeRenderOption.SERIAL_NUMBER].
# Corresponds to the JSON property `responseDateTimeRenderOption`
# @return [String]
attr_accessor :response_date_time_render_option
# Determines how values in the response should be rendered.
# The default render option is ValueRenderOption.FORMATTED_VALUE.
# Corresponds to the JSON property `responseValueRenderOption`
# @return [String]
attr_accessor :response_value_render_option
# Determines if the update response should include the values
# of the cells that were updated. By default, responses
# do not include the updated values. The `updatedData` field within
# each of the BatchUpdateValuesResponse.responses will contain
# the updated values. If the range to write was larger than than the range
# actually written, the response will include all values in the requested
# range (excluding trailing empty rows and columns).
# Corresponds to the JSON property `includeValuesInResponse`
# @return [Boolean]
attr_accessor :include_values_in_response
alias_method :include_values_in_response?, :include_values_in_response
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@value_input_option = args[:value_input_option] if args.key?(:value_input_option)
@data = args[:data] if args.key?(:data)
@response_date_time_render_option = args[:response_date_time_render_option] if args.key?(:response_date_time_render_option)
@response_value_render_option = args[:response_value_render_option] if args.key?(:response_value_render_option)
@include_values_in_response = args[:include_values_in_response] if args.key?(:include_values_in_response)
end
end
# A protected range.
class ProtectedRange
include Google::Apis::Core::Hashable
# True if the user who requested this protected range can edit the
# protected area.
# This field is read-only.
# Corresponds to the JSON property `requestingUserCanEdit`
# @return [Boolean]
attr_accessor :requesting_user_can_edit
alias_method :requesting_user_can_edit?, :requesting_user_can_edit
# A range on a sheet.
# All indexes are zero-based.
# Indexes are half open, e.g the start index is inclusive
# and the end index is exclusive -- [start_index, end_index).
# Missing indexes indicate the range is unbounded on that side.
# For example, if `"Sheet1"` is sheet ID 0, then:
# `Sheet1!A1:A1 == sheet_id: 0,
# start_row_index: 0, end_row_index: 1,
# start_column_index: 0, end_column_index: 1`
# `Sheet1!A3:B4 == sheet_id: 0,
# start_row_index: 2, end_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A:B == sheet_id: 0,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A5:B == sheet_id: 0,
# start_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1 == sheet_id:0`
# The start index must always be less than or equal to the end index.
# If the start index equals the end index, then the range is empty.
# Empty ranges are typically not meaningful and are usually rendered in the
# UI as `#REF!`.
# Corresponds to the JSON property `range`
# @return [Google::Apis::SheetsV4::GridRange]
attr_accessor :range
# The editors of a protected range.
# Corresponds to the JSON property `editors`
# @return [Google::Apis::SheetsV4::Editors]
attr_accessor :editors
# The description of this protected range.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# The list of unprotected ranges within a protected sheet.
# Unprotected ranges are only supported on protected sheets.
# Corresponds to the JSON property `unprotectedRanges`
# @return [Array<Google::Apis::SheetsV4::GridRange>]
attr_accessor :unprotected_ranges
# The named range this protected range is backed by, if any.
# When writing, only one of range or named_range_id
# may be set.
# Corresponds to the JSON property `namedRangeId`
# @return [String]
attr_accessor :named_range_id
# The ID of the protected range.
# This field is read-only.
# Corresponds to the JSON property `protectedRangeId`
# @return [Fixnum]
attr_accessor :protected_range_id
# True if this protected range will show a warning when editing.
# Warning-based protection means that every user can edit data in the
# protected range, except editing will prompt a warning asking the user
# to confirm the edit.
# When writing: if this field is true, then editors is ignored.
# Additionally, if this field is changed from true to false and the
# `editors` field is not set (nor included in the field mask), then
# the editors will be set to all the editors in the document.
# Corresponds to the JSON property `warningOnly`
# @return [Boolean]
attr_accessor :warning_only
alias_method :warning_only?, :warning_only
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@requesting_user_can_edit = args[:requesting_user_can_edit] if args.key?(:requesting_user_can_edit)
@range = args[:range] if args.key?(:range)
@editors = args[:editors] if args.key?(:editors)
@description = args[:description] if args.key?(:description)
@unprotected_ranges = args[:unprotected_ranges] if args.key?(:unprotected_ranges)
@named_range_id = args[:named_range_id] if args.key?(:named_range_id)
@protected_range_id = args[:protected_range_id] if args.key?(:protected_range_id)
@warning_only = args[:warning_only] if args.key?(:warning_only)
end
end
# Properties about a dimension.
class DimensionProperties
include Google::Apis::Core::Hashable
# The height (if a row) or width (if a column) of the dimension in pixels.
# Corresponds to the JSON property `pixelSize`
# @return [Fixnum]
attr_accessor :pixel_size
# True if this dimension is being filtered.
# This field is read-only.
# Corresponds to the JSON property `hiddenByFilter`
# @return [Boolean]
attr_accessor :hidden_by_filter
alias_method :hidden_by_filter?, :hidden_by_filter
# True if this dimension is explicitly hidden.
# Corresponds to the JSON property `hiddenByUser`
# @return [Boolean]
attr_accessor :hidden_by_user
alias_method :hidden_by_user?, :hidden_by_user
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@pixel_size = args[:pixel_size] if args.key?(:pixel_size)
@hidden_by_filter = args[:hidden_by_filter] if args.key?(:hidden_by_filter)
@hidden_by_user = args[:hidden_by_user] if args.key?(:hidden_by_user)
end
end
# A range along a single dimension on a sheet.
# All indexes are zero-based.
# Indexes are half open: the start index is inclusive
# and the end index is exclusive.
# Missing indexes indicate the range is unbounded on that side.
class DimensionRange
include Google::Apis::Core::Hashable
# The sheet this span is on.
# Corresponds to the JSON property `sheetId`
# @return [Fixnum]
attr_accessor :sheet_id
# The dimension of the span.
# Corresponds to the JSON property `dimension`
# @return [String]
attr_accessor :dimension
# The start (inclusive) of the span, or not set if unbounded.
# Corresponds to the JSON property `startIndex`
# @return [Fixnum]
attr_accessor :start_index
# The end (exclusive) of the span, or not set if unbounded.
# Corresponds to the JSON property `endIndex`
# @return [Fixnum]
attr_accessor :end_index
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@sheet_id = args[:sheet_id] if args.key?(:sheet_id)
@dimension = args[:dimension] if args.key?(:dimension)
@start_index = args[:start_index] if args.key?(:start_index)
@end_index = args[:end_index] if args.key?(:end_index)
end
end
# A named range.
class NamedRange
include Google::Apis::Core::Hashable
# The name of the named range.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# The ID of the named range.
# Corresponds to the JSON property `namedRangeId`
# @return [String]
attr_accessor :named_range_id
# A range on a sheet.
# All indexes are zero-based.
# Indexes are half open, e.g the start index is inclusive
# and the end index is exclusive -- [start_index, end_index).
# Missing indexes indicate the range is unbounded on that side.
# For example, if `"Sheet1"` is sheet ID 0, then:
# `Sheet1!A1:A1 == sheet_id: 0,
# start_row_index: 0, end_row_index: 1,
# start_column_index: 0, end_column_index: 1`
# `Sheet1!A3:B4 == sheet_id: 0,
# start_row_index: 2, end_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A:B == sheet_id: 0,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A5:B == sheet_id: 0,
# start_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1 == sheet_id:0`
# The start index must always be less than or equal to the end index.
# If the start index equals the end index, then the range is empty.
# Empty ranges are typically not meaningful and are usually rendered in the
# UI as `#REF!`.
# Corresponds to the JSON property `range`
# @return [Google::Apis::SheetsV4::GridRange]
attr_accessor :range
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@name = args[:name] if args.key?(:name)
@named_range_id = args[:named_range_id] if args.key?(:named_range_id)
@range = args[:range] if args.key?(:range)
end
end
# Moves data from the source to the destination.
class CutPasteRequest
include Google::Apis::Core::Hashable
# A coordinate in a sheet.
# All indexes are zero-based.
# Corresponds to the JSON property `destination`
# @return [Google::Apis::SheetsV4::GridCoordinate]
attr_accessor :destination
# A range on a sheet.
# All indexes are zero-based.
# Indexes are half open, e.g the start index is inclusive
# and the end index is exclusive -- [start_index, end_index).
# Missing indexes indicate the range is unbounded on that side.
# For example, if `"Sheet1"` is sheet ID 0, then:
# `Sheet1!A1:A1 == sheet_id: 0,
# start_row_index: 0, end_row_index: 1,
# start_column_index: 0, end_column_index: 1`
# `Sheet1!A3:B4 == sheet_id: 0,
# start_row_index: 2, end_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A:B == sheet_id: 0,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A5:B == sheet_id: 0,
# start_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1 == sheet_id:0`
# The start index must always be less than or equal to the end index.
# If the start index equals the end index, then the range is empty.
# Empty ranges are typically not meaningful and are usually rendered in the
# UI as `#REF!`.
# Corresponds to the JSON property `source`
# @return [Google::Apis::SheetsV4::GridRange]
attr_accessor :source
# What kind of data to paste. All the source data will be cut, regardless
# of what is pasted.
# Corresponds to the JSON property `pasteType`
# @return [String]
attr_accessor :paste_type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@destination = args[:destination] if args.key?(:destination)
@source = args[:source] if args.key?(:source)
@paste_type = args[:paste_type] if args.key?(:paste_type)
end
end
# A single series of data in a chart.
# For example, if charting stock prices over time, multiple series may exist,
# one for the "Open Price", "High Price", "Low Price" and "Close Price".
class BasicChartSeries
include Google::Apis::Core::Hashable
# The data included in a domain or series.
# Corresponds to the JSON property `series`
# @return [Google::Apis::SheetsV4::ChartData]
attr_accessor :series
# The type of this series. Valid only if the
# chartType is
# COMBO.
# Different types will change the way the series is visualized.
# Only LINE, AREA,
# and COLUMN are supported.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
# The minor axis that will specify the range of values for this series.
# For example, if charting stocks over time, the "Volume" series
# may want to be pinned to the right with the prices pinned to the left,
# because the scale of trading volume is different than the scale of
# prices.
# It is an error to specify an axis that isn't a valid minor axis
# for the chart's type.
# Corresponds to the JSON property `targetAxis`
# @return [String]
attr_accessor :target_axis
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@series = args[:series] if args.key?(:series)
@type = args[:type] if args.key?(:type)
@target_axis = args[:target_axis] if args.key?(:target_axis)
end
end
# The borders of the cell.
class Borders
include Google::Apis::Core::Hashable
# A border along a cell.
# Corresponds to the JSON property `right`
# @return [Google::Apis::SheetsV4::Border]
attr_accessor :right
# A border along a cell.
# Corresponds to the JSON property `bottom`
# @return [Google::Apis::SheetsV4::Border]
attr_accessor :bottom
# A border along a cell.
# Corresponds to the JSON property `top`
# @return [Google::Apis::SheetsV4::Border]
attr_accessor :top
# A border along a cell.
# Corresponds to the JSON property `left`
# @return [Google::Apis::SheetsV4::Border]
attr_accessor :left
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@right = args[:right] if args.key?(:right)
@bottom = args[:bottom] if args.key?(:bottom)
@top = args[:top] if args.key?(:top)
@left = args[:left] if args.key?(:left)
end
end
# Automatically resizes one or more dimensions based on the contents
# of the cells in that dimension.
class AutoResizeDimensionsRequest
include Google::Apis::Core::Hashable
# A range along a single dimension on a sheet.
# All indexes are zero-based.
# Indexes are half open: the start index is inclusive
# and the end index is exclusive.
# Missing indexes indicate the range is unbounded on that side.
# Corresponds to the JSON property `dimensions`
# @return [Google::Apis::SheetsV4::DimensionRange]
attr_accessor :dimensions
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@dimensions = args[:dimensions] if args.key?(:dimensions)
end
end
# Updates the borders of a range.
# If a field is not set in the request, that means the border remains as-is.
# For example, with two subsequent UpdateBordersRequest:
# 1. range: A1:A5 `` top: RED, bottom: WHITE ``
# 2. range: A1:A5 `` left: BLUE ``
# That would result in A1:A5 having a borders of
# `` top: RED, bottom: WHITE, left: BLUE ``.
# If you want to clear a border, explicitly set the style to
# NONE.
class UpdateBordersRequest
include Google::Apis::Core::Hashable
# A border along a cell.
# Corresponds to the JSON property `bottom`
# @return [Google::Apis::SheetsV4::Border]
attr_accessor :bottom
# A border along a cell.
# Corresponds to the JSON property `innerVertical`
# @return [Google::Apis::SheetsV4::Border]
attr_accessor :inner_vertical
# A border along a cell.
# Corresponds to the JSON property `right`
# @return [Google::Apis::SheetsV4::Border]
attr_accessor :right
# A range on a sheet.
# All indexes are zero-based.
# Indexes are half open, e.g the start index is inclusive
# and the end index is exclusive -- [start_index, end_index).
# Missing indexes indicate the range is unbounded on that side.
# For example, if `"Sheet1"` is sheet ID 0, then:
# `Sheet1!A1:A1 == sheet_id: 0,
# start_row_index: 0, end_row_index: 1,
# start_column_index: 0, end_column_index: 1`
# `Sheet1!A3:B4 == sheet_id: 0,
# start_row_index: 2, end_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A:B == sheet_id: 0,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A5:B == sheet_id: 0,
# start_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1 == sheet_id:0`
# The start index must always be less than or equal to the end index.
# If the start index equals the end index, then the range is empty.
# Empty ranges are typically not meaningful and are usually rendered in the
# UI as `#REF!`.
# Corresponds to the JSON property `range`
# @return [Google::Apis::SheetsV4::GridRange]
attr_accessor :range
# A border along a cell.
# Corresponds to the JSON property `innerHorizontal`
# @return [Google::Apis::SheetsV4::Border]
attr_accessor :inner_horizontal
# A border along a cell.
# Corresponds to the JSON property `top`
# @return [Google::Apis::SheetsV4::Border]
attr_accessor :top
# A border along a cell.
# Corresponds to the JSON property `left`
# @return [Google::Apis::SheetsV4::Border]
attr_accessor :left
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bottom = args[:bottom] if args.key?(:bottom)
@inner_vertical = args[:inner_vertical] if args.key?(:inner_vertical)
@right = args[:right] if args.key?(:right)
@range = args[:range] if args.key?(:range)
@inner_horizontal = args[:inner_horizontal] if args.key?(:inner_horizontal)
@top = args[:top] if args.key?(:top)
@left = args[:left] if args.key?(:left)
end
end
# The format of a cell.
class CellFormat
include Google::Apis::Core::Hashable
# The vertical alignment of the value in the cell.
# Corresponds to the JSON property `verticalAlignment`
# @return [String]
attr_accessor :vertical_alignment
# The amount of padding around the cell, in pixels.
# When updating padding, every field must be specified.
# Corresponds to the JSON property `padding`
# @return [Google::Apis::SheetsV4::Padding]
attr_accessor :padding
# The borders of the cell.
# Corresponds to the JSON property `borders`
# @return [Google::Apis::SheetsV4::Borders]
attr_accessor :borders
# The direction of the text in the cell.
# Corresponds to the JSON property `textDirection`
# @return [String]
attr_accessor :text_direction
# The wrap strategy for the value in the cell.
# Corresponds to the JSON property `wrapStrategy`
# @return [String]
attr_accessor :wrap_strategy
# The number format of a cell.
# Corresponds to the JSON property `numberFormat`
# @return [Google::Apis::SheetsV4::NumberFormat]
attr_accessor :number_format
# The horizontal alignment of the value in the cell.
# Corresponds to the JSON property `horizontalAlignment`
# @return [String]
attr_accessor :horizontal_alignment
# How a hyperlink, if it exists, should be displayed in the cell.
# Corresponds to the JSON property `hyperlinkDisplayType`
# @return [String]
attr_accessor :hyperlink_display_type
# The format of a run of text in a cell.
# Absent values indicate that the field isn't specified.
# Corresponds to the JSON property `textFormat`
# @return [Google::Apis::SheetsV4::TextFormat]
attr_accessor :text_format
# Represents a color in the RGBA color space. This representation is designed
# for simplicity of conversion to/from color representations in various
# languages over compactness; for example, the fields of this representation
# can be trivially provided to the constructor of "java.awt.Color" in Java; it
# can also be trivially provided to UIColor's "+colorWithRed:green:blue:alpha"
# method in iOS; and, with just a little work, it can be easily formatted into
# a CSS "rgba()" string in JavaScript, as well. Here are some examples:
# Example (Java):
# import com.google.type.Color;
# // ...
# public static java.awt.Color fromProto(Color protocolor) `
# float alpha = protocolor.hasAlpha()
# ? protocolor.getAlpha().getValue()
# : 1.0;
# return new java.awt.Color(
# protocolor.getRed(),
# protocolor.getGreen(),
# protocolor.getBlue(),
# alpha);
# `
# public static Color toProto(java.awt.Color color) `
# float red = (float) color.getRed();
# float green = (float) color.getGreen();
# float blue = (float) color.getBlue();
# float denominator = 255.0;
# Color.Builder resultBuilder =
# Color
# .newBuilder()
# .setRed(red / denominator)
# .setGreen(green / denominator)
# .setBlue(blue / denominator);
# int alpha = color.getAlpha();
# if (alpha != 255) `
# result.setAlpha(
# FloatValue
# .newBuilder()
# .setValue(((float) alpha) / denominator)
# .build());
# `
# return resultBuilder.build();
# `
# // ...
# Example (iOS / Obj-C):
# // ...
# static UIColor* fromProto(Color* protocolor) `
# float red = [protocolor red];
# float green = [protocolor green];
# float blue = [protocolor blue];
# FloatValue* alpha_wrapper = [protocolor alpha];
# float alpha = 1.0;
# if (alpha_wrapper != nil) `
# alpha = [alpha_wrapper value];
# `
# return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
# `
# static Color* toProto(UIColor* color) `
# CGFloat red, green, blue, alpha;
# if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) `
# return nil;
# `
# Color* result = [Color alloc] init];
# [result setRed:red];
# [result setGreen:green];
# [result setBlue:blue];
# if (alpha <= 0.9999) `
# [result setAlpha:floatWrapperWithValue(alpha)];
# `
# [result autorelease];
# return result;
# `
# // ...
# Example (JavaScript):
# // ...
# var protoToCssColor = function(rgb_color) `
# var redFrac = rgb_color.red || 0.0;
# var greenFrac = rgb_color.green || 0.0;
# var blueFrac = rgb_color.blue || 0.0;
# var red = Math.floor(redFrac * 255);
# var green = Math.floor(greenFrac * 255);
# var blue = Math.floor(blueFrac * 255);
# if (!('alpha' in rgb_color)) `
# return rgbToCssColor_(red, green, blue);
# `
# var alphaFrac = rgb_color.alpha.value || 0.0;
# var rgbParams = [red, green, blue].join(',');
# return ['rgba(', rgbParams, ',', alphaFrac, ')'].join('');
# `;
# var rgbToCssColor_ = function(red, green, blue) `
# var rgbNumber = new Number((red << 16) | (green << 8) | blue);
# var hexString = rgbNumber.toString(16);
# var missingZeros = 6 - hexString.length;
# var resultBuilder = ['#'];
# for (var i = 0; i < missingZeros; i++) `
# resultBuilder.push('0');
# `
# resultBuilder.push(hexString);
# return resultBuilder.join('');
# `;
# // ...
# Corresponds to the JSON property `backgroundColor`
# @return [Google::Apis::SheetsV4::Color]
attr_accessor :background_color
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@vertical_alignment = args[:vertical_alignment] if args.key?(:vertical_alignment)
@padding = args[:padding] if args.key?(:padding)
@borders = args[:borders] if args.key?(:borders)
@text_direction = args[:text_direction] if args.key?(:text_direction)
@wrap_strategy = args[:wrap_strategy] if args.key?(:wrap_strategy)
@number_format = args[:number_format] if args.key?(:number_format)
@horizontal_alignment = args[:horizontal_alignment] if args.key?(:horizontal_alignment)
@hyperlink_display_type = args[:hyperlink_display_type] if args.key?(:hyperlink_display_type)
@text_format = args[:text_format] if args.key?(:text_format)
@background_color = args[:background_color] if args.key?(:background_color)
end
end
# The response when clearing a range of values in a spreadsheet.
class ClearValuesResponse
include Google::Apis::Core::Hashable
# The spreadsheet the updates were applied to.
# Corresponds to the JSON property `spreadsheetId`
# @return [String]
attr_accessor :spreadsheet_id
# The range (in A1 notation) that was cleared.
# (If the request was for an unbounded range or a ranger larger
# than the bounds of the sheet, this will be the actual range
# that was cleared, bounded to the sheet's limits.)
# Corresponds to the JSON property `clearedRange`
# @return [String]
attr_accessor :cleared_range
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@spreadsheet_id = args[:spreadsheet_id] if args.key?(:spreadsheet_id)
@cleared_range = args[:cleared_range] if args.key?(:cleared_range)
end
end
# Deletes a conditional format rule at the given index.
# All subsequent rules' indexes are decremented.
class DeleteConditionalFormatRuleRequest
include Google::Apis::Core::Hashable
# The zero-based index of the rule to be deleted.
# Corresponds to the JSON property `index`
# @return [Fixnum]
attr_accessor :index
# The sheet the rule is being deleted from.
# Corresponds to the JSON property `sheetId`
# @return [Fixnum]
attr_accessor :sheet_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@index = args[:index] if args.key?(:index)
@sheet_id = args[:sheet_id] if args.key?(:sheet_id)
end
end
# Removes the named range with the given ID from the spreadsheet.
class DeleteNamedRangeRequest
include Google::Apis::Core::Hashable
# The ID of the named range to delete.
# Corresponds to the JSON property `namedRangeId`
# @return [String]
attr_accessor :named_range_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@named_range_id = args[:named_range_id] if args.key?(:named_range_id)
end
end
# The result of adding a banded range.
class AddBandingResponse
include Google::Apis::Core::Hashable
# A banded (alternating colors) range in a sheet.
# Corresponds to the JSON property `bandedRange`
# @return [Google::Apis::SheetsV4::BandedRange]
attr_accessor :banded_range
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@banded_range = args[:banded_range] if args.key?(:banded_range)
end
end
# The data included in a domain or series.
class ChartData
include Google::Apis::Core::Hashable
# Source ranges for a chart.
# Corresponds to the JSON property `sourceRange`
# @return [Google::Apis::SheetsV4::ChartSourceRange]
attr_accessor :source_range
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@source_range = args[:source_range] if args.key?(:source_range)
end
end
# The response when retrieving more than one range of values in a spreadsheet.
class BatchGetValuesResponse
include Google::Apis::Core::Hashable
# The ID of the spreadsheet the data was retrieved from.
# Corresponds to the JSON property `spreadsheetId`
# @return [String]
attr_accessor :spreadsheet_id
# The requested values. The order of the ValueRanges is the same as the
# order of the requested ranges.
# Corresponds to the JSON property `valueRanges`
# @return [Array<Google::Apis::SheetsV4::ValueRange>]
attr_accessor :value_ranges
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@spreadsheet_id = args[:spreadsheet_id] if args.key?(:spreadsheet_id)
@value_ranges = args[:value_ranges] if args.key?(:value_ranges)
end
end
# Updates properties of the supplied banded range.
class UpdateBandingRequest
include Google::Apis::Core::Hashable
# The fields that should be updated. At least one field must be specified.
# The root `bandedRange` is implied and should not be specified.
# A single `"*"` can be used as short-hand for listing every field.
# Corresponds to the JSON property `fields`
# @return [String]
attr_accessor :fields
# A banded (alternating colors) range in a sheet.
# Corresponds to the JSON property `bandedRange`
# @return [Google::Apis::SheetsV4::BandedRange]
attr_accessor :banded_range
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@fields = args[:fields] if args.key?(:fields)
@banded_range = args[:banded_range] if args.key?(:banded_range)
end
end
# Represents a color in the RGBA color space. This representation is designed
# for simplicity of conversion to/from color representations in various
# languages over compactness; for example, the fields of this representation
# can be trivially provided to the constructor of "java.awt.Color" in Java; it
# can also be trivially provided to UIColor's "+colorWithRed:green:blue:alpha"
# method in iOS; and, with just a little work, it can be easily formatted into
# a CSS "rgba()" string in JavaScript, as well. Here are some examples:
# Example (Java):
# import com.google.type.Color;
# // ...
# public static java.awt.Color fromProto(Color protocolor) `
# float alpha = protocolor.hasAlpha()
# ? protocolor.getAlpha().getValue()
# : 1.0;
# return new java.awt.Color(
# protocolor.getRed(),
# protocolor.getGreen(),
# protocolor.getBlue(),
# alpha);
# `
# public static Color toProto(java.awt.Color color) `
# float red = (float) color.getRed();
# float green = (float) color.getGreen();
# float blue = (float) color.getBlue();
# float denominator = 255.0;
# Color.Builder resultBuilder =
# Color
# .newBuilder()
# .setRed(red / denominator)
# .setGreen(green / denominator)
# .setBlue(blue / denominator);
# int alpha = color.getAlpha();
# if (alpha != 255) `
# result.setAlpha(
# FloatValue
# .newBuilder()
# .setValue(((float) alpha) / denominator)
# .build());
# `
# return resultBuilder.build();
# `
# // ...
# Example (iOS / Obj-C):
# // ...
# static UIColor* fromProto(Color* protocolor) `
# float red = [protocolor red];
# float green = [protocolor green];
# float blue = [protocolor blue];
# FloatValue* alpha_wrapper = [protocolor alpha];
# float alpha = 1.0;
# if (alpha_wrapper != nil) `
# alpha = [alpha_wrapper value];
# `
# return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
# `
# static Color* toProto(UIColor* color) `
# CGFloat red, green, blue, alpha;
# if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) `
# return nil;
# `
# Color* result = [Color alloc] init];
# [result setRed:red];
# [result setGreen:green];
# [result setBlue:blue];
# if (alpha <= 0.9999) `
# [result setAlpha:floatWrapperWithValue(alpha)];
# `
# [result autorelease];
# return result;
# `
# // ...
# Example (JavaScript):
# // ...
# var protoToCssColor = function(rgb_color) `
# var redFrac = rgb_color.red || 0.0;
# var greenFrac = rgb_color.green || 0.0;
# var blueFrac = rgb_color.blue || 0.0;
# var red = Math.floor(redFrac * 255);
# var green = Math.floor(greenFrac * 255);
# var blue = Math.floor(blueFrac * 255);
# if (!('alpha' in rgb_color)) `
# return rgbToCssColor_(red, green, blue);
# `
# var alphaFrac = rgb_color.alpha.value || 0.0;
# var rgbParams = [red, green, blue].join(',');
# return ['rgba(', rgbParams, ',', alphaFrac, ')'].join('');
# `;
# var rgbToCssColor_ = function(red, green, blue) `
# var rgbNumber = new Number((red << 16) | (green << 8) | blue);
# var hexString = rgbNumber.toString(16);
# var missingZeros = 6 - hexString.length;
# var resultBuilder = ['#'];
# for (var i = 0; i < missingZeros; i++) `
# resultBuilder.push('0');
# `
# resultBuilder.push(hexString);
# return resultBuilder.join('');
# `;
# // ...
class Color
include Google::Apis::Core::Hashable
# The amount of red in the color as a value in the interval [0, 1].
# Corresponds to the JSON property `red`
# @return [Float]
attr_accessor :red
# The amount of green in the color as a value in the interval [0, 1].
# Corresponds to the JSON property `green`
# @return [Float]
attr_accessor :green
# The amount of blue in the color as a value in the interval [0, 1].
# Corresponds to the JSON property `blue`
# @return [Float]
attr_accessor :blue
# The fraction of this color that should be applied to the pixel. That is,
# the final pixel color is defined by the equation:
# pixel color = alpha * (this color) + (1.0 - alpha) * (background color)
# This means that a value of 1.0 corresponds to a solid color, whereas
# a value of 0.0 corresponds to a completely transparent color. This
# uses a wrapper message rather than a simple float scalar so that it is
# possible to distinguish between a default value and the value being unset.
# If omitted, this color object is to be rendered as a solid color
# (as if the alpha value had been explicitly given with a value of 1.0).
# Corresponds to the JSON property `alpha`
# @return [Float]
attr_accessor :alpha
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@red = args[:red] if args.key?(:red)
@green = args[:green] if args.key?(:green)
@blue = args[:blue] if args.key?(:blue)
@alpha = args[:alpha] if args.key?(:alpha)
end
end
# A single grouping (either row or column) in a pivot table.
class PivotGroup
include Google::Apis::Core::Hashable
# The order the values in this group should be sorted.
# Corresponds to the JSON property `sortOrder`
# @return [String]
attr_accessor :sort_order
# Information about which values in a pivot group should be used for sorting.
# Corresponds to the JSON property `valueBucket`
# @return [Google::Apis::SheetsV4::PivotGroupSortValueBucket]
attr_accessor :value_bucket
# The column offset of the source range that this grouping is based on.
# For example, if the source was `C10:E15`, a `sourceColumnOffset` of `0`
# means this group refers to column `C`, whereas the offset `1` would refer
# to column `D`.
# Corresponds to the JSON property `sourceColumnOffset`
# @return [Fixnum]
attr_accessor :source_column_offset
# True if the pivot table should include the totals for this grouping.
# Corresponds to the JSON property `showTotals`
# @return [Boolean]
attr_accessor :show_totals
alias_method :show_totals?, :show_totals
# Metadata about values in the grouping.
# Corresponds to the JSON property `valueMetadata`
# @return [Array<Google::Apis::SheetsV4::PivotGroupValueMetadata>]
attr_accessor :value_metadata
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@sort_order = args[:sort_order] if args.key?(:sort_order)
@value_bucket = args[:value_bucket] if args.key?(:value_bucket)
@source_column_offset = args[:source_column_offset] if args.key?(:source_column_offset)
@show_totals = args[:show_totals] if args.key?(:show_totals)
@value_metadata = args[:value_metadata] if args.key?(:value_metadata)
end
end
# A pivot table.
class PivotTable
include Google::Apis::Core::Hashable
# Each row grouping in the pivot table.
# Corresponds to the JSON property `rows`
# @return [Array<Google::Apis::SheetsV4::PivotGroup>]
attr_accessor :rows
# Whether values should be listed horizontally (as columns)
# or vertically (as rows).
# Corresponds to the JSON property `valueLayout`
# @return [String]
attr_accessor :value_layout
# Each column grouping in the pivot table.
# Corresponds to the JSON property `columns`
# @return [Array<Google::Apis::SheetsV4::PivotGroup>]
attr_accessor :columns
# A list of values to include in the pivot table.
# Corresponds to the JSON property `values`
# @return [Array<Google::Apis::SheetsV4::PivotValue>]
attr_accessor :values
# A range on a sheet.
# All indexes are zero-based.
# Indexes are half open, e.g the start index is inclusive
# and the end index is exclusive -- [start_index, end_index).
# Missing indexes indicate the range is unbounded on that side.
# For example, if `"Sheet1"` is sheet ID 0, then:
# `Sheet1!A1:A1 == sheet_id: 0,
# start_row_index: 0, end_row_index: 1,
# start_column_index: 0, end_column_index: 1`
# `Sheet1!A3:B4 == sheet_id: 0,
# start_row_index: 2, end_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A:B == sheet_id: 0,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A5:B == sheet_id: 0,
# start_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1 == sheet_id:0`
# The start index must always be less than or equal to the end index.
# If the start index equals the end index, then the range is empty.
# Empty ranges are typically not meaningful and are usually rendered in the
# UI as `#REF!`.
# Corresponds to the JSON property `source`
# @return [Google::Apis::SheetsV4::GridRange]
attr_accessor :source
# An optional mapping of filters per source column offset.
# The filters will be applied before aggregating data into the pivot table.
# The map's key is the column offset of the source range that you want to
# filter, and the value is the criteria for that column.
# For example, if the source was `C10:E15`, a key of `0` will have the filter
# for column `C`, whereas the key `1` is for column `D`.
# Corresponds to the JSON property `criteria`
# @return [Hash<String,Google::Apis::SheetsV4::PivotFilterCriteria>]
attr_accessor :criteria
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@rows = args[:rows] if args.key?(:rows)
@value_layout = args[:value_layout] if args.key?(:value_layout)
@columns = args[:columns] if args.key?(:columns)
@values = args[:values] if args.key?(:values)
@source = args[:source] if args.key?(:source)
@criteria = args[:criteria] if args.key?(:criteria)
end
end
# Source ranges for a chart.
class ChartSourceRange
include Google::Apis::Core::Hashable
# The ranges of data for a series or domain.
# Exactly one dimension must have a length of 1,
# and all sources in the list must have the same dimension
# with length 1.
# The domain (if it exists) & all series must have the same number
# of source ranges. If using more than one source range, then the source
# range at a given offset must be contiguous across the domain and series.
# For example, these are valid configurations:
# domain sources: A1:A5
# series1 sources: B1:B5
# series2 sources: D6:D10
# domain sources: A1:A5, C10:C12
# series1 sources: B1:B5, D10:D12
# series2 sources: C1:C5, E10:E12
# Corresponds to the JSON property `sources`
# @return [Array<Google::Apis::SheetsV4::GridRange>]
attr_accessor :sources
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@sources = args[:sources] if args.key?(:sources)
end
end
# Adds new cells after the last row with data in a sheet,
# inserting new rows into the sheet if necessary.
class AppendCellsRequest
include Google::Apis::Core::Hashable
# The data to append.
# Corresponds to the JSON property `rows`
# @return [Array<Google::Apis::SheetsV4::RowData>]
attr_accessor :rows
# The fields of CellData that should be updated.
# At least one field must be specified.
# The root is the CellData; 'row.values.' should not be specified.
# A single `"*"` can be used as short-hand for listing every field.
# Corresponds to the JSON property `fields`
# @return [String]
attr_accessor :fields
# The sheet ID to append the data to.
# Corresponds to the JSON property `sheetId`
# @return [Fixnum]
attr_accessor :sheet_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@rows = args[:rows] if args.key?(:rows)
@fields = args[:fields] if args.key?(:fields)
@sheet_id = args[:sheet_id] if args.key?(:sheet_id)
end
end
# Data within a range of the spreadsheet.
class ValueRange
include Google::Apis::Core::Hashable
# The major dimension of the values.
# For output, if the spreadsheet data is: `A1=1,B1=2,A2=3,B2=4`,
# then requesting `range=A1:B2,majorDimension=ROWS` will return
# `[[1,2],[3,4]]`,
# whereas requesting `range=A1:B2,majorDimension=COLUMNS` will return
# `[[1,3],[2,4]]`.
# For input, with `range=A1:B2,majorDimension=ROWS` then `[[1,2],[3,4]]`
# will set `A1=1,B1=2,A2=3,B2=4`. With `range=A1:B2,majorDimension=COLUMNS`
# then `[[1,2],[3,4]]` will set `A1=1,B1=3,A2=2,B2=4`.
# When writing, if this field is not set, it defaults to ROWS.
# Corresponds to the JSON property `majorDimension`
# @return [String]
attr_accessor :major_dimension
# The data that was read or to be written. This is an array of arrays,
# the outer array representing all the data and each inner array
# representing a major dimension. Each item in the inner array
# corresponds with one cell.
# For output, empty trailing rows and columns will not be included.
# For input, supported value types are: bool, string, and double.
# Null values will be skipped.
# To set a cell to an empty value, set the string value to an empty string.
# Corresponds to the JSON property `values`
# @return [Array<Array<Object>>]
attr_accessor :values
# The range the values cover, in A1 notation.
# For output, this range indicates the entire requested range,
# even though the values will exclude trailing rows and columns.
# When appending values, this field represents the range to search for a
# table, after which values will be appended.
# Corresponds to the JSON property `range`
# @return [String]
attr_accessor :range
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@major_dimension = args[:major_dimension] if args.key?(:major_dimension)
@values = args[:values] if args.key?(:values)
@range = args[:range] if args.key?(:range)
end
end
# Adds a new banded range to the spreadsheet.
class AddBandingRequest
include Google::Apis::Core::Hashable
# A banded (alternating colors) range in a sheet.
# Corresponds to the JSON property `bandedRange`
# @return [Google::Apis::SheetsV4::BandedRange]
attr_accessor :banded_range
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@banded_range = args[:banded_range] if args.key?(:banded_range)
end
end
# A single response from an update.
class Response
include Google::Apis::Core::Hashable
# The result of adding a filter view.
# Corresponds to the JSON property `addFilterView`
# @return [Google::Apis::SheetsV4::AddFilterViewResponse]
attr_accessor :add_filter_view
# The result of adding a banded range.
# Corresponds to the JSON property `addBanding`
# @return [Google::Apis::SheetsV4::AddBandingResponse]
attr_accessor :add_banding
# The result of adding a new protected range.
# Corresponds to the JSON property `addProtectedRange`
# @return [Google::Apis::SheetsV4::AddProtectedRangeResponse]
attr_accessor :add_protected_range
# The result of duplicating a sheet.
# Corresponds to the JSON property `duplicateSheet`
# @return [Google::Apis::SheetsV4::DuplicateSheetResponse]
attr_accessor :duplicate_sheet
# The result of updating an embedded object's position.
# Corresponds to the JSON property `updateEmbeddedObjectPosition`
# @return [Google::Apis::SheetsV4::UpdateEmbeddedObjectPositionResponse]
attr_accessor :update_embedded_object_position
# The result of deleting a conditional format rule.
# Corresponds to the JSON property `deleteConditionalFormatRule`
# @return [Google::Apis::SheetsV4::DeleteConditionalFormatRuleResponse]
attr_accessor :delete_conditional_format_rule
# The result of a filter view being duplicated.
# Corresponds to the JSON property `duplicateFilterView`
# @return [Google::Apis::SheetsV4::DuplicateFilterViewResponse]
attr_accessor :duplicate_filter_view
# The result of adding a chart to a spreadsheet.
# Corresponds to the JSON property `addChart`
# @return [Google::Apis::SheetsV4::AddChartResponse]
attr_accessor :add_chart
# The result of the find/replace.
# Corresponds to the JSON property `findReplace`
# @return [Google::Apis::SheetsV4::FindReplaceResponse]
attr_accessor :find_replace
# The result of adding a sheet.
# Corresponds to the JSON property `addSheet`
# @return [Google::Apis::SheetsV4::AddSheetResponse]
attr_accessor :add_sheet
# The result of updating a conditional format rule.
# Corresponds to the JSON property `updateConditionalFormatRule`
# @return [Google::Apis::SheetsV4::UpdateConditionalFormatRuleResponse]
attr_accessor :update_conditional_format_rule
# The result of adding a named range.
# Corresponds to the JSON property `addNamedRange`
# @return [Google::Apis::SheetsV4::AddNamedRangeResponse]
attr_accessor :add_named_range
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@add_filter_view = args[:add_filter_view] if args.key?(:add_filter_view)
@add_banding = args[:add_banding] if args.key?(:add_banding)
@add_protected_range = args[:add_protected_range] if args.key?(:add_protected_range)
@duplicate_sheet = args[:duplicate_sheet] if args.key?(:duplicate_sheet)
@update_embedded_object_position = args[:update_embedded_object_position] if args.key?(:update_embedded_object_position)
@delete_conditional_format_rule = args[:delete_conditional_format_rule] if args.key?(:delete_conditional_format_rule)
@duplicate_filter_view = args[:duplicate_filter_view] if args.key?(:duplicate_filter_view)
@add_chart = args[:add_chart] if args.key?(:add_chart)
@find_replace = args[:find_replace] if args.key?(:find_replace)
@add_sheet = args[:add_sheet] if args.key?(:add_sheet)
@update_conditional_format_rule = args[:update_conditional_format_rule] if args.key?(:update_conditional_format_rule)
@add_named_range = args[:add_named_range] if args.key?(:add_named_range)
end
end
# Inserts cells into a range, shifting the existing cells over or down.
class InsertRangeRequest
include Google::Apis::Core::Hashable
# The dimension which will be shifted when inserting cells.
# If ROWS, existing cells will be shifted down.
# If COLUMNS, existing cells will be shifted right.
# Corresponds to the JSON property `shiftDimension`
# @return [String]
attr_accessor :shift_dimension
# A range on a sheet.
# All indexes are zero-based.
# Indexes are half open, e.g the start index is inclusive
# and the end index is exclusive -- [start_index, end_index).
# Missing indexes indicate the range is unbounded on that side.
# For example, if `"Sheet1"` is sheet ID 0, then:
# `Sheet1!A1:A1 == sheet_id: 0,
# start_row_index: 0, end_row_index: 1,
# start_column_index: 0, end_column_index: 1`
# `Sheet1!A3:B4 == sheet_id: 0,
# start_row_index: 2, end_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A:B == sheet_id: 0,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A5:B == sheet_id: 0,
# start_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1 == sheet_id:0`
# The start index must always be less than or equal to the end index.
# If the start index equals the end index, then the range is empty.
# Empty ranges are typically not meaningful and are usually rendered in the
# UI as `#REF!`.
# Corresponds to the JSON property `range`
# @return [Google::Apis::SheetsV4::GridRange]
attr_accessor :range
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@shift_dimension = args[:shift_dimension] if args.key?(:shift_dimension)
@range = args[:range] if args.key?(:range)
end
end
# A chart embedded in a sheet.
class EmbeddedChart
include Google::Apis::Core::Hashable
# The ID of the chart.
# Corresponds to the JSON property `chartId`
# @return [Fixnum]
attr_accessor :chart_id
# The position of an embedded object such as a chart.
# Corresponds to the JSON property `position`
# @return [Google::Apis::SheetsV4::EmbeddedObjectPosition]
attr_accessor :position
# The specifications of a chart.
# Corresponds to the JSON property `spec`
# @return [Google::Apis::SheetsV4::ChartSpec]
attr_accessor :spec
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@chart_id = args[:chart_id] if args.key?(:chart_id)
@position = args[:position] if args.key?(:position)
@spec = args[:spec] if args.key?(:spec)
end
end
# A run of a text format. The format of this run continues until the start
# index of the next run.
# When updating, all fields must be set.
class TextFormatRun
include Google::Apis::Core::Hashable
# The character index where this run starts.
# Corresponds to the JSON property `startIndex`
# @return [Fixnum]
attr_accessor :start_index
# The format of a run of text in a cell.
# Absent values indicate that the field isn't specified.
# Corresponds to the JSON property `format`
# @return [Google::Apis::SheetsV4::TextFormat]
attr_accessor :format
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@start_index = args[:start_index] if args.key?(:start_index)
@format = args[:format] if args.key?(:format)
end
end
# The result of adding a named range.
class AddNamedRangeResponse
include Google::Apis::Core::Hashable
# A named range.
# Corresponds to the JSON property `namedRange`
# @return [Google::Apis::SheetsV4::NamedRange]
attr_accessor :named_range
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@named_range = args[:named_range] if args.key?(:named_range)
end
end
# Data about each cell in a row.
class RowData
include Google::Apis::Core::Hashable
# The values in the row, one per column.
# Corresponds to the JSON property `values`
# @return [Array<Google::Apis::SheetsV4::CellData>]
attr_accessor :values
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@values = args[:values] if args.key?(:values)
end
end
# Data in the grid, as well as metadata about the dimensions.
class GridData
include Google::Apis::Core::Hashable
# The data in the grid, one entry per row,
# starting with the row in startRow.
# The values in RowData will correspond to columns starting
# at start_column.
# Corresponds to the JSON property `rowData`
# @return [Array<Google::Apis::SheetsV4::RowData>]
attr_accessor :row_data
# The first row this GridData refers to, zero-based.
# Corresponds to the JSON property `startRow`
# @return [Fixnum]
attr_accessor :start_row
# Metadata about the requested columns in the grid, starting with the column
# in start_column.
# Corresponds to the JSON property `columnMetadata`
# @return [Array<Google::Apis::SheetsV4::DimensionProperties>]
attr_accessor :column_metadata
# The first column this GridData refers to, zero-based.
# Corresponds to the JSON property `startColumn`
# @return [Fixnum]
attr_accessor :start_column
# Metadata about the requested rows in the grid, starting with the row
# in start_row.
# Corresponds to the JSON property `rowMetadata`
# @return [Array<Google::Apis::SheetsV4::DimensionProperties>]
attr_accessor :row_metadata
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@row_data = args[:row_data] if args.key?(:row_data)
@start_row = args[:start_row] if args.key?(:start_row)
@column_metadata = args[:column_metadata] if args.key?(:column_metadata)
@start_column = args[:start_column] if args.key?(:start_column)
@row_metadata = args[:row_metadata] if args.key?(:row_metadata)
end
end
# A border along a cell.
class Border
include Google::Apis::Core::Hashable
# Represents a color in the RGBA color space. This representation is designed
# for simplicity of conversion to/from color representations in various
# languages over compactness; for example, the fields of this representation
# can be trivially provided to the constructor of "java.awt.Color" in Java; it
# can also be trivially provided to UIColor's "+colorWithRed:green:blue:alpha"
# method in iOS; and, with just a little work, it can be easily formatted into
# a CSS "rgba()" string in JavaScript, as well. Here are some examples:
# Example (Java):
# import com.google.type.Color;
# // ...
# public static java.awt.Color fromProto(Color protocolor) `
# float alpha = protocolor.hasAlpha()
# ? protocolor.getAlpha().getValue()
# : 1.0;
# return new java.awt.Color(
# protocolor.getRed(),
# protocolor.getGreen(),
# protocolor.getBlue(),
# alpha);
# `
# public static Color toProto(java.awt.Color color) `
# float red = (float) color.getRed();
# float green = (float) color.getGreen();
# float blue = (float) color.getBlue();
# float denominator = 255.0;
# Color.Builder resultBuilder =
# Color
# .newBuilder()
# .setRed(red / denominator)
# .setGreen(green / denominator)
# .setBlue(blue / denominator);
# int alpha = color.getAlpha();
# if (alpha != 255) `
# result.setAlpha(
# FloatValue
# .newBuilder()
# .setValue(((float) alpha) / denominator)
# .build());
# `
# return resultBuilder.build();
# `
# // ...
# Example (iOS / Obj-C):
# // ...
# static UIColor* fromProto(Color* protocolor) `
# float red = [protocolor red];
# float green = [protocolor green];
# float blue = [protocolor blue];
# FloatValue* alpha_wrapper = [protocolor alpha];
# float alpha = 1.0;
# if (alpha_wrapper != nil) `
# alpha = [alpha_wrapper value];
# `
# return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
# `
# static Color* toProto(UIColor* color) `
# CGFloat red, green, blue, alpha;
# if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) `
# return nil;
# `
# Color* result = [Color alloc] init];
# [result setRed:red];
# [result setGreen:green];
# [result setBlue:blue];
# if (alpha <= 0.9999) `
# [result setAlpha:floatWrapperWithValue(alpha)];
# `
# [result autorelease];
# return result;
# `
# // ...
# Example (JavaScript):
# // ...
# var protoToCssColor = function(rgb_color) `
# var redFrac = rgb_color.red || 0.0;
# var greenFrac = rgb_color.green || 0.0;
# var blueFrac = rgb_color.blue || 0.0;
# var red = Math.floor(redFrac * 255);
# var green = Math.floor(greenFrac * 255);
# var blue = Math.floor(blueFrac * 255);
# if (!('alpha' in rgb_color)) `
# return rgbToCssColor_(red, green, blue);
# `
# var alphaFrac = rgb_color.alpha.value || 0.0;
# var rgbParams = [red, green, blue].join(',');
# return ['rgba(', rgbParams, ',', alphaFrac, ')'].join('');
# `;
# var rgbToCssColor_ = function(red, green, blue) `
# var rgbNumber = new Number((red << 16) | (green << 8) | blue);
# var hexString = rgbNumber.toString(16);
# var missingZeros = 6 - hexString.length;
# var resultBuilder = ['#'];
# for (var i = 0; i < missingZeros; i++) `
# resultBuilder.push('0');
# `
# resultBuilder.push(hexString);
# return resultBuilder.join('');
# `;
# // ...
# Corresponds to the JSON property `color`
# @return [Google::Apis::SheetsV4::Color]
attr_accessor :color
# The width of the border, in pixels.
# Deprecated; the width is determined by the "style" field.
# Corresponds to the JSON property `width`
# @return [Fixnum]
attr_accessor :width
# The style of the border.
# Corresponds to the JSON property `style`
# @return [String]
attr_accessor :style
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@color = args[:color] if args.key?(:color)
@width = args[:width] if args.key?(:width)
@style = args[:style] if args.key?(:style)
end
end
# Updates properties of the named range with the specified
# namedRangeId.
class UpdateNamedRangeRequest
include Google::Apis::Core::Hashable
# A named range.
# Corresponds to the JSON property `namedRange`
# @return [Google::Apis::SheetsV4::NamedRange]
attr_accessor :named_range
# The fields that should be updated. At least one field must be specified.
# The root `namedRange` is implied and should not be specified.
# A single `"*"` can be used as short-hand for listing every field.
# Corresponds to the JSON property `fields`
# @return [String]
attr_accessor :fields
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@named_range = args[:named_range] if args.key?(:named_range)
@fields = args[:fields] if args.key?(:fields)
end
end
# Finds and replaces data in cells over a range, sheet, or all sheets.
class FindReplaceRequest
include Google::Apis::Core::Hashable
# True if the find value should match the entire cell.
# Corresponds to the JSON property `matchEntireCell`
# @return [Boolean]
attr_accessor :match_entire_cell
alias_method :match_entire_cell?, :match_entire_cell
# True if the find value is a regex.
# The regular expression and replacement should follow Java regex rules
# at https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html.
# The replacement string is allowed to refer to capturing groups.
# For example, if one cell has the contents `"Google Sheets"` and another
# has `"Google Docs"`, then searching for `"o.* (.*)"` with a replacement of
# `"$1 Rocks"` would change the contents of the cells to
# `"GSheets Rocks"` and `"GDocs Rocks"` respectively.
# Corresponds to the JSON property `searchByRegex`
# @return [Boolean]
attr_accessor :search_by_regex
alias_method :search_by_regex?, :search_by_regex
# The value to search.
# Corresponds to the JSON property `find`
# @return [String]
attr_accessor :find
# The value to use as the replacement.
# Corresponds to the JSON property `replacement`
# @return [String]
attr_accessor :replacement
# A range on a sheet.
# All indexes are zero-based.
# Indexes are half open, e.g the start index is inclusive
# and the end index is exclusive -- [start_index, end_index).
# Missing indexes indicate the range is unbounded on that side.
# For example, if `"Sheet1"` is sheet ID 0, then:
# `Sheet1!A1:A1 == sheet_id: 0,
# start_row_index: 0, end_row_index: 1,
# start_column_index: 0, end_column_index: 1`
# `Sheet1!A3:B4 == sheet_id: 0,
# start_row_index: 2, end_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A:B == sheet_id: 0,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A5:B == sheet_id: 0,
# start_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1 == sheet_id:0`
# The start index must always be less than or equal to the end index.
# If the start index equals the end index, then the range is empty.
# Empty ranges are typically not meaningful and are usually rendered in the
# UI as `#REF!`.
# Corresponds to the JSON property `range`
# @return [Google::Apis::SheetsV4::GridRange]
attr_accessor :range
# The sheet to find/replace over.
# Corresponds to the JSON property `sheetId`
# @return [Fixnum]
attr_accessor :sheet_id
# True to find/replace over all sheets.
# Corresponds to the JSON property `allSheets`
# @return [Boolean]
attr_accessor :all_sheets
alias_method :all_sheets?, :all_sheets
# True if the search is case sensitive.
# Corresponds to the JSON property `matchCase`
# @return [Boolean]
attr_accessor :match_case
alias_method :match_case?, :match_case
# True if the search should include cells with formulas.
# False to skip cells with formulas.
# Corresponds to the JSON property `includeFormulas`
# @return [Boolean]
attr_accessor :include_formulas
alias_method :include_formulas?, :include_formulas
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@match_entire_cell = args[:match_entire_cell] if args.key?(:match_entire_cell)
@search_by_regex = args[:search_by_regex] if args.key?(:search_by_regex)
@find = args[:find] if args.key?(:find)
@replacement = args[:replacement] if args.key?(:replacement)
@range = args[:range] if args.key?(:range)
@sheet_id = args[:sheet_id] if args.key?(:sheet_id)
@all_sheets = args[:all_sheets] if args.key?(:all_sheets)
@match_case = args[:match_case] if args.key?(:match_case)
@include_formulas = args[:include_formulas] if args.key?(:include_formulas)
end
end
# Adds a new sheet.
# When a sheet is added at a given index,
# all subsequent sheets' indexes are incremented.
# To add an object sheet, use AddChartRequest instead and specify
# EmbeddedObjectPosition.sheetId or
# EmbeddedObjectPosition.newSheet.
class AddSheetRequest
include Google::Apis::Core::Hashable
# Properties of a sheet.
# Corresponds to the JSON property `properties`
# @return [Google::Apis::SheetsV4::SheetProperties]
attr_accessor :properties
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@properties = args[:properties] if args.key?(:properties)
end
end
# Updates all cells in a range with new data.
class UpdateCellsRequest
include Google::Apis::Core::Hashable
# The data to write.
# Corresponds to the JSON property `rows`
# @return [Array<Google::Apis::SheetsV4::RowData>]
attr_accessor :rows
# The fields of CellData that should be updated.
# At least one field must be specified.
# The root is the CellData; 'row.values.' should not be specified.
# A single `"*"` can be used as short-hand for listing every field.
# Corresponds to the JSON property `fields`
# @return [String]
attr_accessor :fields
# A coordinate in a sheet.
# All indexes are zero-based.
# Corresponds to the JSON property `start`
# @return [Google::Apis::SheetsV4::GridCoordinate]
attr_accessor :start
# A range on a sheet.
# All indexes are zero-based.
# Indexes are half open, e.g the start index is inclusive
# and the end index is exclusive -- [start_index, end_index).
# Missing indexes indicate the range is unbounded on that side.
# For example, if `"Sheet1"` is sheet ID 0, then:
# `Sheet1!A1:A1 == sheet_id: 0,
# start_row_index: 0, end_row_index: 1,
# start_column_index: 0, end_column_index: 1`
# `Sheet1!A3:B4 == sheet_id: 0,
# start_row_index: 2, end_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A:B == sheet_id: 0,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A5:B == sheet_id: 0,
# start_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1 == sheet_id:0`
# The start index must always be less than or equal to the end index.
# If the start index equals the end index, then the range is empty.
# Empty ranges are typically not meaningful and are usually rendered in the
# UI as `#REF!`.
# Corresponds to the JSON property `range`
# @return [Google::Apis::SheetsV4::GridRange]
attr_accessor :range
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@rows = args[:rows] if args.key?(:rows)
@fields = args[:fields] if args.key?(:fields)
@start = args[:start] if args.key?(:start)
@range = args[:range] if args.key?(:range)
end
end
# The result of deleting a conditional format rule.
class DeleteConditionalFormatRuleResponse
include Google::Apis::Core::Hashable
# A rule describing a conditional format.
# Corresponds to the JSON property `rule`
# @return [Google::Apis::SheetsV4::ConditionalFormatRule]
attr_accessor :rule
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@rule = args[:rule] if args.key?(:rule)
end
end
# Deletes a range of cells, shifting other cells into the deleted area.
class DeleteRangeRequest
include Google::Apis::Core::Hashable
# The dimension from which deleted cells will be replaced with.
# If ROWS, existing cells will be shifted upward to
# replace the deleted cells. If COLUMNS, existing cells
# will be shifted left to replace the deleted cells.
# Corresponds to the JSON property `shiftDimension`
# @return [String]
attr_accessor :shift_dimension
# A range on a sheet.
# All indexes are zero-based.
# Indexes are half open, e.g the start index is inclusive
# and the end index is exclusive -- [start_index, end_index).
# Missing indexes indicate the range is unbounded on that side.
# For example, if `"Sheet1"` is sheet ID 0, then:
# `Sheet1!A1:A1 == sheet_id: 0,
# start_row_index: 0, end_row_index: 1,
# start_column_index: 0, end_column_index: 1`
# `Sheet1!A3:B4 == sheet_id: 0,
# start_row_index: 2, end_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A:B == sheet_id: 0,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A5:B == sheet_id: 0,
# start_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1 == sheet_id:0`
# The start index must always be less than or equal to the end index.
# If the start index equals the end index, then the range is empty.
# Empty ranges are typically not meaningful and are usually rendered in the
# UI as `#REF!`.
# Corresponds to the JSON property `range`
# @return [Google::Apis::SheetsV4::GridRange]
attr_accessor :range
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@shift_dimension = args[:shift_dimension] if args.key?(:shift_dimension)
@range = args[:range] if args.key?(:range)
end
end
# A coordinate in a sheet.
# All indexes are zero-based.
class GridCoordinate
include Google::Apis::Core::Hashable
# The sheet this coordinate is on.
# Corresponds to the JSON property `sheetId`
# @return [Fixnum]
attr_accessor :sheet_id
# The row index of the coordinate.
# Corresponds to the JSON property `rowIndex`
# @return [Fixnum]
attr_accessor :row_index
# The column index of the coordinate.
# Corresponds to the JSON property `columnIndex`
# @return [Fixnum]
attr_accessor :column_index
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@sheet_id = args[:sheet_id] if args.key?(:sheet_id)
@row_index = args[:row_index] if args.key?(:row_index)
@column_index = args[:column_index] if args.key?(:column_index)
end
end
# Updates properties of the sheet with the specified
# sheetId.
class UpdateSheetPropertiesRequest
include Google::Apis::Core::Hashable
# The fields that should be updated. At least one field must be specified.
# The root `properties` is implied and should not be specified.
# A single `"*"` can be used as short-hand for listing every field.
# Corresponds to the JSON property `fields`
# @return [String]
attr_accessor :fields
# Properties of a sheet.
# Corresponds to the JSON property `properties`
# @return [Google::Apis::SheetsV4::SheetProperties]
attr_accessor :properties
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@fields = args[:fields] if args.key?(:fields)
@properties = args[:properties] if args.key?(:properties)
end
end
# Unmerges cells in the given range.
class UnmergeCellsRequest
include Google::Apis::Core::Hashable
# A range on a sheet.
# All indexes are zero-based.
# Indexes are half open, e.g the start index is inclusive
# and the end index is exclusive -- [start_index, end_index).
# Missing indexes indicate the range is unbounded on that side.
# For example, if `"Sheet1"` is sheet ID 0, then:
# `Sheet1!A1:A1 == sheet_id: 0,
# start_row_index: 0, end_row_index: 1,
# start_column_index: 0, end_column_index: 1`
# `Sheet1!A3:B4 == sheet_id: 0,
# start_row_index: 2, end_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A:B == sheet_id: 0,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A5:B == sheet_id: 0,
# start_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1 == sheet_id:0`
# The start index must always be less than or equal to the end index.
# If the start index equals the end index, then the range is empty.
# Empty ranges are typically not meaningful and are usually rendered in the
# UI as `#REF!`.
# Corresponds to the JSON property `range`
# @return [Google::Apis::SheetsV4::GridRange]
attr_accessor :range
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@range = args[:range] if args.key?(:range)
end
end
# Properties of a grid.
class GridProperties
include Google::Apis::Core::Hashable
# The number of rows in the grid.
# Corresponds to the JSON property `rowCount`
# @return [Fixnum]
attr_accessor :row_count
# The number of rows that are frozen in the grid.
# Corresponds to the JSON property `frozenRowCount`
# @return [Fixnum]
attr_accessor :frozen_row_count
# True if the grid isn't showing gridlines in the UI.
# Corresponds to the JSON property `hideGridlines`
# @return [Boolean]
attr_accessor :hide_gridlines
alias_method :hide_gridlines?, :hide_gridlines
# The number of columns in the grid.
# Corresponds to the JSON property `columnCount`
# @return [Fixnum]
attr_accessor :column_count
# The number of columns that are frozen in the grid.
# Corresponds to the JSON property `frozenColumnCount`
# @return [Fixnum]
attr_accessor :frozen_column_count
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@row_count = args[:row_count] if args.key?(:row_count)
@frozen_row_count = args[:frozen_row_count] if args.key?(:frozen_row_count)
@hide_gridlines = args[:hide_gridlines] if args.key?(:hide_gridlines)
@column_count = args[:column_count] if args.key?(:column_count)
@frozen_column_count = args[:frozen_column_count] if args.key?(:frozen_column_count)
end
end
# The result of updating an embedded object's position.
class UpdateEmbeddedObjectPositionResponse
include Google::Apis::Core::Hashable
# The position of an embedded object such as a chart.
# Corresponds to the JSON property `position`
# @return [Google::Apis::SheetsV4::EmbeddedObjectPosition]
attr_accessor :position
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@position = args[:position] if args.key?(:position)
end
end
# A sort order associated with a specific column or row.
class SortSpec
include Google::Apis::Core::Hashable
# The order data should be sorted.
# Corresponds to the JSON property `sortOrder`
# @return [String]
attr_accessor :sort_order
# The dimension the sort should be applied to.
# Corresponds to the JSON property `dimensionIndex`
# @return [Fixnum]
attr_accessor :dimension_index
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@sort_order = args[:sort_order] if args.key?(:sort_order)
@dimension_index = args[:dimension_index] if args.key?(:dimension_index)
end
end
# A sheet in a spreadsheet.
class Sheet
include Google::Apis::Core::Hashable
# Properties of a sheet.
# Corresponds to the JSON property `properties`
# @return [Google::Apis::SheetsV4::SheetProperties]
attr_accessor :properties
# The specifications of every chart on this sheet.
# Corresponds to the JSON property `charts`
# @return [Array<Google::Apis::SheetsV4::EmbeddedChart>]
attr_accessor :charts
# The filter views in this sheet.
# Corresponds to the JSON property `filterViews`
# @return [Array<Google::Apis::SheetsV4::FilterView>]
attr_accessor :filter_views
# The conditional format rules in this sheet.
# Corresponds to the JSON property `conditionalFormats`
# @return [Array<Google::Apis::SheetsV4::ConditionalFormatRule>]
attr_accessor :conditional_formats
# The protected ranges in this sheet.
# Corresponds to the JSON property `protectedRanges`
# @return [Array<Google::Apis::SheetsV4::ProtectedRange>]
attr_accessor :protected_ranges
# The default filter associated with a sheet.
# Corresponds to the JSON property `basicFilter`
# @return [Google::Apis::SheetsV4::BasicFilter]
attr_accessor :basic_filter
# The ranges that are merged together.
# Corresponds to the JSON property `merges`
# @return [Array<Google::Apis::SheetsV4::GridRange>]
attr_accessor :merges
# Data in the grid, if this is a grid sheet.
# The number of GridData objects returned is dependent on the number of
# ranges requested on this sheet. For example, if this is representing
# `Sheet1`, and the spreadsheet was requested with ranges
# `Sheet1!A1:C10` and `Sheet1!D15:E20`, then the first GridData will have a
# startRow/startColumn of `0`,
# while the second one will have `startRow 14` (zero-based row 15),
# and `startColumn 3` (zero-based column D).
# Corresponds to the JSON property `data`
# @return [Array<Google::Apis::SheetsV4::GridData>]
attr_accessor :data
# The banded (i.e. alternating colors) ranges on this sheet.
# Corresponds to the JSON property `bandedRanges`
# @return [Array<Google::Apis::SheetsV4::BandedRange>]
attr_accessor :banded_ranges
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@properties = args[:properties] if args.key?(:properties)
@charts = args[:charts] if args.key?(:charts)
@filter_views = args[:filter_views] if args.key?(:filter_views)
@conditional_formats = args[:conditional_formats] if args.key?(:conditional_formats)
@protected_ranges = args[:protected_ranges] if args.key?(:protected_ranges)
@basic_filter = args[:basic_filter] if args.key?(:basic_filter)
@merges = args[:merges] if args.key?(:merges)
@data = args[:data] if args.key?(:data)
@banded_ranges = args[:banded_ranges] if args.key?(:banded_ranges)
end
end
# A rule that may or may not match, depending on the condition.
class BooleanRule
include Google::Apis::Core::Hashable
# A condition that can evaluate to true or false.
# BooleanConditions are used by conditional formatting,
# data validation, and the criteria in filters.
# Corresponds to the JSON property `condition`
# @return [Google::Apis::SheetsV4::BooleanCondition]
attr_accessor :condition
# The format of a cell.
# Corresponds to the JSON property `format`
# @return [Google::Apis::SheetsV4::CellFormat]
attr_accessor :format
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@condition = args[:condition] if args.key?(:condition)
@format = args[:format] if args.key?(:format)
end
end
# Criteria for showing/hiding rows in a filter or filter view.
class FilterCriteria
include Google::Apis::Core::Hashable
# Values that should be hidden.
# Corresponds to the JSON property `hiddenValues`
# @return [Array<String>]
attr_accessor :hidden_values
# A condition that can evaluate to true or false.
# BooleanConditions are used by conditional formatting,
# data validation, and the criteria in filters.
# Corresponds to the JSON property `condition`
# @return [Google::Apis::SheetsV4::BooleanCondition]
attr_accessor :condition
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@hidden_values = args[:hidden_values] if args.key?(:hidden_values)
@condition = args[:condition] if args.key?(:condition)
end
end
# Metadata about a value in a pivot grouping.
class PivotGroupValueMetadata
include Google::Apis::Core::Hashable
# The kinds of value that a cell in a spreadsheet can have.
# Corresponds to the JSON property `value`
# @return [Google::Apis::SheetsV4::ExtendedValue]
attr_accessor :value
# True if the data corresponding to the value is collapsed.
# Corresponds to the JSON property `collapsed`
# @return [Boolean]
attr_accessor :collapsed
alias_method :collapsed?, :collapsed
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@value = args[:value] if args.key?(:value)
@collapsed = args[:collapsed] if args.key?(:collapsed)
end
end
# The editors of a protected range.
class Editors
include Google::Apis::Core::Hashable
# The email addresses of users with edit access to the protected range.
# Corresponds to the JSON property `users`
# @return [Array<String>]
attr_accessor :users
# The email addresses of groups with edit access to the protected range.
# Corresponds to the JSON property `groups`
# @return [Array<String>]
attr_accessor :groups
# True if anyone in the document's domain has edit access to the protected
# range. Domain protection is only supported on documents within a domain.
# Corresponds to the JSON property `domainUsersCanEdit`
# @return [Boolean]
attr_accessor :domain_users_can_edit
alias_method :domain_users_can_edit?, :domain_users_can_edit
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@users = args[:users] if args.key?(:users)
@groups = args[:groups] if args.key?(:groups)
@domain_users_can_edit = args[:domain_users_can_edit] if args.key?(:domain_users_can_edit)
end
end
# Updates a conditional format rule at the given index,
# or moves a conditional format rule to another index.
class UpdateConditionalFormatRuleRequest
include Google::Apis::Core::Hashable
# A rule describing a conditional format.
# Corresponds to the JSON property `rule`
# @return [Google::Apis::SheetsV4::ConditionalFormatRule]
attr_accessor :rule
# The zero-based index of the rule that should be replaced or moved.
# Corresponds to the JSON property `index`
# @return [Fixnum]
attr_accessor :index
# The sheet of the rule to move. Required if new_index is set,
# unused otherwise.
# Corresponds to the JSON property `sheetId`
# @return [Fixnum]
attr_accessor :sheet_id
# The zero-based new index the rule should end up at.
# Corresponds to the JSON property `newIndex`
# @return [Fixnum]
attr_accessor :new_index
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@rule = args[:rule] if args.key?(:rule)
@index = args[:index] if args.key?(:index)
@sheet_id = args[:sheet_id] if args.key?(:sheet_id)
@new_index = args[:new_index] if args.key?(:new_index)
end
end
# A data validation rule.
class DataValidationRule
include Google::Apis::Core::Hashable
# A condition that can evaluate to true or false.
# BooleanConditions are used by conditional formatting,
# data validation, and the criteria in filters.
# Corresponds to the JSON property `condition`
# @return [Google::Apis::SheetsV4::BooleanCondition]
attr_accessor :condition
# True if the UI should be customized based on the kind of condition.
# If true, "List" conditions will show a dropdown.
# Corresponds to the JSON property `showCustomUi`
# @return [Boolean]
attr_accessor :show_custom_ui
alias_method :show_custom_ui?, :show_custom_ui
# True if invalid data should be rejected.
# Corresponds to the JSON property `strict`
# @return [Boolean]
attr_accessor :strict
alias_method :strict?, :strict
# A message to show the user when adding data to the cell.
# Corresponds to the JSON property `inputMessage`
# @return [String]
attr_accessor :input_message
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@condition = args[:condition] if args.key?(:condition)
@show_custom_ui = args[:show_custom_ui] if args.key?(:show_custom_ui)
@strict = args[:strict] if args.key?(:strict)
@input_message = args[:input_message] if args.key?(:input_message)
end
end
# The domain of a chart.
# For example, if charting stock prices over time, this would be the date.
class BasicChartDomain
include Google::Apis::Core::Hashable
# The data included in a domain or series.
# Corresponds to the JSON property `domain`
# @return [Google::Apis::SheetsV4::ChartData]
attr_accessor :domain
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@domain = args[:domain] if args.key?(:domain)
end
end
# Inserts data into the spreadsheet starting at the specified coordinate.
class PasteDataRequest
include Google::Apis::Core::Hashable
# True if the data is HTML.
# Corresponds to the JSON property `html`
# @return [Boolean]
attr_accessor :html
alias_method :html?, :html
# A coordinate in a sheet.
# All indexes are zero-based.
# Corresponds to the JSON property `coordinate`
# @return [Google::Apis::SheetsV4::GridCoordinate]
attr_accessor :coordinate
# The data to insert.
# Corresponds to the JSON property `data`
# @return [String]
attr_accessor :data
# The delimiter in the data.
# Corresponds to the JSON property `delimiter`
# @return [String]
attr_accessor :delimiter
# How the data should be pasted.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@html = args[:html] if args.key?(:html)
@coordinate = args[:coordinate] if args.key?(:coordinate)
@data = args[:data] if args.key?(:data)
@delimiter = args[:delimiter] if args.key?(:delimiter)
@type = args[:type] if args.key?(:type)
end
end
# Appends rows or columns to the end of a sheet.
class AppendDimensionRequest
include Google::Apis::Core::Hashable
# The sheet to append rows or columns to.
# Corresponds to the JSON property `sheetId`
# @return [Fixnum]
attr_accessor :sheet_id
# Whether rows or columns should be appended.
# Corresponds to the JSON property `dimension`
# @return [String]
attr_accessor :dimension
# The number of rows or columns to append.
# Corresponds to the JSON property `length`
# @return [Fixnum]
attr_accessor :length
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@sheet_id = args[:sheet_id] if args.key?(:sheet_id)
@dimension = args[:dimension] if args.key?(:dimension)
@length = args[:length] if args.key?(:length)
end
end
# Adds a named range to the spreadsheet.
class AddNamedRangeRequest
include Google::Apis::Core::Hashable
# A named range.
# Corresponds to the JSON property `namedRange`
# @return [Google::Apis::SheetsV4::NamedRange]
attr_accessor :named_range
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@named_range = args[:named_range] if args.key?(:named_range)
end
end
# Update an embedded object's position (such as a moving or resizing a
# chart or image).
class UpdateEmbeddedObjectPositionRequest
include Google::Apis::Core::Hashable
# The position of an embedded object such as a chart.
# Corresponds to the JSON property `newPosition`
# @return [Google::Apis::SheetsV4::EmbeddedObjectPosition]
attr_accessor :new_position
# The fields of OverlayPosition
# that should be updated when setting a new position. Used only if
# newPosition.overlayPosition
# is set, in which case at least one field must
# be specified. The root `newPosition.overlayPosition` is implied and
# should not be specified.
# A single `"*"` can be used as short-hand for listing every field.
# Corresponds to the JSON property `fields`
# @return [String]
attr_accessor :fields
# The ID of the object to moved.
# Corresponds to the JSON property `objectId`
# @return [Fixnum]
attr_accessor :object_id_prop
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@new_position = args[:new_position] if args.key?(:new_position)
@fields = args[:fields] if args.key?(:fields)
@object_id_prop = args[:object_id_prop] if args.key?(:object_id_prop)
end
end
# A <a href="/chart/interactive/docs/gallery/piechart">pie chart</a>.
class PieChartSpec
include Google::Apis::Core::Hashable
# Where the legend of the pie chart should be drawn.
# Corresponds to the JSON property `legendPosition`
# @return [String]
attr_accessor :legend_position
# The size of the hole in the pie chart.
# Corresponds to the JSON property `pieHole`
# @return [Float]
attr_accessor :pie_hole
# The data included in a domain or series.
# Corresponds to the JSON property `domain`
# @return [Google::Apis::SheetsV4::ChartData]
attr_accessor :domain
# True if the pie is three dimensional.
# Corresponds to the JSON property `threeDimensional`
# @return [Boolean]
attr_accessor :three_dimensional
alias_method :three_dimensional?, :three_dimensional
# The data included in a domain or series.
# Corresponds to the JSON property `series`
# @return [Google::Apis::SheetsV4::ChartData]
attr_accessor :series
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@legend_position = args[:legend_position] if args.key?(:legend_position)
@pie_hole = args[:pie_hole] if args.key?(:pie_hole)
@domain = args[:domain] if args.key?(:domain)
@three_dimensional = args[:three_dimensional] if args.key?(:three_dimensional)
@series = args[:series] if args.key?(:series)
end
end
# Updates properties of the filter view.
class UpdateFilterViewRequest
include Google::Apis::Core::Hashable
# A filter view.
# Corresponds to the JSON property `filter`
# @return [Google::Apis::SheetsV4::FilterView]
attr_accessor :filter
# The fields that should be updated. At least one field must be specified.
# The root `filter` is implied and should not be specified.
# A single `"*"` can be used as short-hand for listing every field.
# Corresponds to the JSON property `fields`
# @return [String]
attr_accessor :fields
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@filter = args[:filter] if args.key?(:filter)
@fields = args[:fields] if args.key?(:fields)
end
end
# A rule describing a conditional format.
class ConditionalFormatRule
include Google::Apis::Core::Hashable
# The ranges that will be formatted if the condition is true.
# All the ranges must be on the same grid.
# Corresponds to the JSON property `ranges`
# @return [Array<Google::Apis::SheetsV4::GridRange>]
attr_accessor :ranges
# A rule that applies a gradient color scale format, based on
# the interpolation points listed. The format of a cell will vary
# based on its contents as compared to the values of the interpolation
# points.
# Corresponds to the JSON property `gradientRule`
# @return [Google::Apis::SheetsV4::GradientRule]
attr_accessor :gradient_rule
# A rule that may or may not match, depending on the condition.
# Corresponds to the JSON property `booleanRule`
# @return [Google::Apis::SheetsV4::BooleanRule]
attr_accessor :boolean_rule
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@ranges = args[:ranges] if args.key?(:ranges)
@gradient_rule = args[:gradient_rule] if args.key?(:gradient_rule)
@boolean_rule = args[:boolean_rule] if args.key?(:boolean_rule)
end
end
# Copies data from the source to the destination.
class CopyPasteRequest
include Google::Apis::Core::Hashable
# A range on a sheet.
# All indexes are zero-based.
# Indexes are half open, e.g the start index is inclusive
# and the end index is exclusive -- [start_index, end_index).
# Missing indexes indicate the range is unbounded on that side.
# For example, if `"Sheet1"` is sheet ID 0, then:
# `Sheet1!A1:A1 == sheet_id: 0,
# start_row_index: 0, end_row_index: 1,
# start_column_index: 0, end_column_index: 1`
# `Sheet1!A3:B4 == sheet_id: 0,
# start_row_index: 2, end_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A:B == sheet_id: 0,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A5:B == sheet_id: 0,
# start_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1 == sheet_id:0`
# The start index must always be less than or equal to the end index.
# If the start index equals the end index, then the range is empty.
# Empty ranges are typically not meaningful and are usually rendered in the
# UI as `#REF!`.
# Corresponds to the JSON property `source`
# @return [Google::Apis::SheetsV4::GridRange]
attr_accessor :source
# What kind of data to paste.
# Corresponds to the JSON property `pasteType`
# @return [String]
attr_accessor :paste_type
# A range on a sheet.
# All indexes are zero-based.
# Indexes are half open, e.g the start index is inclusive
# and the end index is exclusive -- [start_index, end_index).
# Missing indexes indicate the range is unbounded on that side.
# For example, if `"Sheet1"` is sheet ID 0, then:
# `Sheet1!A1:A1 == sheet_id: 0,
# start_row_index: 0, end_row_index: 1,
# start_column_index: 0, end_column_index: 1`
# `Sheet1!A3:B4 == sheet_id: 0,
# start_row_index: 2, end_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A:B == sheet_id: 0,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A5:B == sheet_id: 0,
# start_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1 == sheet_id:0`
# The start index must always be less than or equal to the end index.
# If the start index equals the end index, then the range is empty.
# Empty ranges are typically not meaningful and are usually rendered in the
# UI as `#REF!`.
# Corresponds to the JSON property `destination`
# @return [Google::Apis::SheetsV4::GridRange]
attr_accessor :destination
# How that data should be oriented when pasting.
# Corresponds to the JSON property `pasteOrientation`
# @return [String]
attr_accessor :paste_orientation
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@source = args[:source] if args.key?(:source)
@paste_type = args[:paste_type] if args.key?(:paste_type)
@destination = args[:destination] if args.key?(:destination)
@paste_orientation = args[:paste_orientation] if args.key?(:paste_orientation)
end
end
# A single kind of update to apply to a spreadsheet.
class Request
include Google::Apis::Core::Hashable
# Adds a new conditional format rule at the given index.
# All subsequent rules' indexes are incremented.
# Corresponds to the JSON property `addConditionalFormatRule`
# @return [Google::Apis::SheetsV4::AddConditionalFormatRuleRequest]
attr_accessor :add_conditional_format_rule
# Adds a named range to the spreadsheet.
# Corresponds to the JSON property `addNamedRange`
# @return [Google::Apis::SheetsV4::AddNamedRangeRequest]
attr_accessor :add_named_range
# Updates all cells in a range with new data.
# Corresponds to the JSON property `updateCells`
# @return [Google::Apis::SheetsV4::UpdateCellsRequest]
attr_accessor :update_cells
# Updates properties of a spreadsheet.
# Corresponds to the JSON property `updateSpreadsheetProperties`
# @return [Google::Apis::SheetsV4::UpdateSpreadsheetPropertiesRequest]
attr_accessor :update_spreadsheet_properties
# Deletes the embedded object with the given ID.
# Corresponds to the JSON property `deleteEmbeddedObject`
# @return [Google::Apis::SheetsV4::DeleteEmbeddedObjectRequest]
attr_accessor :delete_embedded_object
# Updates properties of the filter view.
# Corresponds to the JSON property `updateFilterView`
# @return [Google::Apis::SheetsV4::UpdateFilterViewRequest]
attr_accessor :update_filter_view
# Adds a new banded range to the spreadsheet.
# Corresponds to the JSON property `addBanding`
# @return [Google::Apis::SheetsV4::AddBandingRequest]
attr_accessor :add_banding
# Adds new cells after the last row with data in a sheet,
# inserting new rows into the sheet if necessary.
# Corresponds to the JSON property `appendCells`
# @return [Google::Apis::SheetsV4::AppendCellsRequest]
attr_accessor :append_cells
# Automatically resizes one or more dimensions based on the contents
# of the cells in that dimension.
# Corresponds to the JSON property `autoResizeDimensions`
# @return [Google::Apis::SheetsV4::AutoResizeDimensionsRequest]
attr_accessor :auto_resize_dimensions
# Moves data from the source to the destination.
# Corresponds to the JSON property `cutPaste`
# @return [Google::Apis::SheetsV4::CutPasteRequest]
attr_accessor :cut_paste
# Merges all cells in the range.
# Corresponds to the JSON property `mergeCells`
# @return [Google::Apis::SheetsV4::MergeCellsRequest]
attr_accessor :merge_cells
# Updates properties of the named range with the specified
# namedRangeId.
# Corresponds to the JSON property `updateNamedRange`
# @return [Google::Apis::SheetsV4::UpdateNamedRangeRequest]
attr_accessor :update_named_range
# Updates properties of the sheet with the specified
# sheetId.
# Corresponds to the JSON property `updateSheetProperties`
# @return [Google::Apis::SheetsV4::UpdateSheetPropertiesRequest]
attr_accessor :update_sheet_properties
# Deletes the dimensions from the sheet.
# Corresponds to the JSON property `deleteDimension`
# @return [Google::Apis::SheetsV4::DeleteDimensionRequest]
attr_accessor :delete_dimension
# Fills in more data based on existing data.
# Corresponds to the JSON property `autoFill`
# @return [Google::Apis::SheetsV4::AutoFillRequest]
attr_accessor :auto_fill
# Sorts data in rows based on a sort order per column.
# Corresponds to the JSON property `sortRange`
# @return [Google::Apis::SheetsV4::SortRangeRequest]
attr_accessor :sort_range
# Deletes the protected range with the given ID.
# Corresponds to the JSON property `deleteProtectedRange`
# @return [Google::Apis::SheetsV4::DeleteProtectedRangeRequest]
attr_accessor :delete_protected_range
# Duplicates a particular filter view.
# Corresponds to the JSON property `duplicateFilterView`
# @return [Google::Apis::SheetsV4::DuplicateFilterViewRequest]
attr_accessor :duplicate_filter_view
# Adds a chart to a sheet in the spreadsheet.
# Corresponds to the JSON property `addChart`
# @return [Google::Apis::SheetsV4::AddChartRequest]
attr_accessor :add_chart
# Finds and replaces data in cells over a range, sheet, or all sheets.
# Corresponds to the JSON property `findReplace`
# @return [Google::Apis::SheetsV4::FindReplaceRequest]
attr_accessor :find_replace
# Splits a column of text into multiple columns,
# based on a delimiter in each cell.
# Corresponds to the JSON property `textToColumns`
# @return [Google::Apis::SheetsV4::TextToColumnsRequest]
attr_accessor :text_to_columns
# Updates a chart's specifications.
# (This does not move or resize a chart. To move or resize a chart, use
# UpdateEmbeddedObjectPositionRequest.)
# Corresponds to the JSON property `updateChartSpec`
# @return [Google::Apis::SheetsV4::UpdateChartSpecRequest]
attr_accessor :update_chart_spec
# Adds a new sheet.
# When a sheet is added at a given index,
# all subsequent sheets' indexes are incremented.
# To add an object sheet, use AddChartRequest instead and specify
# EmbeddedObjectPosition.sheetId or
# EmbeddedObjectPosition.newSheet.
# Corresponds to the JSON property `addSheet`
# @return [Google::Apis::SheetsV4::AddSheetRequest]
attr_accessor :add_sheet
# Updates an existing protected range with the specified
# protectedRangeId.
# Corresponds to the JSON property `updateProtectedRange`
# @return [Google::Apis::SheetsV4::UpdateProtectedRangeRequest]
attr_accessor :update_protected_range
# Deletes a particular filter view.
# Corresponds to the JSON property `deleteFilterView`
# @return [Google::Apis::SheetsV4::DeleteFilterViewRequest]
attr_accessor :delete_filter_view
# Copies data from the source to the destination.
# Corresponds to the JSON property `copyPaste`
# @return [Google::Apis::SheetsV4::CopyPasteRequest]
attr_accessor :copy_paste
# Inserts rows or columns in a sheet at a particular index.
# Corresponds to the JSON property `insertDimension`
# @return [Google::Apis::SheetsV4::InsertDimensionRequest]
attr_accessor :insert_dimension
# Deletes a range of cells, shifting other cells into the deleted area.
# Corresponds to the JSON property `deleteRange`
# @return [Google::Apis::SheetsV4::DeleteRangeRequest]
attr_accessor :delete_range
# Removes the banded range with the given ID from the spreadsheet.
# Corresponds to the JSON property `deleteBanding`
# @return [Google::Apis::SheetsV4::DeleteBandingRequest]
attr_accessor :delete_banding
# Adds a filter view.
# Corresponds to the JSON property `addFilterView`
# @return [Google::Apis::SheetsV4::AddFilterViewRequest]
attr_accessor :add_filter_view
# Sets a data validation rule to every cell in the range.
# To clear validation in a range, call this with no rule specified.
# Corresponds to the JSON property `setDataValidation`
# @return [Google::Apis::SheetsV4::SetDataValidationRequest]
attr_accessor :set_data_validation
# Updates the borders of a range.
# If a field is not set in the request, that means the border remains as-is.
# For example, with two subsequent UpdateBordersRequest:
# 1. range: A1:A5 `` top: RED, bottom: WHITE ``
# 2. range: A1:A5 `` left: BLUE ``
# That would result in A1:A5 having a borders of
# `` top: RED, bottom: WHITE, left: BLUE ``.
# If you want to clear a border, explicitly set the style to
# NONE.
# Corresponds to the JSON property `updateBorders`
# @return [Google::Apis::SheetsV4::UpdateBordersRequest]
attr_accessor :update_borders
# Deletes a conditional format rule at the given index.
# All subsequent rules' indexes are decremented.
# Corresponds to the JSON property `deleteConditionalFormatRule`
# @return [Google::Apis::SheetsV4::DeleteConditionalFormatRuleRequest]
attr_accessor :delete_conditional_format_rule
# Updates all cells in the range to the values in the given Cell object.
# Only the fields listed in the fields field are updated; others are
# unchanged.
# If writing a cell with a formula, the formula's ranges will automatically
# increment for each field in the range.
# For example, if writing a cell with formula `=A1` into range B2:C4,
# B2 would be `=A1`, B3 would be `=A2`, B4 would be `=A3`,
# C2 would be `=B1`, C3 would be `=B2`, C4 would be `=B3`.
# To keep the formula's ranges static, use the `$` indicator.
# For example, use the formula `=$A$1` to prevent both the row and the
# column from incrementing.
# Corresponds to the JSON property `repeatCell`
# @return [Google::Apis::SheetsV4::RepeatCellRequest]
attr_accessor :repeat_cell
# Clears the basic filter, if any exists on the sheet.
# Corresponds to the JSON property `clearBasicFilter`
# @return [Google::Apis::SheetsV4::ClearBasicFilterRequest]
attr_accessor :clear_basic_filter
# Appends rows or columns to the end of a sheet.
# Corresponds to the JSON property `appendDimension`
# @return [Google::Apis::SheetsV4::AppendDimensionRequest]
attr_accessor :append_dimension
# Updates a conditional format rule at the given index,
# or moves a conditional format rule to another index.
# Corresponds to the JSON property `updateConditionalFormatRule`
# @return [Google::Apis::SheetsV4::UpdateConditionalFormatRuleRequest]
attr_accessor :update_conditional_format_rule
# Inserts cells into a range, shifting the existing cells over or down.
# Corresponds to the JSON property `insertRange`
# @return [Google::Apis::SheetsV4::InsertRangeRequest]
attr_accessor :insert_range
# Moves one or more rows or columns.
# Corresponds to the JSON property `moveDimension`
# @return [Google::Apis::SheetsV4::MoveDimensionRequest]
attr_accessor :move_dimension
# Updates properties of the supplied banded range.
# Corresponds to the JSON property `updateBanding`
# @return [Google::Apis::SheetsV4::UpdateBandingRequest]
attr_accessor :update_banding
# Removes the named range with the given ID from the spreadsheet.
# Corresponds to the JSON property `deleteNamedRange`
# @return [Google::Apis::SheetsV4::DeleteNamedRangeRequest]
attr_accessor :delete_named_range
# Adds a new protected range.
# Corresponds to the JSON property `addProtectedRange`
# @return [Google::Apis::SheetsV4::AddProtectedRangeRequest]
attr_accessor :add_protected_range
# Duplicates the contents of a sheet.
# Corresponds to the JSON property `duplicateSheet`
# @return [Google::Apis::SheetsV4::DuplicateSheetRequest]
attr_accessor :duplicate_sheet
# Deletes the requested sheet.
# Corresponds to the JSON property `deleteSheet`
# @return [Google::Apis::SheetsV4::DeleteSheetRequest]
attr_accessor :delete_sheet
# Unmerges cells in the given range.
# Corresponds to the JSON property `unmergeCells`
# @return [Google::Apis::SheetsV4::UnmergeCellsRequest]
attr_accessor :unmerge_cells
# Update an embedded object's position (such as a moving or resizing a
# chart or image).
# Corresponds to the JSON property `updateEmbeddedObjectPosition`
# @return [Google::Apis::SheetsV4::UpdateEmbeddedObjectPositionRequest]
attr_accessor :update_embedded_object_position
# Updates properties of dimensions within the specified range.
# Corresponds to the JSON property `updateDimensionProperties`
# @return [Google::Apis::SheetsV4::UpdateDimensionPropertiesRequest]
attr_accessor :update_dimension_properties
# Inserts data into the spreadsheet starting at the specified coordinate.
# Corresponds to the JSON property `pasteData`
# @return [Google::Apis::SheetsV4::PasteDataRequest]
attr_accessor :paste_data
# Sets the basic filter associated with a sheet.
# Corresponds to the JSON property `setBasicFilter`
# @return [Google::Apis::SheetsV4::SetBasicFilterRequest]
attr_accessor :set_basic_filter
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@add_conditional_format_rule = args[:add_conditional_format_rule] if args.key?(:add_conditional_format_rule)
@add_named_range = args[:add_named_range] if args.key?(:add_named_range)
@update_cells = args[:update_cells] if args.key?(:update_cells)
@update_spreadsheet_properties = args[:update_spreadsheet_properties] if args.key?(:update_spreadsheet_properties)
@delete_embedded_object = args[:delete_embedded_object] if args.key?(:delete_embedded_object)
@update_filter_view = args[:update_filter_view] if args.key?(:update_filter_view)
@add_banding = args[:add_banding] if args.key?(:add_banding)
@append_cells = args[:append_cells] if args.key?(:append_cells)
@auto_resize_dimensions = args[:auto_resize_dimensions] if args.key?(:auto_resize_dimensions)
@cut_paste = args[:cut_paste] if args.key?(:cut_paste)
@merge_cells = args[:merge_cells] if args.key?(:merge_cells)
@update_named_range = args[:update_named_range] if args.key?(:update_named_range)
@update_sheet_properties = args[:update_sheet_properties] if args.key?(:update_sheet_properties)
@delete_dimension = args[:delete_dimension] if args.key?(:delete_dimension)
@auto_fill = args[:auto_fill] if args.key?(:auto_fill)
@sort_range = args[:sort_range] if args.key?(:sort_range)
@delete_protected_range = args[:delete_protected_range] if args.key?(:delete_protected_range)
@duplicate_filter_view = args[:duplicate_filter_view] if args.key?(:duplicate_filter_view)
@add_chart = args[:add_chart] if args.key?(:add_chart)
@find_replace = args[:find_replace] if args.key?(:find_replace)
@text_to_columns = args[:text_to_columns] if args.key?(:text_to_columns)
@update_chart_spec = args[:update_chart_spec] if args.key?(:update_chart_spec)
@add_sheet = args[:add_sheet] if args.key?(:add_sheet)
@update_protected_range = args[:update_protected_range] if args.key?(:update_protected_range)
@delete_filter_view = args[:delete_filter_view] if args.key?(:delete_filter_view)
@copy_paste = args[:copy_paste] if args.key?(:copy_paste)
@insert_dimension = args[:insert_dimension] if args.key?(:insert_dimension)
@delete_range = args[:delete_range] if args.key?(:delete_range)
@delete_banding = args[:delete_banding] if args.key?(:delete_banding)
@add_filter_view = args[:add_filter_view] if args.key?(:add_filter_view)
@set_data_validation = args[:set_data_validation] if args.key?(:set_data_validation)
@update_borders = args[:update_borders] if args.key?(:update_borders)
@delete_conditional_format_rule = args[:delete_conditional_format_rule] if args.key?(:delete_conditional_format_rule)
@repeat_cell = args[:repeat_cell] if args.key?(:repeat_cell)
@clear_basic_filter = args[:clear_basic_filter] if args.key?(:clear_basic_filter)
@append_dimension = args[:append_dimension] if args.key?(:append_dimension)
@update_conditional_format_rule = args[:update_conditional_format_rule] if args.key?(:update_conditional_format_rule)
@insert_range = args[:insert_range] if args.key?(:insert_range)
@move_dimension = args[:move_dimension] if args.key?(:move_dimension)
@update_banding = args[:update_banding] if args.key?(:update_banding)
@delete_named_range = args[:delete_named_range] if args.key?(:delete_named_range)
@add_protected_range = args[:add_protected_range] if args.key?(:add_protected_range)
@duplicate_sheet = args[:duplicate_sheet] if args.key?(:duplicate_sheet)
@delete_sheet = args[:delete_sheet] if args.key?(:delete_sheet)
@unmerge_cells = args[:unmerge_cells] if args.key?(:unmerge_cells)
@update_embedded_object_position = args[:update_embedded_object_position] if args.key?(:update_embedded_object_position)
@update_dimension_properties = args[:update_dimension_properties] if args.key?(:update_dimension_properties)
@paste_data = args[:paste_data] if args.key?(:paste_data)
@set_basic_filter = args[:set_basic_filter] if args.key?(:set_basic_filter)
end
end
# A condition that can evaluate to true or false.
# BooleanConditions are used by conditional formatting,
# data validation, and the criteria in filters.
class BooleanCondition
include Google::Apis::Core::Hashable
# The type of condition.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
# The values of the condition. The number of supported values depends
# on the condition type. Some support zero values,
# others one or two values,
# and ConditionType.ONE_OF_LIST supports an arbitrary number of values.
# Corresponds to the JSON property `values`
# @return [Array<Google::Apis::SheetsV4::ConditionValue>]
attr_accessor :values
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@type = args[:type] if args.key?(:type)
@values = args[:values] if args.key?(:values)
end
end
# A range on a sheet.
# All indexes are zero-based.
# Indexes are half open, e.g the start index is inclusive
# and the end index is exclusive -- [start_index, end_index).
# Missing indexes indicate the range is unbounded on that side.
# For example, if `"Sheet1"` is sheet ID 0, then:
# `Sheet1!A1:A1 == sheet_id: 0,
# start_row_index: 0, end_row_index: 1,
# start_column_index: 0, end_column_index: 1`
# `Sheet1!A3:B4 == sheet_id: 0,
# start_row_index: 2, end_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A:B == sheet_id: 0,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A5:B == sheet_id: 0,
# start_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1 == sheet_id:0`
# The start index must always be less than or equal to the end index.
# If the start index equals the end index, then the range is empty.
# Empty ranges are typically not meaningful and are usually rendered in the
# UI as `#REF!`.
class GridRange
include Google::Apis::Core::Hashable
# The end row (exclusive) of the range, or not set if unbounded.
# Corresponds to the JSON property `endRowIndex`
# @return [Fixnum]
attr_accessor :end_row_index
# The end column (exclusive) of the range, or not set if unbounded.
# Corresponds to the JSON property `endColumnIndex`
# @return [Fixnum]
attr_accessor :end_column_index
# The start row (inclusive) of the range, or not set if unbounded.
# Corresponds to the JSON property `startRowIndex`
# @return [Fixnum]
attr_accessor :start_row_index
# The start column (inclusive) of the range, or not set if unbounded.
# Corresponds to the JSON property `startColumnIndex`
# @return [Fixnum]
attr_accessor :start_column_index
# The sheet this range is on.
# Corresponds to the JSON property `sheetId`
# @return [Fixnum]
attr_accessor :sheet_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@end_row_index = args[:end_row_index] if args.key?(:end_row_index)
@end_column_index = args[:end_column_index] if args.key?(:end_column_index)
@start_row_index = args[:start_row_index] if args.key?(:start_row_index)
@start_column_index = args[:start_column_index] if args.key?(:start_column_index)
@sheet_id = args[:sheet_id] if args.key?(:sheet_id)
end
end
# The specification for a basic chart. See BasicChartType for the list
# of charts this supports.
class BasicChartSpec
include Google::Apis::Core::Hashable
# The domain of data this is charting.
# Only a single domain is currently supported.
# Corresponds to the JSON property `domains`
# @return [Array<Google::Apis::SheetsV4::BasicChartDomain>]
attr_accessor :domains
# The number of rows or columns in the data that are "headers".
# If not set, Google Sheets will guess how many rows are headers based
# on the data.
# (Note that BasicChartAxis.title may override the axis title
# inferred from the header values.)
# Corresponds to the JSON property `headerCount`
# @return [Fixnum]
attr_accessor :header_count
# The axis on the chart.
# Corresponds to the JSON property `axis`
# @return [Array<Google::Apis::SheetsV4::BasicChartAxis>]
attr_accessor :axis
# The type of the chart.
# Corresponds to the JSON property `chartType`
# @return [String]
attr_accessor :chart_type
# The data this chart is visualizing.
# Corresponds to the JSON property `series`
# @return [Array<Google::Apis::SheetsV4::BasicChartSeries>]
attr_accessor :series
# The position of the chart legend.
# Corresponds to the JSON property `legendPosition`
# @return [String]
attr_accessor :legend_position
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@domains = args[:domains] if args.key?(:domains)
@header_count = args[:header_count] if args.key?(:header_count)
@axis = args[:axis] if args.key?(:axis)
@chart_type = args[:chart_type] if args.key?(:chart_type)
@series = args[:series] if args.key?(:series)
@legend_position = args[:legend_position] if args.key?(:legend_position)
end
end
# Sets a data validation rule to every cell in the range.
# To clear validation in a range, call this with no rule specified.
class SetDataValidationRequest
include Google::Apis::Core::Hashable
# A data validation rule.
# Corresponds to the JSON property `rule`
# @return [Google::Apis::SheetsV4::DataValidationRule]
attr_accessor :rule
# A range on a sheet.
# All indexes are zero-based.
# Indexes are half open, e.g the start index is inclusive
# and the end index is exclusive -- [start_index, end_index).
# Missing indexes indicate the range is unbounded on that side.
# For example, if `"Sheet1"` is sheet ID 0, then:
# `Sheet1!A1:A1 == sheet_id: 0,
# start_row_index: 0, end_row_index: 1,
# start_column_index: 0, end_column_index: 1`
# `Sheet1!A3:B4 == sheet_id: 0,
# start_row_index: 2, end_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A:B == sheet_id: 0,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A5:B == sheet_id: 0,
# start_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1 == sheet_id:0`
# The start index must always be less than or equal to the end index.
# If the start index equals the end index, then the range is empty.
# Empty ranges are typically not meaningful and are usually rendered in the
# UI as `#REF!`.
# Corresponds to the JSON property `range`
# @return [Google::Apis::SheetsV4::GridRange]
attr_accessor :range
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@rule = args[:rule] if args.key?(:rule)
@range = args[:range] if args.key?(:range)
end
end
# Data about a specific cell.
class CellData
include Google::Apis::Core::Hashable
# The kinds of value that a cell in a spreadsheet can have.
# Corresponds to the JSON property `effectiveValue`
# @return [Google::Apis::SheetsV4::ExtendedValue]
attr_accessor :effective_value
# Runs of rich text applied to subsections of the cell. Runs are only valid
# on user entered strings, not formulas, bools, or numbers.
# Runs start at specific indexes in the text and continue until the next
# run. Properties of a run will continue unless explicitly changed
# in a subsequent run (and properties of the first run will continue
# the properties of the cell unless explicitly changed).
# When writing, the new runs will overwrite any prior runs. When writing a
# new user_entered_value, previous runs will be erased.
# Corresponds to the JSON property `textFormatRuns`
# @return [Array<Google::Apis::SheetsV4::TextFormatRun>]
attr_accessor :text_format_runs
# The formatted value of the cell.
# This is the value as it's shown to the user.
# This field is read-only.
# Corresponds to the JSON property `formattedValue`
# @return [String]
attr_accessor :formatted_value
# A hyperlink this cell points to, if any.
# This field is read-only. (To set it, use a `=HYPERLINK` formula.)
# Corresponds to the JSON property `hyperlink`
# @return [String]
attr_accessor :hyperlink
# A pivot table.
# Corresponds to the JSON property `pivotTable`
# @return [Google::Apis::SheetsV4::PivotTable]
attr_accessor :pivot_table
# The format of a cell.
# Corresponds to the JSON property `userEnteredFormat`
# @return [Google::Apis::SheetsV4::CellFormat]
attr_accessor :user_entered_format
# The format of a cell.
# Corresponds to the JSON property `effectiveFormat`
# @return [Google::Apis::SheetsV4::CellFormat]
attr_accessor :effective_format
# Any note on the cell.
# Corresponds to the JSON property `note`
# @return [String]
attr_accessor :note
# The kinds of value that a cell in a spreadsheet can have.
# Corresponds to the JSON property `userEnteredValue`
# @return [Google::Apis::SheetsV4::ExtendedValue]
attr_accessor :user_entered_value
# A data validation rule.
# Corresponds to the JSON property `dataValidation`
# @return [Google::Apis::SheetsV4::DataValidationRule]
attr_accessor :data_validation
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@effective_value = args[:effective_value] if args.key?(:effective_value)
@text_format_runs = args[:text_format_runs] if args.key?(:text_format_runs)
@formatted_value = args[:formatted_value] if args.key?(:formatted_value)
@hyperlink = args[:hyperlink] if args.key?(:hyperlink)
@pivot_table = args[:pivot_table] if args.key?(:pivot_table)
@user_entered_format = args[:user_entered_format] if args.key?(:user_entered_format)
@effective_format = args[:effective_format] if args.key?(:effective_format)
@note = args[:note] if args.key?(:note)
@user_entered_value = args[:user_entered_value] if args.key?(:user_entered_value)
@data_validation = args[:data_validation] if args.key?(:data_validation)
end
end
# The request for updating any aspect of a spreadsheet.
class BatchUpdateSpreadsheetRequest
include Google::Apis::Core::Hashable
# Determines if the update response should include the spreadsheet
# resource.
# Corresponds to the JSON property `includeSpreadsheetInResponse`
# @return [Boolean]
attr_accessor :include_spreadsheet_in_response
alias_method :include_spreadsheet_in_response?, :include_spreadsheet_in_response
# Limits the ranges included in the response spreadsheet.
# Meaningful only if include_spreadsheet_response is 'true'.
# Corresponds to the JSON property `responseRanges`
# @return [Array<String>]
attr_accessor :response_ranges
# True if grid data should be returned. Meaningful only if
# if include_spreadsheet_response is 'true'.
# This parameter is ignored if a field mask was set in the request.
# Corresponds to the JSON property `responseIncludeGridData`
# @return [Boolean]
attr_accessor :response_include_grid_data
alias_method :response_include_grid_data?, :response_include_grid_data
# A list of updates to apply to the spreadsheet.
# Corresponds to the JSON property `requests`
# @return [Array<Google::Apis::SheetsV4::Request>]
attr_accessor :requests
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@include_spreadsheet_in_response = args[:include_spreadsheet_in_response] if args.key?(:include_spreadsheet_in_response)
@response_ranges = args[:response_ranges] if args.key?(:response_ranges)
@response_include_grid_data = args[:response_include_grid_data] if args.key?(:response_include_grid_data)
@requests = args[:requests] if args.key?(:requests)
end
end
# An axis of the chart.
# A chart may not have more than one axis per
# axis position.
class BasicChartAxis
include Google::Apis::Core::Hashable
# The format of a run of text in a cell.
# Absent values indicate that the field isn't specified.
# Corresponds to the JSON property `format`
# @return [Google::Apis::SheetsV4::TextFormat]
attr_accessor :format
# The position of this axis.
# Corresponds to the JSON property `position`
# @return [String]
attr_accessor :position
# The title of this axis. If set, this overrides any title inferred
# from headers of the data.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@format = args[:format] if args.key?(:format)
@position = args[:position] if args.key?(:position)
@title = args[:title] if args.key?(:title)
end
end
# The amount of padding around the cell, in pixels.
# When updating padding, every field must be specified.
class Padding
include Google::Apis::Core::Hashable
# The bottom padding of the cell.
# Corresponds to the JSON property `bottom`
# @return [Fixnum]
attr_accessor :bottom
# The top padding of the cell.
# Corresponds to the JSON property `top`
# @return [Fixnum]
attr_accessor :top
# The left padding of the cell.
# Corresponds to the JSON property `left`
# @return [Fixnum]
attr_accessor :left
# The right padding of the cell.
# Corresponds to the JSON property `right`
# @return [Fixnum]
attr_accessor :right
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bottom = args[:bottom] if args.key?(:bottom)
@top = args[:top] if args.key?(:top)
@left = args[:left] if args.key?(:left)
@right = args[:right] if args.key?(:right)
end
end
# Deletes the dimensions from the sheet.
class DeleteDimensionRequest
include Google::Apis::Core::Hashable
# A range along a single dimension on a sheet.
# All indexes are zero-based.
# Indexes are half open: the start index is inclusive
# and the end index is exclusive.
# Missing indexes indicate the range is unbounded on that side.
# Corresponds to the JSON property `range`
# @return [Google::Apis::SheetsV4::DimensionRange]
attr_accessor :range
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@range = args[:range] if args.key?(:range)
end
end
# Updates a chart's specifications.
# (This does not move or resize a chart. To move or resize a chart, use
# UpdateEmbeddedObjectPositionRequest.)
class UpdateChartSpecRequest
include Google::Apis::Core::Hashable
# The specifications of a chart.
# Corresponds to the JSON property `spec`
# @return [Google::Apis::SheetsV4::ChartSpec]
attr_accessor :spec
# The ID of the chart to update.
# Corresponds to the JSON property `chartId`
# @return [Fixnum]
attr_accessor :chart_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@spec = args[:spec] if args.key?(:spec)
@chart_id = args[:chart_id] if args.key?(:chart_id)
end
end
# Deletes a particular filter view.
class DeleteFilterViewRequest
include Google::Apis::Core::Hashable
# The ID of the filter to delete.
# Corresponds to the JSON property `filterId`
# @return [Fixnum]
attr_accessor :filter_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@filter_id = args[:filter_id] if args.key?(:filter_id)
end
end
# The response when updating a range of values in a spreadsheet.
class BatchUpdateValuesResponse
include Google::Apis::Core::Hashable
# The total number of columns where at least one cell in the column was
# updated.
# Corresponds to the JSON property `totalUpdatedColumns`
# @return [Fixnum]
attr_accessor :total_updated_columns
# The spreadsheet the updates were applied to.
# Corresponds to the JSON property `spreadsheetId`
# @return [String]
attr_accessor :spreadsheet_id
# The total number of rows where at least one cell in the row was updated.
# Corresponds to the JSON property `totalUpdatedRows`
# @return [Fixnum]
attr_accessor :total_updated_rows
# One UpdateValuesResponse per requested range, in the same order as
# the requests appeared.
# Corresponds to the JSON property `responses`
# @return [Array<Google::Apis::SheetsV4::UpdateValuesResponse>]
attr_accessor :responses
# The total number of sheets where at least one cell in the sheet was
# updated.
# Corresponds to the JSON property `totalUpdatedSheets`
# @return [Fixnum]
attr_accessor :total_updated_sheets
# The total number of cells updated.
# Corresponds to the JSON property `totalUpdatedCells`
# @return [Fixnum]
attr_accessor :total_updated_cells
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@total_updated_columns = args[:total_updated_columns] if args.key?(:total_updated_columns)
@spreadsheet_id = args[:spreadsheet_id] if args.key?(:spreadsheet_id)
@total_updated_rows = args[:total_updated_rows] if args.key?(:total_updated_rows)
@responses = args[:responses] if args.key?(:responses)
@total_updated_sheets = args[:total_updated_sheets] if args.key?(:total_updated_sheets)
@total_updated_cells = args[:total_updated_cells] if args.key?(:total_updated_cells)
end
end
# Sorts data in rows based on a sort order per column.
class SortRangeRequest
include Google::Apis::Core::Hashable
# The sort order per column. Later specifications are used when values
# are equal in the earlier specifications.
# Corresponds to the JSON property `sortSpecs`
# @return [Array<Google::Apis::SheetsV4::SortSpec>]
attr_accessor :sort_specs
# A range on a sheet.
# All indexes are zero-based.
# Indexes are half open, e.g the start index is inclusive
# and the end index is exclusive -- [start_index, end_index).
# Missing indexes indicate the range is unbounded on that side.
# For example, if `"Sheet1"` is sheet ID 0, then:
# `Sheet1!A1:A1 == sheet_id: 0,
# start_row_index: 0, end_row_index: 1,
# start_column_index: 0, end_column_index: 1`
# `Sheet1!A3:B4 == sheet_id: 0,
# start_row_index: 2, end_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A:B == sheet_id: 0,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A5:B == sheet_id: 0,
# start_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1 == sheet_id:0`
# The start index must always be less than or equal to the end index.
# If the start index equals the end index, then the range is empty.
# Empty ranges are typically not meaningful and are usually rendered in the
# UI as `#REF!`.
# Corresponds to the JSON property `range`
# @return [Google::Apis::SheetsV4::GridRange]
attr_accessor :range
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@sort_specs = args[:sort_specs] if args.key?(:sort_specs)
@range = args[:range] if args.key?(:range)
end
end
# Merges all cells in the range.
class MergeCellsRequest
include Google::Apis::Core::Hashable
# A range on a sheet.
# All indexes are zero-based.
# Indexes are half open, e.g the start index is inclusive
# and the end index is exclusive -- [start_index, end_index).
# Missing indexes indicate the range is unbounded on that side.
# For example, if `"Sheet1"` is sheet ID 0, then:
# `Sheet1!A1:A1 == sheet_id: 0,
# start_row_index: 0, end_row_index: 1,
# start_column_index: 0, end_column_index: 1`
# `Sheet1!A3:B4 == sheet_id: 0,
# start_row_index: 2, end_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A:B == sheet_id: 0,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A5:B == sheet_id: 0,
# start_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1 == sheet_id:0`
# The start index must always be less than or equal to the end index.
# If the start index equals the end index, then the range is empty.
# Empty ranges are typically not meaningful and are usually rendered in the
# UI as `#REF!`.
# Corresponds to the JSON property `range`
# @return [Google::Apis::SheetsV4::GridRange]
attr_accessor :range
# How the cells should be merged.
# Corresponds to the JSON property `mergeType`
# @return [String]
attr_accessor :merge_type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@range = args[:range] if args.key?(:range)
@merge_type = args[:merge_type] if args.key?(:merge_type)
end
end
# Adds a new protected range.
class AddProtectedRangeRequest
include Google::Apis::Core::Hashable
# A protected range.
# Corresponds to the JSON property `protectedRange`
# @return [Google::Apis::SheetsV4::ProtectedRange]
attr_accessor :protected_range
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@protected_range = args[:protected_range] if args.key?(:protected_range)
end
end
# The request for clearing more than one range of values in a spreadsheet.
class BatchClearValuesRequest
include Google::Apis::Core::Hashable
# The ranges to clear, in A1 notation.
# Corresponds to the JSON property `ranges`
# @return [Array<String>]
attr_accessor :ranges
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@ranges = args[:ranges] if args.key?(:ranges)
end
end
# The result of a filter view being duplicated.
class DuplicateFilterViewResponse
include Google::Apis::Core::Hashable
# A filter view.
# Corresponds to the JSON property `filter`
# @return [Google::Apis::SheetsV4::FilterView]
attr_accessor :filter
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@filter = args[:filter] if args.key?(:filter)
end
end
# The result of duplicating a sheet.
class DuplicateSheetResponse
include Google::Apis::Core::Hashable
# Properties of a sheet.
# Corresponds to the JSON property `properties`
# @return [Google::Apis::SheetsV4::SheetProperties]
attr_accessor :properties
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@properties = args[:properties] if args.key?(:properties)
end
end
# Splits a column of text into multiple columns,
# based on a delimiter in each cell.
class TextToColumnsRequest
include Google::Apis::Core::Hashable
# The delimiter to use. Used only if delimiterType is
# CUSTOM.
# Corresponds to the JSON property `delimiter`
# @return [String]
attr_accessor :delimiter
# A range on a sheet.
# All indexes are zero-based.
# Indexes are half open, e.g the start index is inclusive
# and the end index is exclusive -- [start_index, end_index).
# Missing indexes indicate the range is unbounded on that side.
# For example, if `"Sheet1"` is sheet ID 0, then:
# `Sheet1!A1:A1 == sheet_id: 0,
# start_row_index: 0, end_row_index: 1,
# start_column_index: 0, end_column_index: 1`
# `Sheet1!A3:B4 == sheet_id: 0,
# start_row_index: 2, end_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A:B == sheet_id: 0,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A5:B == sheet_id: 0,
# start_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1 == sheet_id:0`
# The start index must always be less than or equal to the end index.
# If the start index equals the end index, then the range is empty.
# Empty ranges are typically not meaningful and are usually rendered in the
# UI as `#REF!`.
# Corresponds to the JSON property `source`
# @return [Google::Apis::SheetsV4::GridRange]
attr_accessor :source
# The delimiter type to use.
# Corresponds to the JSON property `delimiterType`
# @return [String]
attr_accessor :delimiter_type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@delimiter = args[:delimiter] if args.key?(:delimiter)
@source = args[:source] if args.key?(:source)
@delimiter_type = args[:delimiter_type] if args.key?(:delimiter_type)
end
end
# Clears the basic filter, if any exists on the sheet.
class ClearBasicFilterRequest
include Google::Apis::Core::Hashable
# The sheet ID on which the basic filter should be cleared.
# Corresponds to the JSON property `sheetId`
# @return [Fixnum]
attr_accessor :sheet_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@sheet_id = args[:sheet_id] if args.key?(:sheet_id)
end
end
# The reply for batch updating a spreadsheet.
class BatchUpdateSpreadsheetResponse
include Google::Apis::Core::Hashable
# The reply of the updates. This maps 1:1 with the updates, although
# replies to some requests may be empty.
# Corresponds to the JSON property `replies`
# @return [Array<Google::Apis::SheetsV4::Response>]
attr_accessor :replies
# Resource that represents a spreadsheet.
# Corresponds to the JSON property `updatedSpreadsheet`
# @return [Google::Apis::SheetsV4::Spreadsheet]
attr_accessor :updated_spreadsheet
# The spreadsheet the updates were applied to.
# Corresponds to the JSON property `spreadsheetId`
# @return [String]
attr_accessor :spreadsheet_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@replies = args[:replies] if args.key?(:replies)
@updated_spreadsheet = args[:updated_spreadsheet] if args.key?(:updated_spreadsheet)
@spreadsheet_id = args[:spreadsheet_id] if args.key?(:spreadsheet_id)
end
end
# Removes the banded range with the given ID from the spreadsheet.
class DeleteBandingRequest
include Google::Apis::Core::Hashable
# The ID of the banded range to delete.
# Corresponds to the JSON property `bandedRangeId`
# @return [Fixnum]
attr_accessor :banded_range_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@banded_range_id = args[:banded_range_id] if args.key?(:banded_range_id)
end
end
# The response when updating a range of values in a spreadsheet.
class AppendValuesResponse
include Google::Apis::Core::Hashable
# The response when updating a range of values in a spreadsheet.
# Corresponds to the JSON property `updates`
# @return [Google::Apis::SheetsV4::UpdateValuesResponse]
attr_accessor :updates
# The range (in A1 notation) of the table that values are being appended to
# (before the values were appended).
# Empty if no table was found.
# Corresponds to the JSON property `tableRange`
# @return [String]
attr_accessor :table_range
# The spreadsheet the updates were applied to.
# Corresponds to the JSON property `spreadsheetId`
# @return [String]
attr_accessor :spreadsheet_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@updates = args[:updates] if args.key?(:updates)
@table_range = args[:table_range] if args.key?(:table_range)
@spreadsheet_id = args[:spreadsheet_id] if args.key?(:spreadsheet_id)
end
end
# Moves one or more rows or columns.
class MoveDimensionRequest
include Google::Apis::Core::Hashable
# The zero-based start index of where to move the source data to,
# based on the coordinates *before* the source data is removed
# from the grid. Existing data will be shifted down or right
# (depending on the dimension) to make room for the moved dimensions.
# The source dimensions are removed from the grid, so the
# the data may end up in a different index than specified.
# For example, given `A1..A5` of `0, 1, 2, 3, 4` and wanting to move
# `"1"` and `"2"` to between `"3"` and `"4"`, the source would be
# `ROWS [1..3)`,and the destination index would be `"4"`
# (the zero-based index of row 5).
# The end result would be `A1..A5` of `0, 3, 1, 2, 4`.
# Corresponds to the JSON property `destinationIndex`
# @return [Fixnum]
attr_accessor :destination_index
# A range along a single dimension on a sheet.
# All indexes are zero-based.
# Indexes are half open: the start index is inclusive
# and the end index is exclusive.
# Missing indexes indicate the range is unbounded on that side.
# Corresponds to the JSON property `source`
# @return [Google::Apis::SheetsV4::DimensionRange]
attr_accessor :source
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@destination_index = args[:destination_index] if args.key?(:destination_index)
@source = args[:source] if args.key?(:source)
end
end
# Criteria for showing/hiding rows in a pivot table.
class PivotFilterCriteria
include Google::Apis::Core::Hashable
# Values that should be included. Values not listed here are excluded.
# Corresponds to the JSON property `visibleValues`
# @return [Array<String>]
attr_accessor :visible_values
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@visible_values = args[:visible_values] if args.key?(:visible_values)
end
end
# Adds a filter view.
class AddFilterViewRequest
include Google::Apis::Core::Hashable
# A filter view.
# Corresponds to the JSON property `filter`
# @return [Google::Apis::SheetsV4::FilterView]
attr_accessor :filter
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@filter = args[:filter] if args.key?(:filter)
end
end
# Adds a new conditional format rule at the given index.
# All subsequent rules' indexes are incremented.
class AddConditionalFormatRuleRequest
include Google::Apis::Core::Hashable
# A rule describing a conditional format.
# Corresponds to the JSON property `rule`
# @return [Google::Apis::SheetsV4::ConditionalFormatRule]
attr_accessor :rule
# The zero-based index where the rule should be inserted.
# Corresponds to the JSON property `index`
# @return [Fixnum]
attr_accessor :index
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@rule = args[:rule] if args.key?(:rule)
@index = args[:index] if args.key?(:index)
end
end
# The specifications of a chart.
class ChartSpec
include Google::Apis::Core::Hashable
# A <a href="/chart/interactive/docs/gallery/piechart">pie chart</a>.
# Corresponds to the JSON property `pieChart`
# @return [Google::Apis::SheetsV4::PieChartSpec]
attr_accessor :pie_chart
# The specification for a basic chart. See BasicChartType for the list
# of charts this supports.
# Corresponds to the JSON property `basicChart`
# @return [Google::Apis::SheetsV4::BasicChartSpec]
attr_accessor :basic_chart
# Determines how the charts will use hidden rows or columns.
# Corresponds to the JSON property `hiddenDimensionStrategy`
# @return [String]
attr_accessor :hidden_dimension_strategy
# The title of the chart.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@pie_chart = args[:pie_chart] if args.key?(:pie_chart)
@basic_chart = args[:basic_chart] if args.key?(:basic_chart)
@hidden_dimension_strategy = args[:hidden_dimension_strategy] if args.key?(:hidden_dimension_strategy)
@title = args[:title] if args.key?(:title)
end
end
# The number format of a cell.
class NumberFormat
include Google::Apis::Core::Hashable
# Pattern string used for formatting. If not set, a default pattern based on
# the user's locale will be used if necessary for the given type.
# See the [Date and Number Formats guide](/sheets/guides/formats) for more
# information about the supported patterns.
# Corresponds to the JSON property `pattern`
# @return [String]
attr_accessor :pattern
# The type of the number format.
# When writing, this field must be set.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@pattern = args[:pattern] if args.key?(:pattern)
@type = args[:type] if args.key?(:type)
end
end
# Properties of a sheet.
class SheetProperties
include Google::Apis::Core::Hashable
# The name of the sheet.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
# Represents a color in the RGBA color space. This representation is designed
# for simplicity of conversion to/from color representations in various
# languages over compactness; for example, the fields of this representation
# can be trivially provided to the constructor of "java.awt.Color" in Java; it
# can also be trivially provided to UIColor's "+colorWithRed:green:blue:alpha"
# method in iOS; and, with just a little work, it can be easily formatted into
# a CSS "rgba()" string in JavaScript, as well. Here are some examples:
# Example (Java):
# import com.google.type.Color;
# // ...
# public static java.awt.Color fromProto(Color protocolor) `
# float alpha = protocolor.hasAlpha()
# ? protocolor.getAlpha().getValue()
# : 1.0;
# return new java.awt.Color(
# protocolor.getRed(),
# protocolor.getGreen(),
# protocolor.getBlue(),
# alpha);
# `
# public static Color toProto(java.awt.Color color) `
# float red = (float) color.getRed();
# float green = (float) color.getGreen();
# float blue = (float) color.getBlue();
# float denominator = 255.0;
# Color.Builder resultBuilder =
# Color
# .newBuilder()
# .setRed(red / denominator)
# .setGreen(green / denominator)
# .setBlue(blue / denominator);
# int alpha = color.getAlpha();
# if (alpha != 255) `
# result.setAlpha(
# FloatValue
# .newBuilder()
# .setValue(((float) alpha) / denominator)
# .build());
# `
# return resultBuilder.build();
# `
# // ...
# Example (iOS / Obj-C):
# // ...
# static UIColor* fromProto(Color* protocolor) `
# float red = [protocolor red];
# float green = [protocolor green];
# float blue = [protocolor blue];
# FloatValue* alpha_wrapper = [protocolor alpha];
# float alpha = 1.0;
# if (alpha_wrapper != nil) `
# alpha = [alpha_wrapper value];
# `
# return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
# `
# static Color* toProto(UIColor* color) `
# CGFloat red, green, blue, alpha;
# if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) `
# return nil;
# `
# Color* result = [Color alloc] init];
# [result setRed:red];
# [result setGreen:green];
# [result setBlue:blue];
# if (alpha <= 0.9999) `
# [result setAlpha:floatWrapperWithValue(alpha)];
# `
# [result autorelease];
# return result;
# `
# // ...
# Example (JavaScript):
# // ...
# var protoToCssColor = function(rgb_color) `
# var redFrac = rgb_color.red || 0.0;
# var greenFrac = rgb_color.green || 0.0;
# var blueFrac = rgb_color.blue || 0.0;
# var red = Math.floor(redFrac * 255);
# var green = Math.floor(greenFrac * 255);
# var blue = Math.floor(blueFrac * 255);
# if (!('alpha' in rgb_color)) `
# return rgbToCssColor_(red, green, blue);
# `
# var alphaFrac = rgb_color.alpha.value || 0.0;
# var rgbParams = [red, green, blue].join(',');
# return ['rgba(', rgbParams, ',', alphaFrac, ')'].join('');
# `;
# var rgbToCssColor_ = function(red, green, blue) `
# var rgbNumber = new Number((red << 16) | (green << 8) | blue);
# var hexString = rgbNumber.toString(16);
# var missingZeros = 6 - hexString.length;
# var resultBuilder = ['#'];
# for (var i = 0; i < missingZeros; i++) `
# resultBuilder.push('0');
# `
# resultBuilder.push(hexString);
# return resultBuilder.join('');
# `;
# // ...
# Corresponds to the JSON property `tabColor`
# @return [Google::Apis::SheetsV4::Color]
attr_accessor :tab_color
# The index of the sheet within the spreadsheet.
# When adding or updating sheet properties, if this field
# is excluded then the sheet will be added or moved to the end
# of the sheet list. When updating sheet indices or inserting
# sheets, movement is considered in "before the move" indexes.
# For example, if there were 3 sheets (S1, S2, S3) in order to
# move S1 ahead of S2 the index would have to be set to 2. A sheet
# index update request will be ignored if the requested index is
# identical to the sheets current index or if the requested new
# index is equal to the current sheet index + 1.
# Corresponds to the JSON property `index`
# @return [Fixnum]
attr_accessor :index
# The ID of the sheet. Must be non-negative.
# This field cannot be changed once set.
# Corresponds to the JSON property `sheetId`
# @return [Fixnum]
attr_accessor :sheet_id
# True if the sheet is an RTL sheet instead of an LTR sheet.
# Corresponds to the JSON property `rightToLeft`
# @return [Boolean]
attr_accessor :right_to_left
alias_method :right_to_left?, :right_to_left
# True if the sheet is hidden in the UI, false if it's visible.
# Corresponds to the JSON property `hidden`
# @return [Boolean]
attr_accessor :hidden
alias_method :hidden?, :hidden
# The type of sheet. Defaults to GRID.
# This field cannot be changed once set.
# Corresponds to the JSON property `sheetType`
# @return [String]
attr_accessor :sheet_type
# Properties of a grid.
# Corresponds to the JSON property `gridProperties`
# @return [Google::Apis::SheetsV4::GridProperties]
attr_accessor :grid_properties
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@title = args[:title] if args.key?(:title)
@tab_color = args[:tab_color] if args.key?(:tab_color)
@index = args[:index] if args.key?(:index)
@sheet_id = args[:sheet_id] if args.key?(:sheet_id)
@right_to_left = args[:right_to_left] if args.key?(:right_to_left)
@hidden = args[:hidden] if args.key?(:hidden)
@sheet_type = args[:sheet_type] if args.key?(:sheet_type)
@grid_properties = args[:grid_properties] if args.key?(:grid_properties)
end
end
# Updates properties of dimensions within the specified range.
class UpdateDimensionPropertiesRequest
include Google::Apis::Core::Hashable
# The fields that should be updated. At least one field must be specified.
# The root `properties` is implied and should not be specified.
# A single `"*"` can be used as short-hand for listing every field.
# Corresponds to the JSON property `fields`
# @return [String]
attr_accessor :fields
# Properties about a dimension.
# Corresponds to the JSON property `properties`
# @return [Google::Apis::SheetsV4::DimensionProperties]
attr_accessor :properties
# A range along a single dimension on a sheet.
# All indexes are zero-based.
# Indexes are half open: the start index is inclusive
# and the end index is exclusive.
# Missing indexes indicate the range is unbounded on that side.
# Corresponds to the JSON property `range`
# @return [Google::Apis::SheetsV4::DimensionRange]
attr_accessor :range
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@fields = args[:fields] if args.key?(:fields)
@properties = args[:properties] if args.key?(:properties)
@range = args[:range] if args.key?(:range)
end
end
# A combination of a source range and how to extend that source.
class SourceAndDestination
include Google::Apis::Core::Hashable
# The number of rows or columns that data should be filled into.
# Positive numbers expand beyond the last row or last column
# of the source. Negative numbers expand before the first row
# or first column of the source.
# Corresponds to the JSON property `fillLength`
# @return [Fixnum]
attr_accessor :fill_length
# A range on a sheet.
# All indexes are zero-based.
# Indexes are half open, e.g the start index is inclusive
# and the end index is exclusive -- [start_index, end_index).
# Missing indexes indicate the range is unbounded on that side.
# For example, if `"Sheet1"` is sheet ID 0, then:
# `Sheet1!A1:A1 == sheet_id: 0,
# start_row_index: 0, end_row_index: 1,
# start_column_index: 0, end_column_index: 1`
# `Sheet1!A3:B4 == sheet_id: 0,
# start_row_index: 2, end_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A:B == sheet_id: 0,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A5:B == sheet_id: 0,
# start_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1 == sheet_id:0`
# The start index must always be less than or equal to the end index.
# If the start index equals the end index, then the range is empty.
# Empty ranges are typically not meaningful and are usually rendered in the
# UI as `#REF!`.
# Corresponds to the JSON property `source`
# @return [Google::Apis::SheetsV4::GridRange]
attr_accessor :source
# The dimension that data should be filled into.
# Corresponds to the JSON property `dimension`
# @return [String]
attr_accessor :dimension
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@fill_length = args[:fill_length] if args.key?(:fill_length)
@source = args[:source] if args.key?(:source)
@dimension = args[:dimension] if args.key?(:dimension)
end
end
# A filter view.
class FilterView
include Google::Apis::Core::Hashable
# The criteria for showing/hiding values per column.
# The map's key is the column index, and the value is the criteria for
# that column.
# Corresponds to the JSON property `criteria`
# @return [Hash<String,Google::Apis::SheetsV4::FilterCriteria>]
attr_accessor :criteria
# The name of the filter view.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
# A range on a sheet.
# All indexes are zero-based.
# Indexes are half open, e.g the start index is inclusive
# and the end index is exclusive -- [start_index, end_index).
# Missing indexes indicate the range is unbounded on that side.
# For example, if `"Sheet1"` is sheet ID 0, then:
# `Sheet1!A1:A1 == sheet_id: 0,
# start_row_index: 0, end_row_index: 1,
# start_column_index: 0, end_column_index: 1`
# `Sheet1!A3:B4 == sheet_id: 0,
# start_row_index: 2, end_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A:B == sheet_id: 0,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A5:B == sheet_id: 0,
# start_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1 == sheet_id:0`
# The start index must always be less than or equal to the end index.
# If the start index equals the end index, then the range is empty.
# Empty ranges are typically not meaningful and are usually rendered in the
# UI as `#REF!`.
# Corresponds to the JSON property `range`
# @return [Google::Apis::SheetsV4::GridRange]
attr_accessor :range
# The sort order per column. Later specifications are used when values
# are equal in the earlier specifications.
# Corresponds to the JSON property `sortSpecs`
# @return [Array<Google::Apis::SheetsV4::SortSpec>]
attr_accessor :sort_specs
# The named range this filter view is backed by, if any.
# When writing, only one of range or named_range_id
# may be set.
# Corresponds to the JSON property `namedRangeId`
# @return [String]
attr_accessor :named_range_id
# The ID of the filter view.
# Corresponds to the JSON property `filterViewId`
# @return [Fixnum]
attr_accessor :filter_view_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@criteria = args[:criteria] if args.key?(:criteria)
@title = args[:title] if args.key?(:title)
@range = args[:range] if args.key?(:range)
@sort_specs = args[:sort_specs] if args.key?(:sort_specs)
@named_range_id = args[:named_range_id] if args.key?(:named_range_id)
@filter_view_id = args[:filter_view_id] if args.key?(:filter_view_id)
end
end
# Properties referring a single dimension (either row or column). If both
# BandedRange.row_properties and BandedRange.column_properties are
# set, the fill colors are applied to cells according to the following rules:
# * header_color and footer_color take priority over band colors.
# * first_band_color takes priority over second_band_color.
# * row_properties takes priority over column_properties.
# For example, the first row color takes priority over the first column
# color, but the first column color takes priority over the second row color.
# Similarly, the row header takes priority over the column header in the
# top left cell, but the column header takes priority over the first row
# color if the row header is not set.
class BandingProperties
include Google::Apis::Core::Hashable
# Represents a color in the RGBA color space. This representation is designed
# for simplicity of conversion to/from color representations in various
# languages over compactness; for example, the fields of this representation
# can be trivially provided to the constructor of "java.awt.Color" in Java; it
# can also be trivially provided to UIColor's "+colorWithRed:green:blue:alpha"
# method in iOS; and, with just a little work, it can be easily formatted into
# a CSS "rgba()" string in JavaScript, as well. Here are some examples:
# Example (Java):
# import com.google.type.Color;
# // ...
# public static java.awt.Color fromProto(Color protocolor) `
# float alpha = protocolor.hasAlpha()
# ? protocolor.getAlpha().getValue()
# : 1.0;
# return new java.awt.Color(
# protocolor.getRed(),
# protocolor.getGreen(),
# protocolor.getBlue(),
# alpha);
# `
# public static Color toProto(java.awt.Color color) `
# float red = (float) color.getRed();
# float green = (float) color.getGreen();
# float blue = (float) color.getBlue();
# float denominator = 255.0;
# Color.Builder resultBuilder =
# Color
# .newBuilder()
# .setRed(red / denominator)
# .setGreen(green / denominator)
# .setBlue(blue / denominator);
# int alpha = color.getAlpha();
# if (alpha != 255) `
# result.setAlpha(
# FloatValue
# .newBuilder()
# .setValue(((float) alpha) / denominator)
# .build());
# `
# return resultBuilder.build();
# `
# // ...
# Example (iOS / Obj-C):
# // ...
# static UIColor* fromProto(Color* protocolor) `
# float red = [protocolor red];
# float green = [protocolor green];
# float blue = [protocolor blue];
# FloatValue* alpha_wrapper = [protocolor alpha];
# float alpha = 1.0;
# if (alpha_wrapper != nil) `
# alpha = [alpha_wrapper value];
# `
# return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
# `
# static Color* toProto(UIColor* color) `
# CGFloat red, green, blue, alpha;
# if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) `
# return nil;
# `
# Color* result = [Color alloc] init];
# [result setRed:red];
# [result setGreen:green];
# [result setBlue:blue];
# if (alpha <= 0.9999) `
# [result setAlpha:floatWrapperWithValue(alpha)];
# `
# [result autorelease];
# return result;
# `
# // ...
# Example (JavaScript):
# // ...
# var protoToCssColor = function(rgb_color) `
# var redFrac = rgb_color.red || 0.0;
# var greenFrac = rgb_color.green || 0.0;
# var blueFrac = rgb_color.blue || 0.0;
# var red = Math.floor(redFrac * 255);
# var green = Math.floor(greenFrac * 255);
# var blue = Math.floor(blueFrac * 255);
# if (!('alpha' in rgb_color)) `
# return rgbToCssColor_(red, green, blue);
# `
# var alphaFrac = rgb_color.alpha.value || 0.0;
# var rgbParams = [red, green, blue].join(',');
# return ['rgba(', rgbParams, ',', alphaFrac, ')'].join('');
# `;
# var rgbToCssColor_ = function(red, green, blue) `
# var rgbNumber = new Number((red << 16) | (green << 8) | blue);
# var hexString = rgbNumber.toString(16);
# var missingZeros = 6 - hexString.length;
# var resultBuilder = ['#'];
# for (var i = 0; i < missingZeros; i++) `
# resultBuilder.push('0');
# `
# resultBuilder.push(hexString);
# return resultBuilder.join('');
# `;
# // ...
# Corresponds to the JSON property `secondBandColor`
# @return [Google::Apis::SheetsV4::Color]
attr_accessor :second_band_color
# Represents a color in the RGBA color space. This representation is designed
# for simplicity of conversion to/from color representations in various
# languages over compactness; for example, the fields of this representation
# can be trivially provided to the constructor of "java.awt.Color" in Java; it
# can also be trivially provided to UIColor's "+colorWithRed:green:blue:alpha"
# method in iOS; and, with just a little work, it can be easily formatted into
# a CSS "rgba()" string in JavaScript, as well. Here are some examples:
# Example (Java):
# import com.google.type.Color;
# // ...
# public static java.awt.Color fromProto(Color protocolor) `
# float alpha = protocolor.hasAlpha()
# ? protocolor.getAlpha().getValue()
# : 1.0;
# return new java.awt.Color(
# protocolor.getRed(),
# protocolor.getGreen(),
# protocolor.getBlue(),
# alpha);
# `
# public static Color toProto(java.awt.Color color) `
# float red = (float) color.getRed();
# float green = (float) color.getGreen();
# float blue = (float) color.getBlue();
# float denominator = 255.0;
# Color.Builder resultBuilder =
# Color
# .newBuilder()
# .setRed(red / denominator)
# .setGreen(green / denominator)
# .setBlue(blue / denominator);
# int alpha = color.getAlpha();
# if (alpha != 255) `
# result.setAlpha(
# FloatValue
# .newBuilder()
# .setValue(((float) alpha) / denominator)
# .build());
# `
# return resultBuilder.build();
# `
# // ...
# Example (iOS / Obj-C):
# // ...
# static UIColor* fromProto(Color* protocolor) `
# float red = [protocolor red];
# float green = [protocolor green];
# float blue = [protocolor blue];
# FloatValue* alpha_wrapper = [protocolor alpha];
# float alpha = 1.0;
# if (alpha_wrapper != nil) `
# alpha = [alpha_wrapper value];
# `
# return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
# `
# static Color* toProto(UIColor* color) `
# CGFloat red, green, blue, alpha;
# if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) `
# return nil;
# `
# Color* result = [Color alloc] init];
# [result setRed:red];
# [result setGreen:green];
# [result setBlue:blue];
# if (alpha <= 0.9999) `
# [result setAlpha:floatWrapperWithValue(alpha)];
# `
# [result autorelease];
# return result;
# `
# // ...
# Example (JavaScript):
# // ...
# var protoToCssColor = function(rgb_color) `
# var redFrac = rgb_color.red || 0.0;
# var greenFrac = rgb_color.green || 0.0;
# var blueFrac = rgb_color.blue || 0.0;
# var red = Math.floor(redFrac * 255);
# var green = Math.floor(greenFrac * 255);
# var blue = Math.floor(blueFrac * 255);
# if (!('alpha' in rgb_color)) `
# return rgbToCssColor_(red, green, blue);
# `
# var alphaFrac = rgb_color.alpha.value || 0.0;
# var rgbParams = [red, green, blue].join(',');
# return ['rgba(', rgbParams, ',', alphaFrac, ')'].join('');
# `;
# var rgbToCssColor_ = function(red, green, blue) `
# var rgbNumber = new Number((red << 16) | (green << 8) | blue);
# var hexString = rgbNumber.toString(16);
# var missingZeros = 6 - hexString.length;
# var resultBuilder = ['#'];
# for (var i = 0; i < missingZeros; i++) `
# resultBuilder.push('0');
# `
# resultBuilder.push(hexString);
# return resultBuilder.join('');
# `;
# // ...
# Corresponds to the JSON property `footerColor`
# @return [Google::Apis::SheetsV4::Color]
attr_accessor :footer_color
# Represents a color in the RGBA color space. This representation is designed
# for simplicity of conversion to/from color representations in various
# languages over compactness; for example, the fields of this representation
# can be trivially provided to the constructor of "java.awt.Color" in Java; it
# can also be trivially provided to UIColor's "+colorWithRed:green:blue:alpha"
# method in iOS; and, with just a little work, it can be easily formatted into
# a CSS "rgba()" string in JavaScript, as well. Here are some examples:
# Example (Java):
# import com.google.type.Color;
# // ...
# public static java.awt.Color fromProto(Color protocolor) `
# float alpha = protocolor.hasAlpha()
# ? protocolor.getAlpha().getValue()
# : 1.0;
# return new java.awt.Color(
# protocolor.getRed(),
# protocolor.getGreen(),
# protocolor.getBlue(),
# alpha);
# `
# public static Color toProto(java.awt.Color color) `
# float red = (float) color.getRed();
# float green = (float) color.getGreen();
# float blue = (float) color.getBlue();
# float denominator = 255.0;
# Color.Builder resultBuilder =
# Color
# .newBuilder()
# .setRed(red / denominator)
# .setGreen(green / denominator)
# .setBlue(blue / denominator);
# int alpha = color.getAlpha();
# if (alpha != 255) `
# result.setAlpha(
# FloatValue
# .newBuilder()
# .setValue(((float) alpha) / denominator)
# .build());
# `
# return resultBuilder.build();
# `
# // ...
# Example (iOS / Obj-C):
# // ...
# static UIColor* fromProto(Color* protocolor) `
# float red = [protocolor red];
# float green = [protocolor green];
# float blue = [protocolor blue];
# FloatValue* alpha_wrapper = [protocolor alpha];
# float alpha = 1.0;
# if (alpha_wrapper != nil) `
# alpha = [alpha_wrapper value];
# `
# return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
# `
# static Color* toProto(UIColor* color) `
# CGFloat red, green, blue, alpha;
# if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) `
# return nil;
# `
# Color* result = [Color alloc] init];
# [result setRed:red];
# [result setGreen:green];
# [result setBlue:blue];
# if (alpha <= 0.9999) `
# [result setAlpha:floatWrapperWithValue(alpha)];
# `
# [result autorelease];
# return result;
# `
# // ...
# Example (JavaScript):
# // ...
# var protoToCssColor = function(rgb_color) `
# var redFrac = rgb_color.red || 0.0;
# var greenFrac = rgb_color.green || 0.0;
# var blueFrac = rgb_color.blue || 0.0;
# var red = Math.floor(redFrac * 255);
# var green = Math.floor(greenFrac * 255);
# var blue = Math.floor(blueFrac * 255);
# if (!('alpha' in rgb_color)) `
# return rgbToCssColor_(red, green, blue);
# `
# var alphaFrac = rgb_color.alpha.value || 0.0;
# var rgbParams = [red, green, blue].join(',');
# return ['rgba(', rgbParams, ',', alphaFrac, ')'].join('');
# `;
# var rgbToCssColor_ = function(red, green, blue) `
# var rgbNumber = new Number((red << 16) | (green << 8) | blue);
# var hexString = rgbNumber.toString(16);
# var missingZeros = 6 - hexString.length;
# var resultBuilder = ['#'];
# for (var i = 0; i < missingZeros; i++) `
# resultBuilder.push('0');
# `
# resultBuilder.push(hexString);
# return resultBuilder.join('');
# `;
# // ...
# Corresponds to the JSON property `headerColor`
# @return [Google::Apis::SheetsV4::Color]
attr_accessor :header_color
# Represents a color in the RGBA color space. This representation is designed
# for simplicity of conversion to/from color representations in various
# languages over compactness; for example, the fields of this representation
# can be trivially provided to the constructor of "java.awt.Color" in Java; it
# can also be trivially provided to UIColor's "+colorWithRed:green:blue:alpha"
# method in iOS; and, with just a little work, it can be easily formatted into
# a CSS "rgba()" string in JavaScript, as well. Here are some examples:
# Example (Java):
# import com.google.type.Color;
# // ...
# public static java.awt.Color fromProto(Color protocolor) `
# float alpha = protocolor.hasAlpha()
# ? protocolor.getAlpha().getValue()
# : 1.0;
# return new java.awt.Color(
# protocolor.getRed(),
# protocolor.getGreen(),
# protocolor.getBlue(),
# alpha);
# `
# public static Color toProto(java.awt.Color color) `
# float red = (float) color.getRed();
# float green = (float) color.getGreen();
# float blue = (float) color.getBlue();
# float denominator = 255.0;
# Color.Builder resultBuilder =
# Color
# .newBuilder()
# .setRed(red / denominator)
# .setGreen(green / denominator)
# .setBlue(blue / denominator);
# int alpha = color.getAlpha();
# if (alpha != 255) `
# result.setAlpha(
# FloatValue
# .newBuilder()
# .setValue(((float) alpha) / denominator)
# .build());
# `
# return resultBuilder.build();
# `
# // ...
# Example (iOS / Obj-C):
# // ...
# static UIColor* fromProto(Color* protocolor) `
# float red = [protocolor red];
# float green = [protocolor green];
# float blue = [protocolor blue];
# FloatValue* alpha_wrapper = [protocolor alpha];
# float alpha = 1.0;
# if (alpha_wrapper != nil) `
# alpha = [alpha_wrapper value];
# `
# return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
# `
# static Color* toProto(UIColor* color) `
# CGFloat red, green, blue, alpha;
# if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) `
# return nil;
# `
# Color* result = [Color alloc] init];
# [result setRed:red];
# [result setGreen:green];
# [result setBlue:blue];
# if (alpha <= 0.9999) `
# [result setAlpha:floatWrapperWithValue(alpha)];
# `
# [result autorelease];
# return result;
# `
# // ...
# Example (JavaScript):
# // ...
# var protoToCssColor = function(rgb_color) `
# var redFrac = rgb_color.red || 0.0;
# var greenFrac = rgb_color.green || 0.0;
# var blueFrac = rgb_color.blue || 0.0;
# var red = Math.floor(redFrac * 255);
# var green = Math.floor(greenFrac * 255);
# var blue = Math.floor(blueFrac * 255);
# if (!('alpha' in rgb_color)) `
# return rgbToCssColor_(red, green, blue);
# `
# var alphaFrac = rgb_color.alpha.value || 0.0;
# var rgbParams = [red, green, blue].join(',');
# return ['rgba(', rgbParams, ',', alphaFrac, ')'].join('');
# `;
# var rgbToCssColor_ = function(red, green, blue) `
# var rgbNumber = new Number((red << 16) | (green << 8) | blue);
# var hexString = rgbNumber.toString(16);
# var missingZeros = 6 - hexString.length;
# var resultBuilder = ['#'];
# for (var i = 0; i < missingZeros; i++) `
# resultBuilder.push('0');
# `
# resultBuilder.push(hexString);
# return resultBuilder.join('');
# `;
# // ...
# Corresponds to the JSON property `firstBandColor`
# @return [Google::Apis::SheetsV4::Color]
attr_accessor :first_band_color
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@second_band_color = args[:second_band_color] if args.key?(:second_band_color)
@footer_color = args[:footer_color] if args.key?(:footer_color)
@header_color = args[:header_color] if args.key?(:header_color)
@first_band_color = args[:first_band_color] if args.key?(:first_band_color)
end
end
# The result of adding a new protected range.
class AddProtectedRangeResponse
include Google::Apis::Core::Hashable
# A protected range.
# Corresponds to the JSON property `protectedRange`
# @return [Google::Apis::SheetsV4::ProtectedRange]
attr_accessor :protected_range
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@protected_range = args[:protected_range] if args.key?(:protected_range)
end
end
# The default filter associated with a sheet.
class BasicFilter
include Google::Apis::Core::Hashable
# A range on a sheet.
# All indexes are zero-based.
# Indexes are half open, e.g the start index is inclusive
# and the end index is exclusive -- [start_index, end_index).
# Missing indexes indicate the range is unbounded on that side.
# For example, if `"Sheet1"` is sheet ID 0, then:
# `Sheet1!A1:A1 == sheet_id: 0,
# start_row_index: 0, end_row_index: 1,
# start_column_index: 0, end_column_index: 1`
# `Sheet1!A3:B4 == sheet_id: 0,
# start_row_index: 2, end_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A:B == sheet_id: 0,
# start_column_index: 0, end_column_index: 2`
# `Sheet1!A5:B == sheet_id: 0,
# start_row_index: 4,
# start_column_index: 0, end_column_index: 2`
# `Sheet1 == sheet_id:0`
# The start index must always be less than or equal to the end index.
# If the start index equals the end index, then the range is empty.
# Empty ranges are typically not meaningful and are usually rendered in the
# UI as `#REF!`.
# Corresponds to the JSON property `range`
# @return [Google::Apis::SheetsV4::GridRange]
attr_accessor :range
# The criteria for showing/hiding values per column.
# The map's key is the column index, and the value is the criteria for
# that column.
# Corresponds to the JSON property `criteria`
# @return [Hash<String,Google::Apis::SheetsV4::FilterCriteria>]
attr_accessor :criteria
# The sort order per column. Later specifications are used when values
# are equal in the earlier specifications.
# Corresponds to the JSON property `sortSpecs`
# @return [Array<Google::Apis::SheetsV4::SortSpec>]
attr_accessor :sort_specs
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@range = args[:range] if args.key?(:range)
@criteria = args[:criteria] if args.key?(:criteria)
@sort_specs = args[:sort_specs] if args.key?(:sort_specs)
end
end
end
end
end
| 39.974407 | 133 | 0.602513 |
bb3bdf7c215e43711925eafb4282de461c365b2d | 706 | require 'spec_helper'
describe Projects::BranchesController, '(JavaScript fixtures)', type: :controller do
include JavaScriptFixturesHelpers
let(:admin) { create(:admin) }
let(:namespace) { create(:namespace, name: 'frontend-fixtures' )}
let(:project) { create(:project, :repository, namespace: namespace, path: 'branches-project') }
render_views
before(:all) do
clean_frontend_fixtures('branches/')
end
before do
sign_in(admin)
end
it 'branches/new_branch.html.raw' do |example|
get :new,
namespace_id: project.namespace.to_param,
project_id: project
expect(response).to be_success
store_frontend_fixture(response, example.description)
end
end
| 24.344828 | 97 | 0.720963 |
bb0cdb2eae54edb7de3170311154ddb2dcfd3967 | 129 | require 'rails_helper'
RSpec.describe ClearVideoJob, type: :job do
pending "add some examples to (or delete) #{__FILE__}"
end
| 21.5 | 56 | 0.751938 |
7a85e250e7faac6183dd16e56f5ce6a6ff113c13 | 632 | require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')
describe "posts/edit.html.haml" do
before(:each) do
@post = assign(:post, stub_model(Post,
:new_record? => false,
:title => "MyString",
:body => "MyText"
))
end
it "renders the edit post form" do
render
# Run the generator again with the --webrat-matchers flag if you want to use webrat matchers
assert_select "form", :action => post_path(@post), :method => "post" do
assert_select "input#post_title", :name => "post[title]"
assert_select "textarea#post_body", :name => "post[body]"
end
end
end
| 28.727273 | 96 | 0.640823 |
fff762be5b511fb1bd2c6334d65e6d680f0f156b | 539 | cask 'trufont' do
version '0.4.0'
sha256 '05a3b3b9b9188dfe7af9fc7c3d19dc301e7c877ec249dce7f01ac183e7a8af27'
# github.com/trufont/trufont was verified as official when first introduced to the cask
url "https://github.com/trufont/trufont/releases/download/#{version}/TruFont.app.zip"
appcast 'https://github.com/trufont/trufont/releases.atom',
checkpoint: '0d89b0382b94ce03d1b09b053773413259850682263fe0f0fe06b1c3efd240fa'
name 'TruFont'
homepage 'https://trufont.github.io/'
license :oss
app 'TruFont.app'
end
| 35.933333 | 89 | 0.77551 |
395c50b5cc600dd8afd868e869144d5a65337424 | 1,365 | #
# This class was auto-generated from the API references found at
# https://epayments-api.developer-ingenico.com/s2sapi/v1/
#
require 'ingenico/connect/sdk/data_object'
module Ingenico::Connect::SDK
module Domain
module Payment
# @attr [String] display_name
# @attr [String] integration_type
# @attr [String] virtual_payment_address
class RedirectPaymentProduct4101SpecificInput < Ingenico::Connect::SDK::DataObject
attr_accessor :display_name
attr_accessor :integration_type
attr_accessor :virtual_payment_address
# @return (Hash)
def to_h
hash = super
hash['displayName'] = @display_name unless @display_name.nil?
hash['integrationType'] = @integration_type unless @integration_type.nil?
hash['virtualPaymentAddress'] = @virtual_payment_address unless @virtual_payment_address.nil?
hash
end
def from_hash(hash)
super
if hash.has_key? 'displayName'
@display_name = hash['displayName']
end
if hash.has_key? 'integrationType'
@integration_type = hash['integrationType']
end
if hash.has_key? 'virtualPaymentAddress'
@virtual_payment_address = hash['virtualPaymentAddress']
end
end
end
end
end
end
| 29.042553 | 103 | 0.649817 |
bb2e217de18329bfc4b3c60c56743674344e7373 | 291 | class UseTextDatatypeForTitleAndEntryId < ActiveRecord::Migration[5.1]
def up
change_column :stories, :title, :text
change_column :stories, :entry_id, :text
end
def self.down
change_column :stories, :title, :string
change_column :stories, :entry_id, :string
end
end
| 24.25 | 70 | 0.728522 |
087e344154222f9f846e3193780e6ba5114526a3 | 727 | module WWW
class Mechanize
class Util
class << self
def build_query_string(parameters)
parameters.map { |k,v|
k &&
[WEBrick::HTTPUtils.escape_form(k.to_s),
WEBrick::HTTPUtils.escape_form(v.to_s)].join("=")
}.compact.join('&')
end
def html_unescape(s)
return s unless s
s.gsub(/&(\w+|#[0-9]+);/) { |match|
number = case match
when /&(\w+);/
Mechanize.html_parser::NamedCharacters[$1]
when /&#([0-9]+);/
$1.to_i
end
number ? ([number].pack('U') rescue match) : match
}
end
end
end
end
end
| 24.233333 | 65 | 0.456671 |
218b8f4cbc06fc7e837a6905c6ba75c7027014d0 | 1,341 | require_relative 'lib/rentdynamics/version'
Gem::Specification.new do |spec|
spec.name = "rentdynamics"
spec.version = RentDynamics::VERSION
spec.authors = ["Levicus"]
spec.email = ["[email protected]"]
spec.summary = "Used to interact with the rentdynamics api"
spec.description = "Used to interact with the rentdynamics api"
spec.homepage = "https://www.rentdynamics.com"
spec.license = "MIT"
spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
spec.metadata["allowed_push_host"] = "https://rubygems.org"
spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["source_code_uri"] = "https://github.com/RentDynamics/rentdynamics-rb"
spec.metadata["changelog_uri"] = "https://github.com/RentDynamics/rentdynamics-rb/CHANGELOG.md"
# Specify which files should be added to the gem when it is released.
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
`git ls-files -z`.split("\x0").reject { |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 "rspec", "~> 3.2"
end
| 41.90625 | 97 | 0.674124 |
ab6491dd1f56b88b86903c027c317373a140b451 | 848 | require File.join(Rails.root, "script", "migrations", "policy_hbx_enrollment_creator")
require File.join(Rails.root, "app", "models", "queries", "policies_with_no_hbx_enrollment")
require File.join(Rails.root, "app", "models", "queries", "family_with_given_policy")
@@logger = Logger.new("#{Rails.root}/log/policy_hbx_enrollment_creator_#{Time.now.to_s.gsub(' ','')}.log")
policies = Queries::PoliciesWithNoFamilies.new.execute
policies.each do |policy|
begin
family = FamilyWithGivenPolicy.new(policy.id).execute
if family.nil?
@@logger.info "#{DateTime.now.to_s} policy.id:#{policy.id} has no family to belong to"
next
end
family = PolicyHbxEnrollmentCreator.new(policy, family).create
rescue Exception=>e
@@logger.info "#{DateTime.now.to_s} policy.id:#{policy.id} error message:#{e.message}"
end
end
| 33.92 | 106 | 0.721698 |
f8c1532bbb5454c0f1f8d4a19af3249725d58d6b | 2,154 | require 'veewee/provider/core/helper/ssh'
module Veewee
module Provider
module Core
module BoxCommand
def ssh_command_string
"ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -p #{ssh_options[:port]} -l #{definition.ssh_user} #{self.ip_address}"
end
def winrm_command_string
"knife winrm -m #{self.ip_address} -P #{winrm_options[:port]} -x #{definition.winrm_user}" +
" -P #{definition.winrm_password} COMMAND"
end
def exec(command,options={})
raise Veewee::Error,"Box is not running" unless self.running?
if definition.winrm_user && definition.winrm_password
begin
new_options=winrm_options.merge(options)
self.when_winrm_login_works(self.ip_address,winrm_options.merge(options)) do
result = self.winrm_execute(self.ip_address,command,new_options)
return result
end
rescue RuntimeError => ex
env.ui.error "Error executing command #{command} : #{ex}"
raise Veewee::WinrmError, ex
end
else # definition.ssh_user && definition.ssh_password
begin
new_options=ssh_options.merge(options)
self.when_ssh_login_works(self.ip_address,new_options) do
begin
env.logger.info "About to execute remote command #{command} on box #{name} - #{self.ip_address} - #{new_options}"
result=self.ssh_execute(self.ip_address,command,new_options)
return result
rescue RuntimeError => ex
env.ui.error "Error executing command #{command} : #{ex}"
raise Veewee::SshError, ex
end
end
rescue Net::SSH::AuthenticationFailed => ex # may want to catch winrm auth fails as well
env.ui.error "Authentication failure"
raise Veewee::SshError, "Authentication failure\n"+ex.inspect
end
end
end
end # Module
end # Module
end # Module
end # Module
| 39.888889 | 144 | 0.593779 |
3898277f6563b9e08504006851066111b8ec0e51 | 208 | module Epiphany
class Entity
attr_accessor :type, :phrase, :metadata
def initialize(type, phrase, **metadata)
@type = type
@phrase = phrase
@metadata = metadata
end
end
end
| 17.333333 | 44 | 0.634615 |
018975382aea13df7db4d78603bcfc8e44aad72c | 128 | class VisitOccurrence < ApplicationRecord
self.table_name = 'visit_occurrence'
self.primary_key = 'visit_occurrence_id'
end
| 25.6 | 42 | 0.8125 |
6a4be1fa072cc3e4709a0e16ed4c3d60c15abd3a | 13,367 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Auto-DevOps.gitlab-ci.yml' do
using RSpec::Parameterized::TableSyntax
subject(:template) { Gitlab::Template::GitlabCiYmlTemplate.find('Auto-DevOps') }
where(:default_branch) do
%w[master main]
end
with_them do
describe 'the created pipeline' do
let(:pipeline_branch) { default_branch }
let(:project) { create(:project, :auto_devops, :custom_repo, files: { 'README.md' => '' }) }
let(:user) { project.first_owner }
let(:service) { Ci::CreatePipelineService.new(project, user, ref: pipeline_branch ) }
let(:pipeline) { service.execute!(:push).payload }
let(:build_names) { pipeline.builds.pluck(:name) }
before do
stub_application_setting(default_branch_name: default_branch)
stub_ci_pipeline_yaml_file(template.content)
allow_any_instance_of(Ci::BuildScheduleWorker).to receive(:perform).and_return(true)
end
shared_examples 'no Kubernetes deployment job' do
it 'does not create any Kubernetes deployment-related builds' do
expect(build_names).not_to include('production')
expect(build_names).not_to include('production_manual')
expect(build_names).not_to include('staging')
expect(build_names).not_to include('canary')
expect(build_names).not_to include('review')
expect(build_names).not_to include(a_string_matching(/rollout \d+%/))
expect(build_names).not_to include(a_string_matching(/helm-2to3\d+%/))
end
end
it 'creates a build and a test job' do
expect(build_names).to include('build', 'test')
end
context 'when the project is set for deployment to AWS' do
let(:platform_value) { 'ECS' }
let(:review_prod_build_names) { build_names.select {|n| n.include?('review') || n.include?('production')} }
before do
create(:ci_variable, project: project, key: 'AUTO_DEVOPS_PLATFORM_TARGET', value: platform_value)
end
shared_examples 'no ECS job when AUTO_DEVOPS_PLATFORM_TARGET is not present' do |job_name|
context 'when AUTO_DEVOPS_PLATFORM_TARGET is nil' do
let(:platform_value) { nil }
it 'does not trigger the job' do
expect(build_names).not_to include(job_name)
end
end
context 'when AUTO_DEVOPS_PLATFORM_TARGET is empty' do
let(:platform_value) { '' }
it 'does not trigger the job' do
expect(build_names).not_to include(job_name)
end
end
end
it_behaves_like 'no Kubernetes deployment job'
it_behaves_like 'no ECS job when AUTO_DEVOPS_PLATFORM_TARGET is not present' do
let(:job_name) { 'production_ecs' }
end
it 'creates an ECS deployment job for production only' do
expect(review_prod_build_names).to contain_exactly('production_ecs')
end
context 'with FARGATE as a launch type' do
let(:platform_value) { 'FARGATE' }
it 'creates a FARGATE deployment job for production only' do
expect(review_prod_build_names).to contain_exactly('production_fargate')
end
end
context 'and we are not on the default branch' do
let(:platform_value) { 'ECS' }
let(:pipeline_branch) { 'patch-1' }
before do
project.repository.create_branch(pipeline_branch, default_branch)
end
%w(review_ecs review_fargate).each do |job|
it_behaves_like 'no ECS job when AUTO_DEVOPS_PLATFORM_TARGET is not present' do
let(:job_name) { job }
end
end
it 'creates an ECS deployment job for review only' do
expect(review_prod_build_names).to contain_exactly('review_ecs', 'stop_review_ecs')
end
context 'with FARGATE as a launch type' do
let(:platform_value) { 'FARGATE' }
it 'creates an FARGATE deployment job for review only' do
expect(review_prod_build_names).to contain_exactly('review_fargate', 'stop_review_fargate')
end
end
end
context 'and when the project has an active cluster' do
let(:cluster) { create(:cluster, :project, :provided_by_gcp, projects: [project]) }
before do
allow(cluster).to receive(:active?).and_return(true)
end
context 'on default branch' do
it 'triggers the deployment to Kubernetes, not to ECS' do
expect(build_names).not_to include('review')
expect(build_names).to include('production')
expect(build_names).not_to include('production_ecs')
expect(build_names).not_to include('review_ecs')
end
end
end
context 'when the platform target is EC2' do
let(:platform_value) { 'EC2' }
it 'contains the build_artifact job, not the build job' do
expect(build_names).to include('build_artifact')
expect(build_names).not_to include('build')
end
end
end
context 'when the project has no active cluster' do
it 'only creates a build and a test stage' do
expect(pipeline.stages_names).to eq(%w(build test))
end
it_behaves_like 'no Kubernetes deployment job'
end
shared_examples 'pipeline with Kubernetes jobs' do
describe 'deployment-related builds' do
context 'on default branch' do
it 'does not include rollout jobs besides production' do
expect(build_names).to include('production')
expect(build_names).not_to include('production_manual')
expect(build_names).not_to include('staging')
expect(build_names).not_to include('canary')
expect(build_names).not_to include('review')
expect(build_names).not_to include(a_string_matching(/rollout \d+%/))
end
context 'when STAGING_ENABLED=1' do
before do
create(:ci_variable, project: project, key: 'STAGING_ENABLED', value: '1')
end
it 'includes a staging job and a production_manual job' do
expect(build_names).not_to include('production')
expect(build_names).to include('production_manual')
expect(build_names).to include('staging')
expect(build_names).not_to include('canary')
expect(build_names).not_to include('review')
expect(build_names).not_to include(a_string_matching(/rollout \d+%/))
end
end
context 'when CANARY_ENABLED=1' do
before do
create(:ci_variable, project: project, key: 'CANARY_ENABLED', value: '1')
end
it 'includes a canary job and a production_manual job' do
expect(build_names).not_to include('production')
expect(build_names).to include('production_manual')
expect(build_names).not_to include('staging')
expect(build_names).to include('canary')
expect(build_names).not_to include('review')
expect(build_names).not_to include(a_string_matching(/rollout \d+%/))
end
end
context 'when MIGRATE_HELM_2TO3=true' do
before do
create(:ci_variable, project: project, key: 'MIGRATE_HELM_2TO3', value: 'true')
end
it 'includes a helm-2to3:migrate and a helm-2to3:cleanup job' do
expect(build_names).to include('production:helm-2to3:migrate')
expect(build_names).to include('production:helm-2to3:cleanup')
end
end
end
context 'outside of default branch' do
let(:pipeline_branch) { 'patch-1' }
before do
project.repository.create_branch(pipeline_branch, default_branch)
end
it 'does not include rollout jobs besides review' do
expect(build_names).not_to include('production')
expect(build_names).not_to include('production_manual')
expect(build_names).not_to include('staging')
expect(build_names).not_to include('canary')
expect(build_names).to include('review')
expect(build_names).not_to include(a_string_matching(/rollout \d+%/))
end
context 'when MIGRATE_HELM_2TO3=true' do
before do
create(:ci_variable, project: project, key: 'MIGRATE_HELM_2TO3', value: 'true')
end
it 'includes a helm-2to3:migrate and a helm-2to3:cleanup job' do
expect(build_names).to include('review:helm-2to3:migrate')
expect(build_names).to include('review:helm-2to3:cleanup')
end
end
end
end
end
context 'when a cluster is attached' do
before do
create(:cluster, :project, :provided_by_gcp, projects: [project])
end
it_behaves_like 'pipeline with Kubernetes jobs'
end
context 'when project has an Agent is present' do
before do
create(:cluster_agent, project: project)
end
it_behaves_like 'pipeline with Kubernetes jobs'
end
end
describe 'buildpack detection' do
using RSpec::Parameterized::TableSyntax
where(:case_name, :files, :variables, :include_build_names, :not_include_build_names) do
'No match' | { 'README.md' => '' } | {} | %w() | %w(build test)
'Buildpack' | { 'README.md' => '' } | { 'BUILDPACK_URL' => 'http://example.com' } | %w(build test) | %w()
'Explicit set' | { 'README.md' => '' } | { 'AUTO_DEVOPS_EXPLICITLY_ENABLED' => '1' } | %w(build test) | %w()
'Explicit unset' | { 'README.md' => '' } | { 'AUTO_DEVOPS_EXPLICITLY_ENABLED' => '0' } | %w() | %w(build test)
'DOCKERFILE_PATH' | { 'README.md' => '' } | { 'DOCKERFILE_PATH' => 'Docker.file' } | %w(build test) | %w()
'Dockerfile' | { 'Dockerfile' => '' } | {} | %w(build test) | %w()
'Clojure' | { 'project.clj' => '' } | {} | %w(build test) | %w()
'Go modules' | { 'go.mod' => '' } | {} | %w(build test) | %w()
'Go gb' | { 'src/gitlab.com/gopackage.go' => '' } | {} | %w(build test) | %w()
'Gradle' | { 'gradlew' => '' } | {} | %w(build test) | %w()
'Java' | { 'pom.xml' => '' } | {} | %w(build test) | %w()
'Multi-buildpack' | { '.buildpacks' => '' } | {} | %w(build test) | %w()
'NodeJS' | { 'package.json' => '' } | {} | %w(build test) | %w()
'PHP' | { 'composer.json' => '' } | {} | %w(build test) | %w()
'Play' | { 'conf/application.conf' => '' } | {} | %w(build test) | %w()
'Python' | { 'Pipfile' => '' } | {} | %w(build test) | %w()
'Ruby' | { 'Gemfile' => '' } | {} | %w(build test) | %w()
'Scala' | { 'build.sbt' => '' } | {} | %w(build test) | %w()
'Static' | { '.static' => '' } | {} | %w(build test) | %w()
end
with_them do
let(:project) { create(:project, :custom_repo, files: files) }
let(:user) { project.first_owner }
let(:service) { Ci::CreatePipelineService.new(project, user, ref: default_branch ) }
let(:pipeline) { service.execute(:push).payload }
let(:build_names) { pipeline.builds.pluck(:name) }
before do
stub_application_setting(default_branch_name: default_branch)
stub_ci_pipeline_yaml_file(template.content)
allow_any_instance_of(Ci::BuildScheduleWorker).to receive(:perform).and_return(true)
variables.each do |(key, value)|
create(:ci_variable, project: project, key: key, value: value)
end
end
it 'creates a pipeline with the expected jobs' do
expect(build_names).to include(*include_build_names)
expect(build_names).not_to include(*not_include_build_names)
end
end
end
end
end
| 44.408638 | 147 | 0.543652 |
38e491a4eddc130b6fdb9e93f704951ac05278f6 | 2,653 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::RecoveryServicesSiteRecovery::Mgmt::V2016_08_10
module Models
#
# The properties of an add vCenter request.
#
class AddVCenterRequestProperties
include MsRestAzure
# @return [String] The friendly name of the vCenter.
attr_accessor :friendly_name
# @return [String] The IP address of the vCenter to be discovered.
attr_accessor :ip_address
# @return [String] The process server Id from where the discovery is
# orchestrated.
attr_accessor :process_server_id
# @return [String] The port number for discovery.
attr_accessor :port
# @return [String] The account Id which has privileges to discover the
# vCenter.
attr_accessor :run_as_account_id
#
# Mapper for AddVCenterRequestProperties class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'AddVCenterRequestProperties',
type: {
name: 'Composite',
class_name: 'AddVCenterRequestProperties',
model_properties: {
friendly_name: {
client_side_validation: true,
required: false,
serialized_name: 'friendlyName',
type: {
name: 'String'
}
},
ip_address: {
client_side_validation: true,
required: false,
serialized_name: 'ipAddress',
type: {
name: 'String'
}
},
process_server_id: {
client_side_validation: true,
required: false,
serialized_name: 'processServerId',
type: {
name: 'String'
}
},
port: {
client_side_validation: true,
required: false,
serialized_name: 'port',
type: {
name: 'String'
}
},
run_as_account_id: {
client_side_validation: true,
required: false,
serialized_name: 'runAsAccountId',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 28.836957 | 76 | 0.51602 |
e9651a9b8cee056e3a3bf6dd6867093ccf0ff8da | 489 | require 'alertlogic_tmc/base_api'
module AlertlogicTmc
class PolicyApi < AlertlogicTmc::BaseApi
def find(id)
get("/api/tm/v1/policies/#{id}")
end
def list(options = {})
get("/api/tm/v1/policies", options)
end
def create(options={})
post("/api/tm/v1/policies", options)
end
def update(id, options={})
post("/api/tm/v1/policies/#{id}", options)
end
def destroy(id)
delete("/api/tm/v1/policies/#{id}")
end
end
end | 19.56 | 48 | 0.601227 |
f86ccd293b5f35123f159c9601a31715964982f3 | 1,264 | require File.dirname(__FILE__)
Puppet::Type.type(:property_list).provide(:defaults,
parent: Puppet::Provider::PropertyList) do
commands defaults: '/usr/bin/defaults'
mk_resource_methods
class << self
# Override the write_plist method
# In order to get preferences to sync, we need to use `defaults` or
# HUP cfprefsd. Using defaults is preferred, and we trigger a sync
# by writing a simple value to the prefs domain. This is silly, but it
# appears to work. However, in cases where none of the desired values are
# "simple", we just HUP cfprefsd. It's a bit dirty, but Apple isn't
# really giving us any options when it comes to bulk editing preferences.
def write_plist(path, content, format)
super
flag_map = {
String => '-string',
Integer => '-integer',
Float => '-float',
TrueClass => '-bool',
FalseClass => '-bool',
}
content.each do |key, value|
case value
when String, Integer, Float, TrueClass, FalseClass
flag = flag_map[value.class]
return defaults 'write', path, key, flag, value
end
end
system('/usr/bin/killall cfprefsd')
end
end
end
| 33.263158 | 84 | 0.619462 |
1cfa587d913381134d1e1fbbc7891e6749b391df | 1,778 | module Contribution::PaymentEngineHandler
extend ActiveSupport::Concern
included do
delegate :can_do_refund?, to: :payment_engine
def payment_engine
PaymentEngines.find_engine(self.payment_method) || PaymentEngines::Interface.new
end
def review_path
payment_engine.review_path(self)
end
def direct_refund
payment_engine.direct_refund(self)
end
def second_slip_path
payment_engine.try(:second_slip_path, self)
end
def can_generate_second_slip?
payment_engine.try(:can_generate_second_slip?)
end
def update_current_billing_info
self.address_street = user.address_street
self.address_number = user.address_number
self.address_neighbourhood = user.address_neighbourhood
self.address_zip_code = user.address_zip_code
self.address_city = user.address_city
self.address_state = user.address_state
self.address_phone_number = user.phone_number
self.payer_document = user.cpf
self.payer_name = user.display_name
end
def update_user_billing_info
user.update_attributes({
address_street: address_street.presence || user.address_street,
address_number: address_number.presence || user.address_number,
address_neighbourhood: address_neighbourhood.presence || user.address_neighbourhood,
address_zip_code: address_zip_code.presence|| user.address_zip_code,
address_city: address_city.presence || user.address_city,
address_state: address_state.presence || user.address_state,
phone_number: address_phone_number.presence || user.phone_number,
cpf: payer_document.presence || user.cpf,
full_name: payer_name.presence || user.full_name
})
end
end
end
| 31.75 | 92 | 0.73622 |
33ed59094d01e5a7467f62f0a266da165fdcc4f7 | 1,142 | require "test_helper"
class I18nTest < ActionDispatch::IntegrationTest
def collect_combined_keys(hash, namespace = nil)
hash.collect do |k, v|
keys = []
keys << collect_combined_keys(v, "#{namespace}.#{k}") if v.is_a?(Hash)
keys << "#{namespace}.#{k}"
end.flatten
end
test "translation consistency" do
locales_path = File.expand_path("../../config/locales", __dir__)
locales = Dir.glob("#{locales_path}/*.yml").collect do |file_path|
File.basename(file_path, ".yml")
end
# collecting all locales
locale_keys = {}
locales.each do |locale|
translations = YAML.load_file("#{locales_path}/#{locale}.yml")
locale_keys[locale] = collect_combined_keys(translations[locale])
end
# Using en as reference
reference = locale_keys[locales.delete("en")]
assert reference.present?
locale_keys.each do |locale, keys|
missing = reference - keys
assert missing.blank?, "#{locale} locale is missing: #{missing.join(', ')}"
extra = keys - reference
assert extra.blank?, "#{locale} locale has extra: #{extra.join(', ')}"
end
end
end
| 30.864865 | 81 | 0.648862 |
1a9a8c49de0fad1f4d685847c813c6f77ce6396b | 623 | cask :v1 => 'adobe-dng-converter' do
version '8.6'
sha256 '3bb43ca608b7e62727512c813b395ea46aad545f68f9323cc78c9c5f47145650'
url "http://download.adobe.com/pub/adobe/dng/mac/DNGConverter_#{version.gsub('.', '_')}.dmg"
name 'Adobe Camera Raw and DNG Converter'
homepage 'http://www.adobe.com/support/downloads/product.jsp?product=106&platform=Macintosh'
license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
pkg 'Adobe DNG Converter.pkg'
uninstall :pkgutil => 'com.adobe.adobeDngConverter*',
:quit => 'com.adobe.DNGConverter'
end
| 41.533333 | 115 | 0.733547 |
8760036f7972466a573d32ddbb34ce91f2b32352 | 244 | class CreateNpcModelArmor < ActiveRecord::Migration[5.2]
def change
create_table :npc_model_armors do |t|
t.references :npc_model, foreign_key: true
t.references :armor, foreign_key: true
t.timestamps
end
end
end
| 22.181818 | 56 | 0.709016 |
1ca28bcc7b1a7877a016ae8803d4cde671b070b7 | 1,958 | class Wolfmqtt < Formula
desc "Small, fast, portable MQTT client C implementation"
homepage "https://github.com/wolfSSL/wolfMQTT"
url "https://github.com/wolfSSL/wolfMQTT/archive/refs/tags/v1.11.0.tar.gz"
sha256 "5d0c14ff0c5c571907802f51b91990e1528f7a586df4b6d796cf157b470f5712"
license "GPL-2.0-or-later"
head "https://github.com/wolfSSL/wolfMQTT.git", branch: "master"
bottle do
sha256 cellar: :any, arm64_monterey: "41814c2573b16061ff0f997063b5662418e267d00a45f67ce9294219fae94c3f"
sha256 cellar: :any, arm64_big_sur: "ded91f6729d83cdf7122b79534326d480416b6aace5223e2ce4a3235b49d75c7"
sha256 cellar: :any, monterey: "ff77fbd5bd48a2db0e5196925109d3cfb37d86a60ff97c8a3353e003b2a0e135"
sha256 cellar: :any, big_sur: "23575090380bb2d04015ba571e12c0a1f94958543389fb746822d7c7456f55e3"
sha256 cellar: :any, catalina: "64de89e504b10f918f9de2caf4c1742a1f8942500c7af9c5267724b58c01deb0"
sha256 cellar: :any_skip_relocation, x86_64_linux: "c829fe3a132623334e46eeb6b22c25e645d4199d0afdd4b2a9c9272564431f52"
end
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
depends_on "wolfssl"
def install
args = %W[
--disable-silent-rules
--disable-dependency-tracking
--infodir=#{info}
--mandir=#{man}
--prefix=#{prefix}
--sysconfdir=#{etc}
--enable-nonblock
--enable-mt
--enable-mqtt5
--enable-propcb
--enable-sn
]
system "./autogen.sh"
system "./configure", *args
system "make"
system "make", "install"
end
test do
(testpath/"test.cpp").write <<~EOT
#include <wolfmqtt/mqtt_client.h>
int main() {
MqttClient mqttClient;
return 0;
}
EOT
system ENV.cc, "test.cpp", "-L#{lib}", "-lwolfmqtt", "-o", "test"
system "./test"
end
end
| 34.964286 | 123 | 0.66905 |
6aae27e7674152b61f6a5ebab36a13fa47c0e57e | 2,378 | module PublishingApi
class LinksPresenter
LINK_NAMES_TO_METHODS_MAP = {
organisations: :organisation_ids,
primary_publishing_organisation: :primary_publishing_organisation_id,
original_primary_publishing_organisation: :original_primary_publishing_organisation_id,
policy_areas: :policy_area_ids,
statistical_data_set_documents: :statistical_data_set_ids,
topics: :topic_content_ids,
parent: :parent_content_ids,
world_locations: :world_location_ids,
worldwide_organisations: :worldwide_organisation_ids,
government: :government_id,
}.freeze
def initialize(item)
@item = item
end
def extract(filter_links)
if filter_links.include?(:organisations)
filter_links << :primary_publishing_organisation
filter_links << :original_primary_publishing_organisation
end
filter_links.reduce(Hash.new) do |links, link_name|
private_method_name = LINK_NAMES_TO_METHODS_MAP[link_name]
links[link_name] = send(private_method_name)
links
end
end
private
attr_reader :item
def policy_area_ids
(item.try(:topics) || []).map(&:content_id)
end
def statistical_data_set_ids
(item.try(:statistical_data_sets) || []).map(&:content_id)
end
def organisation_ids
(item.try(:organisations) || []).map(&:content_id)
end
def primary_publishing_organisation_id
lead_organisations = item.try(:lead_organisations) || []
[lead_organisations.map(&:content_id).first].compact
end
def original_primary_publishing_organisation_id
original_lead_organisations = item.try(:document).try(:editions).try(:first).try(:lead_organisations) || []
[original_lead_organisations.map(&:content_id).first].compact
end
def world_location_ids
(item.try(:world_locations) || []).map(&:content_id)
end
def worldwide_organisation_ids
(item.try(:worldwide_organisations) || []).map(&:content_id)
end
def topic_content_ids
item.specialist_sectors.map(&:topic_content_id)
end
def parent_content_ids
parent_content_id = item.primary_specialist_sectors.try(:first).try(:topic_content_id)
parent_content_id ? [parent_content_id] : []
end
def government_id
[item.government&.content_id].compact
end
end
end
| 29.358025 | 113 | 0.711943 |
399254f89e91fa93a524530e52d851dacd2d3a55 | 449 | module Bazaar
class Cart < ApplicationRecord
include Bazaar::CartSearchable if (Bazaar::CartSearchable rescue nil)
include Bazaar::ApplicationCartConcern if (Bazaar::ApplicationCartConcern rescue nil)
enum status: { 'active' => 1, 'init_checkout' => 2, 'success' => 3 }
has_many :cart_offers, dependent: :destroy
belongs_to :order, required: false
belongs_to :user, required: false
def to_s
"Cart \##{self.id}"
end
end
end
| 23.631579 | 87 | 0.723831 |
5d299ff1e67c6ac8fd4566576eda7c795ec61cb1 | 143 | class AddDivisions < ActiveRecord::Migration
def change
create_table(:divisions) do |t|
t.column(:name, :string)
end
end
end
| 17.875 | 44 | 0.678322 |
1815218d25a393e919097287ad4cf4ac4028d27b | 184 | path =File.join(File.dirname(__FILE__), '../../', 'lib')
$LOAD_PATH.unshift(path)
require 'pry'
require 'rspec'
require 'capybara_page_object'
World(CapybaraPageObject::PageFactory)
| 20.444444 | 56 | 0.744565 |
bbbda2997480e7e2b37349ff9d8d94f257ddc5b5 | 15,035 | # frozen_string_literal: true
require "hanami/utils/string"
RSpec.shared_examples "a new app" do
let(:app) { Hanami::Utils::String.new(input).underscore.to_s }
it "generates vanilla app" do
project = "bookshelf_generate_app_#{Random.rand(100_000_000)}"
with_project(project) do
app_name = Hanami::Utils::String.new(app).classify
app_upcase = Hanami::Utils::String.new(app).upcase
output = <<-OUT
create apps/#{app}/application.rb
create apps/#{app}/config/routes.rb
create apps/#{app}/views/application_layout.rb
create apps/#{app}/templates/application.html.erb
create apps/#{app}/assets/favicon.ico
create apps/#{app}/controllers/.gitkeep
create apps/#{app}/assets/images/.gitkeep
create apps/#{app}/assets/javascripts/.gitkeep
create apps/#{app}/assets/stylesheets/.gitkeep
create spec/#{app}/features/.gitkeep
create spec/#{app}/controllers/.gitkeep
create spec/#{app}/views/application_layout_spec.rb
insert config/environment.rb
insert config/environment.rb
append .env.development
append .env.test
OUT
run_cmd "hanami generate app #{input}", output
#
# apps/<app>/application.rb
#
expect("apps/#{app}/application.rb").to have_file_content <<-END
require 'hanami/helpers'
require 'hanami/assets'
module #{app_name}
class Application < Hanami::Application
configure do
##
# BASIC
#
# Define the root path of this application.
# All paths specified in this configuration are relative to path below.
#
root __dir__
# Relative load paths where this application will recursively load the
# code.
#
# When you add new directories, remember to add them here.
#
load_paths << [
'controllers',
'views'
]
# Handle exceptions with HTTP statuses (true) or don't catch them (false).
# Defaults to true.
# See: http://www.rubydoc.info/gems/hanami-controller/#Exceptions_management
#
# handle_exceptions true
##
# HTTP
#
# Routes definitions for this application
# See: http://www.rubydoc.info/gems/hanami-router#Usage
#
routes 'config/routes'
# URI scheme used by the routing system to generate absolute URLs
# Defaults to "http"
#
# scheme 'https'
# URI host used by the routing system to generate absolute URLs
# Defaults to "localhost"
#
# host 'example.org'
# URI port used by the routing system to generate absolute URLs
# Argument: An object coercible to integer, defaults to 80 if the scheme
# is http and 443 if it's https
#
# This should only be configured if app listens to non-standard ports
#
# port 443
# Enable cookies
# Argument: boolean to toggle the feature
# A Hash with options
#
# Options:
# :domain - The domain (String - nil by default, not required)
# :path - Restrict cookies to a relative URI
# (String - nil by default)
# :max_age - Cookies expiration expressed in seconds
# (Integer - nil by default)
# :secure - Restrict cookies to secure connections
# (Boolean - Automatically true when using HTTPS)
# See #scheme and #ssl?
# :httponly - Prevent JavaScript access (Boolean - true by default)
#
# cookies true
# or
# cookies max_age: 300
# Enable sessions
# Argument: Symbol the Rack session adapter
# A Hash with options
#
# See: http://www.rubydoc.info/gems/rack/Rack/Session/Cookie
#
# sessions :cookie, secret: ENV['#{app_upcase}_SESSIONS_SECRET']
# Configure Rack middleware for this application
#
# middleware.use Rack::Protection
# Default format for the requests that don't specify an HTTP_ACCEPT header
# Argument: A symbol representation of a mime type, defaults to :html
#
# default_request_format :html
# Default format for responses that don't consider the request format
# Argument: A symbol representation of a mime type, defaults to :html
#
# default_response_format :html
##
# TEMPLATES
#
# The layout to be used by all views
#
layout :application # It will load #{app_name}::Views::ApplicationLayout
# The relative path to templates
#
templates 'templates'
##
# ASSETS
#
assets do
# JavaScript compressor
#
# Supported engines:
#
# * :builtin
# * :uglifier
# * :yui
# * :closure
#
# See: https://guides.hanamirb.org/assets/compressors
#
# In order to skip JavaScript compression comment the following line
javascript_compressor :builtin
# Stylesheet compressor
#
# Supported engines:
#
# * :builtin
# * :yui
# * :sass
#
# See: https://guides.hanamirb.org/assets/compressors
#
# In order to skip stylesheet compression comment the following line
stylesheet_compressor :builtin
# Specify sources for assets
#
sources << [
'assets'
]
end
##
# SECURITY
#
# X-Frame-Options is a HTTP header supported by modern browsers.
# It determines if a web page can or cannot be included via <frame> and
# <iframe> tags by untrusted domains.
#
# Web applications can send this header to prevent Clickjacking attacks.
#
# Read more at:
#
# * https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options
# * https://www.owasp.org/index.php/Clickjacking
#
security.x_frame_options 'DENY'
# X-Content-Type-Options prevents browsers from interpreting files as
# something else than declared by the content type in the HTTP headers.
#
# Read more at:
#
# * https://www.owasp.org/index.php/OWASP_Secure_Headers_Project#X-Content-Type-Options
# * https://msdn.microsoft.com/en-us/library/gg622941%28v=vs.85%29.aspx
# * https://blogs.msdn.microsoft.com/ie/2008/09/02/ie8-security-part-vi-beta-2-update
#
security.x_content_type_options 'nosniff'
# X-XSS-Protection is a HTTP header to determine the behavior of the
# browser in case an XSS attack is detected.
#
# Read more at:
#
# * https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)
# * https://www.owasp.org/index.php/OWASP_Secure_Headers_Project#X-XSS-Protection
#
security.x_xss_protection '1; mode=block'
# Content-Security-Policy (CSP) is a HTTP header supported by modern
# browsers. It determines trusted sources of execution for dynamic
# contents (JavaScript) or other web related assets: stylesheets, images,
# fonts, plugins, etc.
#
# Web applications can send this header to mitigate Cross Site Scripting
# (XSS) attacks.
#
# The default value allows images, scripts, AJAX, fonts and CSS from the
# same origin, and does not allow any other resources to load (eg object,
# frame, media, etc).
#
# Inline JavaScript is NOT allowed. To enable it, please use:
# "script-src 'unsafe-inline'".
#
# Content Security Policy introduction:
#
# * http://www.html5rocks.com/en/tutorials/security/content-security-policy/
# * https://www.owasp.org/index.php/Content_Security_Policy
# * https://www.owasp.org/index.php/Cross-site_Scripting_%28XSS%29
#
# Inline and eval JavaScript risks:
#
# * http://www.html5rocks.com/en/tutorials/security/content-security-policy/#inline-code-considered-harmful
# * http://www.html5rocks.com/en/tutorials/security/content-security-policy/#eval-too
#
# Content Security Policy usage:
#
# * http://content-security-policy.com/
# * https://developer.mozilla.org/en-US/docs/Web/Security/CSP/Using_Content_Security_Policy
#
# Content Security Policy references:
#
# * https://developer.mozilla.org/en-US/docs/Web/Security/CSP/CSP_policy_directives
#
security.content_security_policy %{
form-action 'self';
frame-ancestors 'self';
base-uri 'self';
default-src 'none';
script-src 'self';
connect-src 'self';
img-src 'self' https: data:;
style-src 'self' 'unsafe-inline' https:;
font-src 'self';
object-src 'none';
plugin-types application/pdf;
child-src 'self';
frame-src 'self';
media-src 'self'
}
##
# FRAMEWORKS
#
# Configure the code that will yield each time #{app_name}::Action is included
# This is useful for sharing common functionality
#
# See: http://www.rubydoc.info/gems/hanami-controller#Configuration
controller.prepare do
# include MyAuthentication # included in all the actions
# before :authenticate! # run an authentication before callback
end
# Configure the code that will yield each time #{app_name}::View is included
# This is useful for sharing common functionality
#
# See: http://www.rubydoc.info/gems/hanami-view#Configuration
view.prepare do
include Hanami::Helpers
include #{app_name}::Assets::Helpers
end
end
##
# DEVELOPMENT
#
configure :development do
# Don't handle exceptions, render the stack trace
handle_exceptions false
end
##
# TEST
#
configure :test do
# Don't handle exceptions, render the stack trace
handle_exceptions false
end
##
# PRODUCTION
#
configure :production do
# scheme 'https'
# host 'example.org'
# port 443
assets do
# Don't compile static assets in production mode (eg. Sass, ES6)
#
# See: http://www.rubydoc.info/gems/hanami-assets#Configuration
compile false
# Use fingerprint file name for asset paths
#
# See: https://guides.hanamirb.org/assets/overview
fingerprint true
# Content Delivery Network (CDN)
#
# See: https://guides.hanamirb.org/assets/content-delivery-network
#
# scheme 'https'
# host 'cdn.example.org'
# port 443
# Subresource Integrity
#
# See: https://guides.hanamirb.org/assets/content-delivery-network/#subresource-integrity
subresource_integrity :sha256
end
end
end
end
END
#
# apps/<app>/config/routes.rb
#
expect("apps/#{app}/config/routes.rb").to have_file_content <<-END
# Configure your routes here
# See: https://guides.hanamirb.org/routing/overview
#
# Example:
# get '/hello', to: ->(env) { [200, {}, ['Hello from Hanami!']] }
END
#
# apps/<app>/views/application_layout.rb
#
expect("apps/#{app}/views/application_layout.rb").to have_file_content <<~END
module #{app_name}
module Views
class ApplicationLayout
include #{app_name}::Layout
end
end
end
END
#
# apps/<app>/assets/favicon.ico
#
expect("apps/#{app}/assets/favicon.ico").to be_an_existing_file
#
# spec/<app>/views/application_layout_spec.rb
#
expect("spec/#{app}/views/application_layout_spec.rb").to be_an_existing_file
#
# apps/<app>/controllers/.gitkeep
#
expect("apps/#{app}/controllers/.gitkeep").to be_an_existing_file
#
# apps/<app>/assets/images/.gitkeep
#
expect("apps/#{app}/assets/images/.gitkeep").to be_an_existing_file
#
# apps/<app>/assets/javascripts/.gitkeep
#
expect("apps/#{app}/assets/javascripts/.gitkeep").to be_an_existing_file
#
# apps/<app>/assets/stylesheets/.gitkeep
#
expect("apps/#{app}/assets/stylesheets/.gitkeep").to be_an_existing_file
#
# spec/<app>/features/.gitkeep
#
expect("spec/#{app}/features/.gitkeep").to be_an_existing_file
#
# spec/<app>/controllers/.gitkeep
#
expect("spec/#{app}/controllers/.gitkeep").to be_an_existing_file
#
# config/environment.rb
#
expect("config/environment.rb").to have_file_content <<-END
require 'bundler/setup'
require 'hanami/setup'
require 'hanami/model'
require_relative '../lib/#{project}'
require_relative '../apps/web/application'
require_relative '../apps/#{app}/application'
Hanami.configure do
mount #{app_name}::Application, at: '/#{app}'
mount Web::Application, at: '/'
model do
##
# Database adapter
#
# Available options:
#
# * SQL adapter
# adapter :sql, 'sqlite://db/#{project}_development.sqlite3'
# adapter :sql, 'postgresql://localhost/#{project}_development'
# adapter :sql, 'mysql://localhost/#{project}_development'
#
adapter :sql, ENV.fetch('DATABASE_URL')
##
# Migrations
#
migrations 'db/migrations'
schema 'db/schema.sql'
end
mailer do
root 'lib/#{project}/mailers'
# See https://guides.hanamirb.org/mailers/delivery
delivery :test
end
environment :development do
# See: https://guides.hanamirb.org/projects/logging
logger level: :debug
end
environment :production do
logger level: :info, formatter: :json, filter: []
mailer do
delivery :smtp, address: ENV.fetch('SMTP_HOST'), port: ENV.fetch('SMTP_PORT')
end
end
end
END
#
# .env.development
#
expect(".env.development").to have_file_content(%r{# Define ENV variables for development environment})
expect(".env.development").to have_file_content(%r{DATABASE_URL="sqlite://db/#{project}_development.sqlite"})
expect(".env.development").to have_file_content(%r{SERVE_STATIC_ASSETS="true"})
expect(".env.development").to have_file_content(%r{WEB_SESSIONS_SECRET="[\w]{64}"})
expect(".env.development").to have_file_content(%r{#{app_upcase}_SESSIONS_SECRET="[\w]{64}"})
#
# .env.test
#
expect(".env.test").to have_file_content(%r{# Define ENV variables for test environment})
expect(".env.test").to have_file_content(%r{DATABASE_URL="sqlite://db/#{project}_test.sqlite"})
expect(".env.test").to have_file_content(%r{SERVE_STATIC_ASSETS="true"})
expect(".env.test").to have_file_content(%r{WEB_SESSIONS_SECRET="[\w]{64}"})
expect(".env.test").to have_file_content(%r{#{app_upcase}_SESSIONS_SECRET="[\w]{64}"})
end
end
end
| 30.373737 | 115 | 0.616362 |
6216e3b6c1a66643dc6b63ab8f222720b074eea3 | 3,565 | module Locomotive
class FileInput < ::SimpleForm::Inputs::FileInput
extend Forwardable
def_delegators :template, :link_to, :content_tag
include Locomotive::SimpleForm::BootstrapHelpers
def input(wrapper_options = nil)
row_wrapping(data: { persisted: persisted_file?, persisted_file: persisted_file?, resize_format: options[:resize_format] }) do
file_html + buttons_html
end
end
def file_html
col_wrapping :file, 8 do
no_file_html +
new_file_html +
filename_or_image +
@builder.file_field(attribute_name, input_html_options) +
@builder.hidden_field(:"remove_#{attribute_name}", class: 'remove', value: '0') +
@builder.hidden_field(:"remote_#{attribute_name}_url", class: 'remote-url', value: '') +
hidden_fields
end
end
def buttons_html
col_wrapping :buttons, 4 do
button_html(:choose, options[:select_content_asset]) +
button_html(:change, options[:select_content_asset]) +
button_html(:cancel, false) +
template.link_to(trash_icon, '#', class: "delete #{hidden_css(:delete)}")
end
end
def button_html(name, dropdown = true)
if dropdown
content_tag(:div,
content_tag(:button,
(text(name) + ' ' + content_tag(:span, '', class: 'caret')).html_safe,
class: 'btn btn-primary btn-sm dropdown-toggle', data: { toggle: 'dropdown', aria_expanded: false }) +
content_tag(:ul,
content_tag(:li, content_tag(:a, text(:select_local_file), href: '#', class: "local-file #{name}")) +
content_tag(:li, content_tag(:a, text(:select_content_asset), href: template.content_assets_path(template.current_site), class: 'content-assets')),
class: 'dropdown-menu dropdown-menu-right', role: 'menu'),
class: "btn-group #{name} #{hidden_css(name)}")
else
template.link_to(text(name), '#', class: "#{name} btn btn-primary btn-sm #{hidden_css(name)}")
end
end
def trash_icon
template.content_tag(:i, '', class: 'far fa-trash-alt')
end
def filename_or_image
if persisted_file?
css = "current-file #{persisted_file.image? ? 'image' : ''}"
template.content_tag :span, (image_html + filename_html).html_safe, class: css
else
''
end
end
def no_file_html
template.content_tag :span, text(:none), class: "no-file #{hidden_css(:no_file)}"
end
def new_file_html
template.content_tag :span, 'New file here', class: "new-file #{hidden_css(:new_file)}"
end
def image_html
if persisted_file.image?
url = Locomotive::Dragonfly.resize_url persisted_file.url, '60x60#'
template.image_tag(url)
else
''
end
end
def hidden_fields
(options[:hidden_fields] || []).map do |name|
@builder.hidden_field(name)
end.join.html_safe
end
def filename_html
template.link_to(File.basename(persisted_file.to_s), persisted_file.url)
end
def persisted_file?
self.object.send(:"#{attribute_name}?")
end
def persisted_file
self.object.send(attribute_name.to_sym)
end
def hidden_css(name)
displayed = case name
when :choose, :no_file then !object.persisted? || !persisted_file?
when :change, :delete then persisted_file?
else false
end
displayed ? '' : 'hide'
end
def text(name)
I18n.t(name, scope: 'locomotive.inputs.file')
end
end
end
| 30.470085 | 159 | 0.6331 |
d5a68c9ebb833cf67c1abc1f229a281955df15c5 | 1,825 | require_relative 'base_helpers'
require_relative '../../tests/command_runner'
module AcceptanceTests
module CommandHelpers
include BaseHelpers
extend RSpec::Matchers::DSL
def run_command(*args)
Tests::CommandRunner.run(*args) do |runner|
runner.directory = fs.project_directory
yield runner if block_given?
end
end
def run_command!(*args)
run_command(*args) do |runner|
runner.run_successfully = true
yield runner if block_given?
end
end
def run_command_isolated_from_bundle(*args)
run_command(*args) do |runner|
runner.around_command do |run_command|
Bundler.with_clean_env(&run_command)
end
yield runner if block_given?
end
end
def run_command_isolated_from_bundle!(*args)
run_command_isolated_from_bundle(*args) do |runner|
runner.run_successfully = true
yield runner if block_given?
end
end
def run_command_within_bundle(*args)
run_command_isolated_from_bundle(*args) do |runner|
runner.command_prefix = 'bundle exec'
runner.env['BUNDLE_GEMFILE'] = fs.find_in_project('Gemfile').to_s
yield runner if block_given?
end
end
def run_command_within_bundle!(*args)
run_command_within_bundle(*args) do |runner|
runner.run_successfully = true
yield runner if block_given?
end
end
def run_rake_tasks(*tasks)
options = tasks.last.is_a?(Hash) ? tasks.pop : {}
args = ['rake', *tasks, '--trace'] + [options]
run_command_within_bundle(*args)
end
def run_rake_tasks!(*tasks)
options = tasks.last.is_a?(Hash) ? tasks.pop : {}
args = ['rake', *tasks, '--trace'] + [options]
run_command_within_bundle!(*args)
end
end
end
| 26.449275 | 73 | 0.654795 |
ed1a12363d228a7795f18b4f188a865920367a58 | 232 | include RandomNumber
FactoryGirl.define do
factory :message do
u { {:u_id => Random.new.rand, :name => Faker::Name.name} }
mes { Faker::Lorem.sentence }
created_at { rand_time(2.days.ago).to_i }
end
end
| 25.777778 | 63 | 0.633621 |
5d099e97a569b7c890d8c998eabec59099c35120 | 8,742 | #-- encoding: UTF-8
#-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2018 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2017 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
class BoardsController < ApplicationController
default_search_scope :messages
before_action :find_project_by_project_id,
:authorize
before_action :new_board, only: [:new, :create]
before_action :find_board_if_available, except: [:index]
before_action only: [:create, :update] do
upload_custom_file("board", "Board")
end
after_action only: [:create, :update] do
assign_custom_file_name("Board", @board.id)
parse_classifier_value("Board", @board.class.name, @board.id)
end
after_action only: [:create] do
init_counter_value("Board", @board.class.name, @board.id)
end
accept_key_auth :index, :show
include SortHelper
include WatchersHelper
include PaginationHelper
include OpenProject::ClientPreferenceExtractor
include CustomFilesHelper
include CounterHelper
include ClassifierHelper
def index
if params[:commit] == "Применить"
params[:filter_status].blank? ? @filter_status = nil : params[:filter_status] == "true" ? @filter_status = true : @filter_status = false
end
@boards = @project.boards
render_404 if @boards.empty?
# show the board if there is only one
if @boards.size == 1
@board = @boards.first
show
end
end
def show
sort_init 'updated_on', 'desc'
sort_update 'created_on' => "#{Message.table_name}.created_on",
'replies' => "#{Message.table_name}.replies_count",
'updated_on' => "#{Message.table_name}.updated_on",
'subject' => "#{Message.table_name}.subject",
'author' => "#{Message.table_name}.author_id"
respond_to do |format|
format.html do
set_topics
gon.rabl template: 'app/views/messages/index.rabl'
gon.project_id = @project.id
gon.activity_modul_enabled = @project.module_enabled?('activity')
gon.board_id = @board.id
gon.sort_column = 'updated_on'
gon.sort_direction = 'desc'
gon.total_count = @board.topics.count
gon.settings = client_preferences
@message = Message.new
render action: 'show', layout: !request.xhr?
end
format.json do
set_topics
gon.rabl template: 'app/views/messages/index.rabl'
render template: 'messages/index'
end
format.atom do
@messages = @board
.messages
.order(["#{Message.table_name}.sticked_on ASC", sort_clause].compact.join(', '))
.includes(:author, :board)
.limit(Setting.feeds_limit.to_i)
render_feed(@messages, title: "#{@project}: #{@board}")
end
end
end
def set_topics
@topics = @board
.topics
.order(["#{Message.table_name}.sticked_on ASC", sort_clause].compact.join(', '))
.includes(:author, last_reply: :author)
.page(page_param)
.per_page(per_page_param)
# @existing_statuses = @topics.select(:locked).distinct.map { |s| [s.locked ? "Открыто" : "Закрыто", s.locked] }
@existing_statuses = Message.find_by_sql("SELECT DISTINCT messages.locked FROM messages WHERE messages.board_id = '#{@board.id}' AND messages.parent_id IS NULL").map { |s| [s.locked ? "Открыто" : "Закрыто", s.locked] }
unless @filter_status.nil?
if !@filter_status
@topics = @topics.where(locked: true)
else
@topics = @topics.where(locked: false)
end
end
end
def new; end
def create
@timenow = Time.now.strftime("%d/%m/%Y %H:%M") #ban
if @board.save
flash[:notice] = l(:notice_successful_create)
begin
Member.where(project_id: @board.project_id).each do |member|
if member != User.current
Alert.create_pop_up_alert(@board, "Created", User.current, member.user)
end
#ban(
addr_user = User.find_by(id: member.user_id)
if Setting.can_notified_event(addr_user, 'board_added')
UserMailer.board_added(addr_user, @board, User.current, @project, @timenow).deliver_later
end
#)
end
rescue Exception => e
Rails.logger.info(e.message)
end
redirect_to_settings_in_projects
else
render :new
end
end
def edit; end
def update
@timenow = Time.now.strftime("%d/%m/%Y %H:%M") #ban
if @board.update_attributes(permitted_params.board)
flash[:notice] = l(:notice_successful_update)
begin
Member.where(project_id: @board.project_id).each do |member|
if member != User.current
Alert.create_pop_up_alert(@board, "Changed", User.current, member.user)
end
#ban(
addr_user = User.find_by(id: member.user_id)
if Setting.can_notified_event(addr_user,'board_changed')
UserMailer.board_changed(addr_user, @board, User.current, @project, @timenow).deliver_later
end
# )
end
rescue Exception => e
Rails.logger.info(e.message)
end
redirect_to_settings_in_projects
else
render :edit
end
end
def move
@timenow = Time.now.strftime("%d/%m/%Y %H:%M") #ban
if @board.update_attributes(permitted_params.board_move)
flash[:notice] = l(:notice_successful_update)
begin
Member.where(project_id: @board.project_id).each do |member|
if member != User.current
Alert.create_pop_up_alert(@board, "Moved", User.current, member.user)
end
#ban(
addr_user = User.find_by(id: member.user_id)
if Setting.can_notified_event(addr_user,'board_moved')
UserMailer.board_moved(addr_user, @board, User.current, @project, @timenow).deliver_later
end
#)
end
rescue Exception => e
Rails.logger.info(e.message)
end
else
flash.now[:error] = l('board_could_not_be_saved')
render action: 'edit'
end
redirect_to_settings_in_projects(@board.project_id)
end
def destroy
#ban(
@boardname = @board.name
@timenow = Time.now.strftime("%d/%m/%Y %H:%M")
#)
@board.destroy
flash[:notice] = l(:notice_successful_delete)
begin
Member.where(project_id: @board.project_id).each do |member|
if member != User.current
Alert.create_pop_up_alert(@board, "Deleted", User.current, member.user)
end
#ban(
addr_user = User.find_by(id: member.user_id)
if Setting.can_notified_event(addr_user,'board_deleted')
UserMailer.board_deleted(User.find_by(id:member.user_id), @boardname, User.current, @project, @timenow).deliver_later
end
#)
end
rescue Exception => e
Rails.logger.info(e.message)
end
redirect_to_settings_in_projects
end
private
def redirect_to_settings_in_projects(id = @project)
redirect_to controller: '/project_settings', action: 'show', id: id, tab: 'boards'
end
def find_board_if_available
@board = @project.boards.find(params[:id]) if params[:id]
rescue ActiveRecord::RecordNotFound
render_404
end
def new_board
@board = Board.new(permitted_params.board?)
@board.project = @project
end
protected
def default_breadcrumb
if action_name == 'index'
t(:label_board_plural)
else
ActionController::Base.helpers.link_to(t(:label_board_plural), project_boards_path(@project))
end
end
def show_local_breadcrumb
true
end
end
| 31.905109 | 222 | 0.65111 |
2105904af6ee5277de7105fe446052823ba46617 | 354 | class Igor < Formula
desc "Opens a shell in your favorite docker container"
homepage "https://github.com/felixb/igor"
version "de4d3fa"
head "https://github.com/felixb/igor.git"
def install
bin_path = buildpath/"igor"
bin_path.install Dir["*"]
cd bin_path do
mv "igor.sh", "igor"
bin.install "igor"
end
end
end
| 19.666667 | 56 | 0.658192 |
089c3643a401b81542251410c7935c695d492898 | 1,439 | require File.dirname(__FILE__) + "/spec_helper"
describe Pivotal::InMemoryEnumeration do
class Ime < Pivotal::InMemoryEnumeration
self.enumerated_values = [
Ime.new(1, "One"),
Ime.new(2, "Two"),
Ime.new(3, "Three")
]
end
describe 'new' do
it "can find by id" do
ime = Ime[1]
ime.id.should == 1
ime.name.should =="One"
end
it "can find by string name" do
ime = Ime['One']
ime.id.should == 1
ime.name.should =="One"
end
it "can find by symbol name" do
ime = Ime[:One]
ime.id.should == 1
ime.name.should =="One"
end
it "return nil for nil" do
Ime[nil].should be_nil
end
it "will raise if key is worng type" do
lambda{Ime[/bad/]}.should raise_error
end
end
describe "ids" do
it "should use id from quoted_id" do
Ime[1].quoted_id.should == 1
end
it "should use id for param" do
Ime[1].to_param.should == "1"
end
end
describe "totals" do
it "should have count" do
Ime.count.should == 3
end
it "should have them all" do
Ime.all.should == Ime.enumerated_values
end
end
describe "lookups" do
it "can look up by id" do
Ime.lookup_id(1).name.should == "One"
end
it "can look up by name" do
Ime.lookup_name("One").id.should == 1
end
end
end | 20.557143 | 47 | 0.555942 |
bf7cac1bed5272964fac9a8e6146a3afd1d9eea4 | 612 | # frozen_string_literal: true
module Pronto
class Punchlist < Runner
# Classify whether files are relevant to punchlist
class FileClassifier
def initialize(source_file_globber: SourceFinder::SourceFileGlobber.new)
@source_file_globber = source_file_globber
end
def non_binary?(path)
# https://ruby-doc.org/core-2.5.1/File.html#method-c-fnmatch
# EXTGLOB enables ',' as part of glob language
File.fnmatch?(@source_file_globber.source_and_doc_files_glob,
path,
File::FNM_EXTGLOB)
end
end
end
end
| 29.142857 | 78 | 0.660131 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.