repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/-test-/funcall/extconf.rb
|
<gh_stars>0
# frozen_string_literal: false
require 'mkmf'
create_makefile("-test-/funcall/funcall")
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/KNOWNBUGS.rb
|
#
# This test file concludes tests which point out known bugs.
# So all tests will cause failure.
#
|
arnab0073/idea
|
.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/rvm-1.11.3.9/lib/rvm/environment/info.rb
|
<filename>.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/rvm-1.11.3.9/lib/rvm/environment/info.rb
require 'yaml'
module RVM
class Environment
# Return a Hash with the same output that command:
#
# $ rvm info
#
def info(*ruby_strings)
ruby_string = normalize_ruby_string(ruby_strings)
res = rvm(:info, ruby_string)
res.successful? ? YAML.load(res.stdout) : {}
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/btn_with_frame.rb
|
<reponame>arnab0073/idea
require 'tk'
class Button_with_Frame < TkButton
def create_self(keys)
@frame = TkFrame.new('widgetname'=>@path, 'background'=>'yellow')
install_win(@path) # create new @path which is a daughter of old @path
super(keys)
TkPack(@path, :padx=>7, :pady=>7)
@epath = @frame.path
end
def epath
@epath
end
end
Button_with_Frame.new(:text=>'QUIT', :command=>proc{exit}) {
pack(:padx=>15, :pady=>5)
}
Tk.mainloop
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/rackspace/requests/cdn_v2/update_service.rb
|
<filename>.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/rackspace/requests/cdn_v2/update_service.rb
class Fog::Rackspace::CDNV2::Real
def update_service(service)
request(
:expects => [201, 202],
:method => 'PATCH',
:body => Fog::JSON.encode(service.operations),
:path => "services/#{service.id}"
)
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/bigdecimal/extconf.rb
|
require 'mkmf'
have_func("labs", "stdlib.h")
have_func("llabs", "stdlib.h")
create_makefile('bigdecimal')
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/strscan/extconf.rb
|
# frozen_string_literal: false
require 'mkmf'
$INCFLAGS << " -I$(top_srcdir)"
create_makefile 'strscan'
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/sample/ripper/strip-comment.rb
|
# $Id: strip-comment.rb 25189 2009-10-02 12:04:37Z akr $
require 'ripper/filter'
class CommentStripper < Ripper::Filter
def CommentStripper.strip(src)
new(src).parse(nil)
end
def on_default(event, token, data)
print token
end
def on_comment(token, data)
puts
end
end
CommentStripper.strip(ARGF)
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/openstack/models/baremetal/ports.rb
|
<reponame>arnab0073/idea
require 'fog/core/collection'
require 'fog/openstack/models/baremetal/port'
module Fog
module Baremetal
class OpenStack
class Ports < Fog::Collection
model Fog::Baremetal::OpenStack::Port
def all
load(service.list_ports.body['ports'])
end
def details(parameters=nil)
load(service.list_ports_detailed(parameters).body['ports'])
end
def find_by_uuid(uuid)
new(service.get_port(uuid).body)
end
alias_method :get, :find_by_uuid
def destroy(uuid)
port = self.find_by_id(uuid)
port.destroy
end
def method_missing(method_sym, *arguments, &block)
if method_sym.to_s =~ /^find_by_(.*)$/
load(service.list_ports_detailed({$1 => arguments.first}).body['ports'])
else
super
end
end
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/lib/pstore.rb
|
# frozen_string_literal: false
# = PStore -- Transactional File Storage for Ruby Objects
#
# pstore.rb -
# originally by matz
# documentation by <NAME> and <NAME>
# improved by <NAME>
#
# See PStore for documentation.
require "digest/md5"
#
# PStore implements a file based persistence mechanism based on a Hash. User
# code can store hierarchies of Ruby objects (values) into the data store file
# by name (keys). An object hierarchy may be just a single object. User code
# may later read values back from the data store or even update data, as needed.
#
# The transactional behavior ensures that any changes succeed or fail together.
# This can be used to ensure that the data store is not left in a transitory
# state, where some values were updated but others were not.
#
# Behind the scenes, Ruby objects are stored to the data store file with
# Marshal. That carries the usual limitations. Proc objects cannot be
# marshalled, for example.
#
# == Usage example:
#
# require "pstore"
#
# # a mock wiki object...
# class WikiPage
# def initialize( page_name, author, contents )
# @page_name = page_name
# @revisions = Array.new
#
# add_revision(author, contents)
# end
#
# attr_reader :page_name
#
# def add_revision( author, contents )
# @revisions << { :created => Time.now,
# :author => author,
# :contents => contents }
# end
#
# def wiki_page_references
# [@page_name] + @revisions.last[:contents].scan(/\b(?:[A-Z]+[a-z]+){2,}/)
# end
#
# # ...
# end
#
# # create a new page...
# home_page = WikiPage.new( "HomePage", "<NAME>",
# "A page about the JoysOfDocumentation..." )
#
# # then we want to update page data and the index together, or not at all...
# wiki = PStore.new("wiki_pages.pstore")
# wiki.transaction do # begin transaction; do all of this or none of it
# # store page...
# wiki[home_page.page_name] = home_page
# # ensure that an index has been created...
# wiki[:wiki_index] ||= Array.new
# # update wiki index...
# wiki[:wiki_index].push(*home_page.wiki_page_references)
# end # commit changes to wiki data store file
#
# ### Some time later... ###
#
# # read wiki data...
# wiki.transaction(true) do # begin read-only transaction, no changes allowed
# wiki.roots.each do |data_root_name|
# p data_root_name
# p wiki[data_root_name]
# end
# end
#
# == Transaction modes
#
# By default, file integrity is only ensured as long as the operating system
# (and the underlying hardware) doesn't raise any unexpected I/O errors. If an
# I/O error occurs while PStore is writing to its file, then the file will
# become corrupted.
#
# You can prevent this by setting <em>pstore.ultra_safe = true</em>.
# However, this results in a minor performance loss, and only works on platforms
# that support atomic file renames. Please consult the documentation for
# +ultra_safe+ for details.
#
# Needless to say, if you're storing valuable data with PStore, then you should
# backup the PStore files from time to time.
class PStore
RDWR_ACCESS = {mode: IO::RDWR | IO::CREAT | IO::BINARY, encoding: Encoding::ASCII_8BIT}.freeze
RD_ACCESS = {mode: IO::RDONLY | IO::BINARY, encoding: Encoding::ASCII_8BIT}.freeze
WR_ACCESS = {mode: IO::WRONLY | IO::CREAT | IO::TRUNC | IO::BINARY, encoding: Encoding::ASCII_8BIT}.freeze
# The error type thrown by all PStore methods.
class Error < StandardError
end
# Whether PStore should do its best to prevent file corruptions, even when under
# unlikely-to-occur error conditions such as out-of-space conditions and other
# unusual OS filesystem errors. Setting this flag comes at the price in the form
# of a performance loss.
#
# This flag only has effect on platforms on which file renames are atomic (e.g.
# all POSIX platforms: Linux, MacOS X, FreeBSD, etc). The default value is false.
attr_accessor :ultra_safe
#
# To construct a PStore object, pass in the _file_ path where you would like
# the data to be stored.
#
# PStore objects are always reentrant. But if _thread_safe_ is set to true,
# then it will become thread-safe at the cost of a minor performance hit.
#
def initialize(file, thread_safe = false)
dir = File::dirname(file)
unless File::directory? dir
raise PStore::Error, format("directory %s does not exist", dir)
end
if File::exist? file and not File::readable? file
raise PStore::Error, format("file %s not readable", file)
end
@filename = file
@abort = false
@ultra_safe = false
@thread_safe = thread_safe
@lock = Mutex.new
end
# Raises PStore::Error if the calling code is not in a PStore#transaction.
def in_transaction
raise PStore::Error, "not in transaction" unless @lock.locked?
end
#
# Raises PStore::Error if the calling code is not in a PStore#transaction or
# if the code is in a read-only PStore#transaction.
#
def in_transaction_wr
in_transaction
raise PStore::Error, "in read-only transaction" if @rdonly
end
private :in_transaction, :in_transaction_wr
#
# Retrieves a value from the PStore file data, by _name_. The hierarchy of
# Ruby objects stored under that root _name_ will be returned.
#
# *WARNING*: This method is only valid in a PStore#transaction. It will
# raise PStore::Error if called at any other time.
#
def [](name)
in_transaction
@table[name]
end
#
# This method is just like PStore#[], save that you may also provide a
# _default_ value for the object. In the event the specified _name_ is not
# found in the data store, your _default_ will be returned instead. If you do
# not specify a default, PStore::Error will be raised if the object is not
# found.
#
# *WARNING*: This method is only valid in a PStore#transaction. It will
# raise PStore::Error if called at any other time.
#
def fetch(name, default=PStore::Error)
in_transaction
unless @table.key? name
if default == PStore::Error
raise PStore::Error, format("undefined root name `%s'", name)
else
return default
end
end
@table[name]
end
#
# Stores an individual Ruby object or a hierarchy of Ruby objects in the data
# store file under the root _name_. Assigning to a _name_ already in the data
# store clobbers the old data.
#
# == Example:
#
# require "pstore"
#
# store = PStore.new("data_file.pstore")
# store.transaction do # begin transaction
# # load some data into the store...
# store[:single_object] = "My data..."
# store[:obj_hierarchy] = { "<NAME>" => ["rational.rb", "pstore.rb"],
# "<NAME>" => ["erb.rb", "pstore.rb"] }
# end # commit changes to data store file
#
# *WARNING*: This method is only valid in a PStore#transaction and it cannot
# be read-only. It will raise PStore::Error if called at any other time.
#
def []=(name, value)
in_transaction_wr
@table[name] = value
end
#
# Removes an object hierarchy from the data store, by _name_.
#
# *WARNING*: This method is only valid in a PStore#transaction and it cannot
# be read-only. It will raise PStore::Error if called at any other time.
#
def delete(name)
in_transaction_wr
@table.delete name
end
#
# Returns the names of all object hierarchies currently in the store.
#
# *WARNING*: This method is only valid in a PStore#transaction. It will
# raise PStore::Error if called at any other time.
#
def roots
in_transaction
@table.keys
end
#
# Returns true if the supplied _name_ is currently in the data store.
#
# *WARNING*: This method is only valid in a PStore#transaction. It will
# raise PStore::Error if called at any other time.
#
def root?(name)
in_transaction
@table.key? name
end
# Returns the path to the data store file.
def path
@filename
end
#
# Ends the current PStore#transaction, committing any changes to the data
# store immediately.
#
# == Example:
#
# require "pstore"
#
# store = PStore.new("data_file.pstore")
# store.transaction do # begin transaction
# # load some data into the store...
# store[:one] = 1
# store[:two] = 2
#
# store.commit # end transaction here, committing changes
#
# store[:three] = 3 # this change is never reached
# end
#
# *WARNING*: This method is only valid in a PStore#transaction. It will
# raise PStore::Error if called at any other time.
#
def commit
in_transaction
@abort = false
throw :pstore_abort_transaction
end
#
# Ends the current PStore#transaction, discarding any changes to the data
# store.
#
# == Example:
#
# require "pstore"
#
# store = PStore.new("data_file.pstore")
# store.transaction do # begin transaction
# store[:one] = 1 # this change is not applied, see below...
# store[:two] = 2 # this change is not applied, see below...
#
# store.abort # end transaction here, discard all changes
#
# store[:three] = 3 # this change is never reached
# end
#
# *WARNING*: This method is only valid in a PStore#transaction. It will
# raise PStore::Error if called at any other time.
#
def abort
in_transaction
@abort = true
throw :pstore_abort_transaction
end
#
# Opens a new transaction for the data store. Code executed inside a block
# passed to this method may read and write data to and from the data store
# file.
#
# At the end of the block, changes are committed to the data store
# automatically. You may exit the transaction early with a call to either
# PStore#commit or PStore#abort. See those methods for details about how
# changes are handled. Raising an uncaught Exception in the block is
# equivalent to calling PStore#abort.
#
# If _read_only_ is set to +true+, you will only be allowed to read from the
# data store during the transaction and any attempts to change the data will
# raise a PStore::Error.
#
# Note that PStore does not support nested transactions.
#
def transaction(read_only = false) # :yields: pstore
value = nil
if !@thread_safe
raise PStore::Error, "nested transaction" unless @lock.try_lock
else
begin
@lock.lock
rescue ThreadError
raise PStore::Error, "nested transaction"
end
end
begin
@rdonly = read_only
@abort = false
file = open_and_lock_file(@filename, read_only)
if file
begin
@table, checksum, original_data_size = load_data(file, read_only)
catch(:pstore_abort_transaction) do
value = yield(self)
end
if !@abort && !read_only
save_data(checksum, original_data_size, file)
end
ensure
file.close if !file.closed?
end
else
# This can only occur if read_only == true.
@table = {}
catch(:pstore_abort_transaction) do
value = yield(self)
end
end
ensure
@lock.unlock
end
value
end
private
# Constant for relieving Ruby's garbage collector.
EMPTY_STRING = ""
EMPTY_MARSHAL_DATA = Marshal.dump({})
EMPTY_MARSHAL_CHECKSUM = Digest::MD5.digest(EMPTY_MARSHAL_DATA)
#
# Open the specified filename (either in read-only mode or in
# read-write mode) and lock it for reading or writing.
#
# The opened File object will be returned. If _read_only_ is true,
# and the file does not exist, then nil will be returned.
#
# All exceptions are propagated.
#
def open_and_lock_file(filename, read_only)
if read_only
begin
file = File.new(filename, RD_ACCESS)
begin
file.flock(File::LOCK_SH)
return file
rescue
file.close
raise
end
rescue Errno::ENOENT
return nil
end
else
file = File.new(filename, RDWR_ACCESS)
file.flock(File::LOCK_EX)
return file
end
end
# Load the given PStore file.
# If +read_only+ is true, the unmarshalled Hash will be returned.
# If +read_only+ is false, a 3-tuple will be returned: the unmarshalled
# Hash, an MD5 checksum of the data, and the size of the data.
def load_data(file, read_only)
if read_only
begin
table = load(file)
raise Error, "PStore file seems to be corrupted." unless table.is_a?(Hash)
rescue EOFError
# This seems to be a newly-created file.
table = {}
end
table
else
data = file.read
if data.empty?
# This seems to be a newly-created file.
table = {}
checksum = empty_marshal_checksum
size = empty_marshal_data.bytesize
else
table = load(data)
checksum = Digest::MD5.digest(data)
size = data.bytesize
raise Error, "PStore file seems to be corrupted." unless table.is_a?(Hash)
end
data.replace(EMPTY_STRING)
[table, checksum, size]
end
end
def on_windows?
is_windows = RUBY_PLATFORM =~ /mswin|mingw|bccwin|wince/
self.class.__send__(:define_method, :on_windows?) do
is_windows
end
is_windows
end
def save_data(original_checksum, original_file_size, file)
new_data = dump(@table)
if new_data.bytesize != original_file_size || Digest::MD5.digest(new_data) != original_checksum
if @ultra_safe && !on_windows?
# Windows doesn't support atomic file renames.
save_data_with_atomic_file_rename_strategy(new_data, file)
else
save_data_with_fast_strategy(new_data, file)
end
end
new_data.replace(EMPTY_STRING)
end
def save_data_with_atomic_file_rename_strategy(data, file)
temp_filename = "#{@filename}.tmp.#{Process.pid}.#{rand 1000000}"
temp_file = File.new(temp_filename, WR_ACCESS)
begin
temp_file.flock(File::LOCK_EX)
temp_file.write(data)
temp_file.flush
File.rename(temp_filename, @filename)
rescue
File.unlink(temp_file) rescue nil
raise
ensure
temp_file.close
end
end
def save_data_with_fast_strategy(data, file)
file.rewind
file.write(data)
file.truncate(data.bytesize)
end
# This method is just a wrapped around Marshal.dump
# to allow subclass overriding used in YAML::Store.
def dump(table) # :nodoc:
Marshal::dump(table)
end
# This method is just a wrapped around Marshal.load.
# to allow subclass overriding used in YAML::Store.
def load(content) # :nodoc:
Marshal::load(content)
end
def empty_marshal_data
EMPTY_MARSHAL_DATA
end
def empty_marshal_checksum
EMPTY_MARSHAL_CHECKSUM
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/ruby/test_variable.rb
|
<gh_stars>1-10
# frozen_string_literal: false
require 'test/unit'
class TestVariable < Test::Unit::TestCase
class Gods
@@rule = "Uranus"
def ruler0
@@rule
end
def self.ruler1 # <= per method definition style
@@rule
end
class << self # <= multiple method definition style
def ruler2
@@rule
end
end
end
module Olympians
@@rule ="Zeus"
def ruler3
@@rule
end
end
class Titans < Gods
@@rule = "Cronus" # modifies @@rule in Gods
include Olympians
def ruler4
EnvUtil.suppress_warning {
@@rule
}
end
end
def test_variable
assert_instance_of(Fixnum, $$)
# read-only variable
assert_raise(NameError) do
$$ = 5
end
assert_normal_exit("$*=0; $*", "[ruby-dev:36698]")
foobar = "foobar"
$_ = foobar
assert_equal(foobar, $_)
assert_equal("Cronus", Gods.new.ruler0)
assert_equal("Cronus", Gods.ruler1)
assert_equal("Cronus", Gods.ruler2)
assert_equal("Cronus", Titans.ruler1)
assert_equal("Cronus", Titans.ruler2)
atlas = Titans.new
assert_equal("Cronus", atlas.ruler0)
assert_equal("Zeus", atlas.ruler3)
assert_equal("Cronus", atlas.ruler4)
assert_nothing_raised do
class << Gods
defined?(@@rule) && @@rule
end
end
end
def test_local_variables
lvar = 1
assert_instance_of(Symbol, local_variables[0], "[ruby-dev:34008]")
lvar
end
def test_local_variables2
x = 1
proc do |y|
assert_equal([:x, :y], local_variables.sort)
end.call
x
end
def test_local_variables3
x = 1
proc do |y|
1.times do |z|
assert_equal([:x, :y, :z], local_variables.sort)
end
end.call
x
end
def test_shadowing_local_variables
bug9486 = '[ruby-core:60501] [Bug #9486]'
x = tap {|x| break local_variables}
assert_equal([:x, :bug9486], x)
end
def test_shadowing_block_local_variables
bug9486 = '[ruby-core:60501] [Bug #9486]'
x = tap {|;x| break local_variables}
assert_equal([:x, :bug9486], x)
end
def test_global_variable_0
assert_in_out_err(["-e", "$0='t'*1000;print $0"], "", /\At+\z/, [])
end
def test_global_variable_poped
assert_nothing_raised {
EnvUtil.suppress_warning {
eval("$foo; 1")
}
}
end
def test_constant_poped
assert_nothing_raised {
EnvUtil.suppress_warning {
eval("TestVariable::Gods; 1")
}
}
end
def test_special_constant_ivars
[ true, false, :symbol, "dsym#{rand(9999)}".to_sym, 1, 1.0 ].each do |v|
assert_empty v.instance_variables
msg = "can't modify frozen #{v.class}"
assert_raise_with_message(RuntimeError, msg) do
v.instance_variable_set(:@foo, :bar)
end
assert_nil v.instance_variable_get(:@foo)
refute v.instance_variable_defined?(:@foo)
assert_raise_with_message(RuntimeError, msg) do
v.remove_instance_variable(:@foo)
end
end
end
def test_local_variables_with_kwarg
bug11674 = '[ruby-core:71437] [Bug #11674]'
v = with_kwargs_11(v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8,v9:9,v10:10,v11:11)
assert_equal(%i(v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11), v, bug11674)
end
private
def with_kwargs_11(v1:, v2:, v3:, v4:, v5:, v6:, v7:, v8:, v9:, v10:, v11:)
local_variables
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tk/clock.rb
|
<gh_stars>10-100
#
# tk/clock.rb : methods for clock command
#
require 'tk'
module Tk
module Clock
include Tk
extend TkCore
def self.add(clk, *args)
tk_call_without_enc('clock','add', clk, *args).to_i
end
def self.clicks(ms=nil)
ms = ms.to_s if ms.kind_of?(Symbol)
case ms
when nil, ''
tk_call_without_enc('clock','clicks').to_i
when /^mic/
tk_call_without_enc('clock','clicks','-microseconds').to_i
when /^mil/
tk_call_without_enc('clock','clicks','-milliseconds').to_i
else
tk_call_without_enc('clock','clicks','-milliseconds').to_i
end
end
def self.format(clk, form=nil)
if form
tk_call('clock','format',clk,'-format',form)
else
tk_call('clock','format',clk)
end
end
def self.formatGMT(clk, form=nil)
if form
tk_call('clock','format',clk,'-format',form,'-gmt','1')
else
tk_call('clock','format',clk,'-gmt','1')
end
end
def self.scan(str, base=nil)
if base
tk_call('clock','scan',str,'-base',base).to_i
else
tk_call('clock','scan',str).to_i
end
end
def self.scanGMT(str, base=nil)
if base
tk_call('clock','scan',str,'-base',base,'-gmt','1').to_i
else
tk_call('clock','scan',str,'-gmt','1').to_i
end
end
def self.seconds
tk_call_without_enc('clock','seconds').to_i
end
def self.milliseconds
tk_call_without_enc('clock','milliseconds').to_i
end
def self.microseconds
tk_call_without_enc('clock','microseconds').to_i
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/tool/change_maker.rb
|
#! ./miniruby
def diff2index(cmd, *argv)
lines = []
path = nil
`#{cmd} #{argv.join(" ")}`.split(/\n/).each do |line|
case line
when /^Index: (\S*)/, /^diff --git [a-z]\/(\S*) [a-z]\/\1/
path = $1
when /^@@\s*-[,\d]+ +\+(\d+)[,\d]*\s*@@(?: +([A-Za-z_][A-Za-z_0-9 ]*[A-Za-z_0-9]))?/
line = $1.to_i
ent = "\t* #{path}"
ent << " (#{$2})" if $2
lines << "#{ent}:"
end
end
lines.uniq!
lines.empty? ? nil : lines
end
if File.directory?(".svn")
cmd = "svn diff --diff-cmd=diff -x-pU0"
change = diff2index(cmd, ARGV)
elsif File.directory?(".git")
cmd = "git diff -U0"
change = diff2index(cmd, ARGV) || diff2index(cmd, "--cached", ARGV)
else
abort "does not seem to be under a vcs"
end
puts change if change
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/rbconfig/sizeof/extconf.rb
|
<reponame>arnab0073/idea
# frozen_string_literal: false
$srcs = %w[sizes.c]
$distcleanfiles.concat($srcs)
check_sizeof('int_least8_t')
check_sizeof('int_least16_t')
check_sizeof('int_least32_t')
check_sizeof('int_least64_t')
check_sizeof('int_fast8_t')
check_sizeof('int_fast16_t')
check_sizeof('int_fast32_t')
check_sizeof('int_fast64_t')
check_sizeof('intmax_t')
check_sizeof('sig_atomic_t', %w[signal.h])
check_sizeof('wchar_t')
check_sizeof('wint_t', %w[wctype.h])
check_sizeof('wctrans_t', %w[wctype.h])
check_sizeof('wctype_t', %w[wctype.h])
check_sizeof('_Bool')
check_sizeof('long double')
check_sizeof('float _Complex')
check_sizeof('double _Complex')
check_sizeof('long double _Complex')
check_sizeof('float _Imaginary')
check_sizeof('double _Imaginary')
check_sizeof('long double _Imaginary')
check_sizeof('__int128') # x86_64 ABI (optional)
check_sizeof('__float128') # x86_64 ABI (optional)
check_sizeof('_Decimal32') # x86_64 ABI
check_sizeof('_Decimal64') # x86_64 ABI
check_sizeof('_Decimal128') # x86_64 ABI
check_sizeof('__m64') # x86_64 ABI (optional)
check_sizeof('__m128') # x86_64 ABI (optional)
check_sizeof('__float80') # gcc x86
create_makefile('rbconfig/sizeof')
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/test/appenders/test_file.rb
|
<reponame>arnab0073/idea
# encoding: UTF-8
require File.expand_path('../setup', File.dirname(__FILE__))
module TestLogging
module TestAppenders
class TestFile < Test::Unit::TestCase
include LoggingTestCase
NAME = 'logfile'
def setup
super
Logging.init
FileUtils.mkdir [File.join(TMP, 'dir'), File.join(TMP, 'uw_dir')]
FileUtils.chmod 0555, File.join(TMP, 'uw_dir')
FileUtils.touch File.join(TMP, 'uw_file')
FileUtils.chmod 0444, File.join(TMP, 'uw_file')
end
def test_factory_method_validates_input
assert_raise(ArgumentError) do
Logging.appenders.file
end
end
def test_class_assert_valid_logfile
log = File.join(TMP, 'uw_dir', 'file.log')
assert_raise(ArgumentError) do
Logging.appenders.file(log).class.assert_valid_logfile(log)
end
log = File.join(TMP, 'dir')
assert_raise(ArgumentError) do
Logging.appenders.file(log).class.assert_valid_logfile(log)
end
log = File.join(TMP, 'uw_file')
assert_raise(ArgumentError) do
Logging.appenders.file(log).class.assert_valid_logfile(log)
end
log = File.join(TMP, 'file.log')
assert Logging.appenders.file(log).class.assert_valid_logfile(log)
end
def test_initialize
log = File.join(TMP, 'file.log')
appender = Logging.appenders.file(NAME, :filename => log)
assert_equal 'logfile', appender.name
assert_equal ::File.expand_path(log), appender.filename
appender << "This will be the first line\n"
appender << "This will be the second line\n"
appender.flush
File.open(log, 'r') do |file|
assert_equal "This will be the first line\n", file.readline
assert_equal "This will be the second line\n", file.readline
assert_raise(EOFError) {file.readline}
end
cleanup
appender = Logging.appenders.file(NAME, :filename => log)
assert_equal 'logfile', appender.name
assert_equal ::File.expand_path(log), appender.filename
appender << "This will be the third line\n"
appender.flush
File.open(log, 'r') do |file|
assert_equal "This will be the first line\n", file.readline
assert_equal "This will be the second line\n", file.readline
assert_equal "This will be the third line\n", file.readline
assert_raise(EOFError) {file.readline}
end
cleanup
appender = Logging.appenders.file(NAME, :filename => log,
:truncate => true)
assert_equal 'logfile', appender.name
appender << "The file was truncated\n"
appender.flush
File.open(log, 'r') do |file|
assert_equal "The file was truncated\n", file.readline
assert_raise(EOFError) {file.readline}
end
cleanup
end
def test_changing_directories
log = File.join(TMP, 'file.log')
appender = Logging.appenders.file(NAME, :filename => log)
assert_equal 'logfile', appender.name
assert_equal ::File.expand_path(log), appender.filename
begin
pwd = Dir.pwd
Dir.chdir TMP
assert_nothing_raised { appender.reopen }
ensure
Dir.chdir pwd
end
end
if Object.const_defined? :Encoding
def test_encoding
log = File.join(TMP, 'file-encoding.log')
appender = Logging.appenders.file(NAME, :filename => log, :encoding => 'ASCII')
appender << "A normal line of text\n"
appender << "ümlaut\n"
appender.close
lines = File.readlines(log, :encoding => 'UTF-8')
assert_equal "A normal line of text\n", lines[0]
assert_equal "ümlaut\n", lines[1]
cleanup
end
end
private
def cleanup
unless Logging.appenders[NAME].nil?
Logging.appenders[NAME].close false
Logging.appenders[NAME] = nil
end
end
end # TestFile
end # TestAppenders
end # TestLogging
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/win32ole/test_ole_methods.rb
|
<reponame>arnab0073/idea
# frozen_string_literal: false
#
# This is test for [ruby-talk:196897]
#
begin
require 'win32ole'
rescue LoadError
end
require "test/unit"
if defined?(WIN32OLE)
class TestWIN32OLE_FOR_PROPERTYPUTREF < Test::Unit::TestCase
def setup
@obj = WIN32OLE.new('Scripting.Dictionary')
end
def test_ole_methods
x = @obj.ole_methods.select {|m|
m.invoke_kind == 'PROPERTYPUTREF'
}
assert(x.size > 0)
assert_equal(1, x.size)
assert_equal('Item', x[0].name)
end
def test_ole_put_methods
x = @obj.ole_put_methods.select {|m|
m.invoke_kind == 'PROPERTYPUTREF'
}
assert(x.size > 0)
assert_equal(1, x.size)
assert_equal('Item', x[0].name)
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/blt/ted.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/blt/ted.rb
#
# tkextlib/blt/ted.rb
#
# *** This is alpha version, because there is no document on BLT. ***
#
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tkextlib/blt.rb'
module Tk::BLT
module Ted
extend TkCore
TkCommandNames = ['::blt::ted'.freeze].freeze
##############################
extend TkItemConfigMethod
class << self
def __item_cget_cmd(id)
['::blt::ted', 'cget', id]
end
private :__item_cget_cmd
def __item_config_cmd(id)
['::blt::ted', 'configure', id]
end
private :__item_config_cmd
private :itemcget_tkstring, :itemcget, :itemcget_strict
private :itemconfigure, :itemconfiginfo, :current_itemconfiginfo
def cget_tkstring(master, option)
itemcget_tkstring(master, option)
end
def cget(master, option)
itemcget(master, option)
end
def cget_strict(master, option)
itemcget_strict(master, option)
end
def configure(master, slot, value=None)
itemconfigure(master, slot, value)
end
def configinfo(master, slot=nil)
itemconfiginfo(master, slot)
end
def current_configinfo(master, slot=nil)
current_itemconfiginfo(master, slot)
end
end
##############################
def self.edit(master, *args)
tk_call('::blt::ted', 'edit', master, *args)
end
def self.rep(master, *args)
tk_call('::blt::ted', 'rep', master, *args)
end
def self.select(master, *args)
tk_call('::blt::ted', 'select', master, *args)
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/lib/ohai/plugins/openstack.rb
|
<filename>.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/lib/ohai/plugins/openstack.rb
#
# Author:: <NAME> (<<EMAIL>>)
# Copyright:: Copyright (c) 2012 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
provides "openstack"
require 'ohai/mixin/ec2_metadata'
extend Ohai::Mixin::Ec2Metadata
# does it matter that it's not hitting latest?
#Ec2Metadata::EC2_METADATA_URL = "/latest/meta-data"
# Adds openstack Mash
if hint?('openstack') || hint?('hp')
Ohai::Log.debug("ohai openstack")
openstack Mash.new
#for now, use the metadata service
if can_metadata_connect?(EC2_METADATA_ADDR,80)
Ohai::Log.debug("connecting to the OpenStack metadata service")
self.fetch_metadata.each {|k, v| openstack[k] = v }
case
when hint?('hp')
openstack['provider'] = 'hp'
else
openstack['provider'] = 'openstack'
end
else
Ohai::Log.debug("unable to connect to the OpenStack metadata service")
end
else
Ohai::Log.debug("NOT ohai openstack")
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/rubyntlm-0.6.0/lib/net/ntlm/exceptions.rb
|
module Net
module NTLM
class NtlmError < StandardError; end
class InvalidTargetDataError < NtlmError
attr_reader :data
def initialize(msg, data)
@data = data
super(msg)
end
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/openstack/requests/identity/create_ec2_credential.rb
|
module Fog
module Identity
class OpenStack
class Real
##
# Create an EC2 credential for a user in a tenant. Requires
# administrator credentials.
#
# ==== Parameters
# * user_id<~String>: The id of the user to create an EC2 credential
# for
# * tenant_id<~String>: The id of the tenant to create the credential
# in
#
# ==== Returns
# * response<~Excon::Response>:
# * body<~Hash>:
# * 'credential'<~Hash>: Created EC2 credential
# * 'access'<~String>: The access key
# * 'secret'<~String>: The secret key
# * 'user_id'<~String>: The user id
# * 'tenant_id'<~String>: The tenant id
def create_ec2_credential(user_id, tenant_id)
data = { 'tenant_id' => tenant_id }
request(
:body => Fog::JSON.encode(data),
:expects => [200, 202],
:method => 'POST',
:path => "users/#{user_id}/credentials/OS-EC2"
)
end
end
class Mock
def create_ec2_credential(user_id, tenant_id)
response = Excon::Response.new
response.status = 200
data = {
'access' => Fog::Mock.random_hex(32),
'secret' => Fog::Mock.random_hex(32),
'tenant_id' => tenant_id,
'user_id' => user_id,
}
self.data[:ec2_credentials][user_id][data['access']] = data
response.body = { 'credential' => data }
response
end
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/rdoc/test_rdoc_stats.rb
|
# frozen_string_literal: false
require 'rdoc/test_case'
class TestRDocStats < RDoc::TestCase
def setup
super
@s = RDoc::Stats.new @store, 0
@tl = @store.add_file 'file.rb'
@tl.parser = RDoc::Parser::Ruby
end
def test_doc_stats
c = RDoc::CodeObject.new
assert_equal [1, 1], @s.doc_stats([c])
end
def test_doc_stats_documented
c = RDoc::CodeObject.new
c.comment = comment 'x'
assert_equal [1, 0], @s.doc_stats([c])
end
def test_doc_stats_display_eh
c = RDoc::CodeObject.new
c.ignore
assert_equal [0, 0], @s.doc_stats([c])
end
def test_report_attr
c = @tl.add_class RDoc::NormalClass, 'C'
c.record_location @tl
c.add_comment 'C', @tl
a = RDoc::Attr.new nil, 'a', 'RW', nil
a.record_location @tl
c.add_attribute a
@store.complete :public
report = @s.report
expected =
doc(
para('The following items are not documented:'),
blank_line,
verb(
"class C # is documented\n",
"\n",
" attr_accessor :a # in file file.rb\n",
"\n",
"end\n"),
blank_line)
assert_equal expected, report
end
def test_report_attr_documented
c = @tl.add_class RDoc::NormalClass, 'C'
c.record_location @tl
c.add_comment 'C', @tl
a = RDoc::Attr.new nil, 'a', 'RW', 'a'
a.record_location @tl
c.add_attribute a
@store.complete :public
report = @s.report
assert_equal @s.great_job, report
end
def test_report_attr_line
c = @tl.add_class RDoc::NormalClass, 'C'
c.record_location @tl
c.add_comment 'C', @tl
a = RDoc::Attr.new nil, 'a', 'RW', nil
a.record_location @tl
a.line = 3
c.add_attribute a
@store.complete :public
assert_match '# in file file.rb:3', @s.report.accept(to_rdoc)
end
def test_report_constant
m = @tl.add_module RDoc::NormalModule, 'M'
m.record_location @tl
m.add_comment 'M', @tl
c = RDoc::Constant.new 'C', nil, nil
c.record_location @tl
m.add_constant c
@store.complete :public
report = @s.report
expected =
doc(
para('The following items are not documented:'),
blank_line,
verb(
"module M # is documented\n",
"\n",
" # in file file.rb\n",
" C = nil\n",
"\n",
"end\n"),
blank_line)
assert_equal expected, report
end
def test_report_constant_alias
mod = @tl.add_module RDoc::NormalModule, 'M'
c = @tl.add_class RDoc::NormalClass, 'C'
mod.add_constant c
ca = RDoc::Constant.new 'CA', nil, nil
ca.is_alias_for = c
@tl.add_constant ca
@store.complete :public
report = @s.report
# TODO change this to refute match, aliases should be ignored as they are
# programmer convenience constructs
assert_match 'class Object', report.accept(to_rdoc)
end
def test_report_constant_documented
m = @tl.add_module RDoc::NormalModule, 'M'
m.record_location @tl
m.add_comment 'M', @tl
c = RDoc::Constant.new 'C', nil, 'C'
c.record_location @tl
m.add_constant c
@store.complete :public
report = @s.report
assert_equal @s.great_job, report
end
def test_report_constant_line
m = @tl.add_module RDoc::NormalModule, 'M'
m.record_location @tl
m.add_comment 'M', @tl
c = RDoc::Constant.new 'C', nil, nil
c.record_location @tl
c.line = 5
m.add_constant c
@store.complete :public
assert_match '# in file file.rb:5', @s.report.accept(to_rdoc)
end
def test_report_class
c = @tl.add_class RDoc::NormalClass, 'C'
c.record_location @tl
m = RDoc::AnyMethod.new nil, 'm'
m.record_location @tl
c.add_method m
m.comment = 'm'
@store.complete :public
report = @s.report
expected =
doc(
para('The following items are not documented:'),
blank_line,
para('In files:'),
list(:BULLET, *[
item(nil, para('file.rb'))]),
blank_line,
verb("class C\n", "end\n"),
blank_line)
assert_equal expected, report
end
def test_report_skip_object
c = @tl.add_class RDoc::NormalClass, 'Object'
c.record_location @tl
m = RDoc::AnyMethod.new nil, 'm'
m.record_location @tl
c.add_method m
m.comment = 'm'
@store.complete :public
refute_match %r%^class Object$%, @s.report.accept(to_rdoc)
end
def test_report_class_documented
c = @tl.add_class RDoc::NormalClass, 'C'
c.record_location @tl
c.add_comment 'C', @tl
m = RDoc::AnyMethod.new nil, 'm'
m.record_location @tl
c.add_method m
m.comment = 'm'
@store.complete :public
report = @s.report
assert_equal @s.great_job, report
end
def test_report_class_documented_level_1
c1 = @tl.add_class RDoc::NormalClass, 'C1'
c1.record_location @tl
c1.add_comment 'C1', @tl
m1 = RDoc::AnyMethod.new nil, 'm1'
m1.record_location @tl
c1.add_method m1
m1.comment = 'm1'
c2 = @tl.add_class RDoc::NormalClass, 'C2'
c2.record_location @tl
m2 = RDoc::AnyMethod.new nil, 'm2'
m2.record_location @tl
c2.add_method m2
m2.comment = 'm2'
@store.complete :public
@s.coverage_level = 1
report = @s.report
expected =
doc(
para('The following items are not documented:'),
blank_line,
para('In files:'),
list(:BULLET, *[
item(nil, para('file.rb'))]),
blank_line,
verb("class C2\n", "end\n"),
blank_line)
assert_equal expected, report
end
def test_report_class_empty
@tl.add_class RDoc::NormalClass, 'C'
@store.complete :public
report = @s.report
expected =
doc(
para('The following items are not documented:'),
blank_line,
para('class C is referenced but empty.'),
para("It probably came from another project. I'm sorry I'm holding it against you."),
blank_line)
assert_equal expected, report
end
def test_report_class_empty_2
c1 = @tl.add_class RDoc::NormalClass, 'C1'
c1.record_location @tl
c2 = @tl.add_class RDoc::NormalClass, 'C2'
c2.record_location @tl
c2.add_comment 'C2', @tl
@store.complete :public
@s.coverage_level = 1
report = @s.report
expected =
doc(
para('The following items are not documented:'),
blank_line,
para('In files:'),
list(:BULLET, *[
item(nil, para('file.rb'))]),
blank_line,
verb("class C1\n", "end\n"),
blank_line)
assert_equal expected, report
end
def test_report_class_method_documented
c = @tl.add_class RDoc::NormalClass, 'C'
c.record_location @tl
m = RDoc::AnyMethod.new nil, 'm'
m.record_location @tl
c.add_method m
m.comment = 'm'
@store.complete :public
report = @s.report
expected =
doc(
para('The following items are not documented:'),
blank_line,
para('In files:'),
list(:BULLET, *[
item(nil, para('file.rb'))]),
blank_line,
verb("class C\n", "end\n"),
blank_line)
assert_equal expected, report
end
def test_report_class_module_ignore
c = @tl.add_class RDoc::NormalClass, 'C'
c.ignore
@store.complete :public
report = @s.report_class_module c
assert_nil report
end
def test_report_empty
@store.complete :public
report = @s.report
assert_equal @s.great_job, report
end
def test_report_method
c = @tl.add_class RDoc::NormalClass, 'C'
c.record_location @tl
c.add_comment 'C', @tl
m1 = RDoc::AnyMethod.new nil, 'm1'
m1.record_location @tl
c.add_method m1
m2 = RDoc::AnyMethod.new nil, 'm2'
m2.record_location @tl
c.add_method m2
m2.comment = 'm2'
@store.complete :public
report = @s.report
expected =
doc(
para('The following items are not documented:'),
blank_line,
verb(*[
"class C # is documented\n",
"\n",
" # in file file.rb\n",
" def m1; end\n",
"\n",
"end\n"]),
blank_line)
assert_equal expected, report
end
def test_report_method_class
c = @tl.add_class RDoc::NormalClass, 'C'
c.record_location @tl
c.add_comment 'C', @tl
m1 = RDoc::AnyMethod.new nil, 'm1'
m1.record_location @tl
m1.singleton = true
c.add_method m1
m2 = RDoc::AnyMethod.new nil, 'm2'
m2.record_location @tl
m2.singleton = true
c.add_method m2
m2.comment = 'm2'
@store.complete :public
report = @s.report
expected =
doc(
para('The following items are not documented:'),
blank_line,
verb(*[
"class C # is documented\n",
"\n",
" # in file file.rb\n",
" def self.m1; end\n",
"\n",
"end\n"]),
blank_line)
assert_equal expected, report
end
def test_report_method_documented
c = @tl.add_class RDoc::NormalClass, 'C'
c.record_location @tl
c.add_comment 'C', @tl
m = RDoc::AnyMethod.new nil, 'm'
m.record_location @tl
c.add_method m
m.comment = 'm'
@store.complete :public
report = @s.report
assert_equal @s.great_job, report
end
def test_report_method_line
c = @tl.add_class RDoc::NormalClass, 'C'
c.record_location @tl
c.add_comment 'C', @tl
m1 = RDoc::AnyMethod.new nil, 'm1'
m1.record_location @tl
m1.line = 4
c.add_method m1
@store.complete :public
assert_match '# in file file.rb:4', @s.report.accept(to_rdoc)
end
def test_report_method_parameters
c = @tl.add_class RDoc::NormalClass, 'C'
c.record_location @tl
c.add_comment 'C', @tl
m1 = RDoc::AnyMethod.new nil, 'm1'
m1.record_location @tl
m1.params = '(p1, p2)'
m1.comment = 'Stuff with +p1+'
c.add_method m1
m2 = RDoc::AnyMethod.new nil, 'm2'
m2.record_location @tl
c.add_method m2
m2.comment = 'm2'
@store.complete :public
@s.coverage_level = 1
report = @s.report
expected =
doc(
para('The following items are not documented:'),
blank_line,
verb(*[
"class C # is documented\n",
"\n",
" # in file file.rb\n",
" # +p2+ is not documented\n",
" def m1(p1, p2); end\n",
"\n",
"end\n"]),
blank_line)
assert_equal expected, report
end
def test_report_method_parameters_documented
@tl.parser = RDoc::Parser::Ruby
c = @tl.add_class RDoc::NormalClass, 'C'
c.record_location @tl
c.add_comment 'C', @tl
m = RDoc::AnyMethod.new nil, 'm'
m.record_location @tl
m.params = '(p1)'
m.comment = 'Stuff with +p1+'
c.add_method m
@store.complete :public
@s.coverage_level = 1
report = @s.report
assert_equal @s.great_job, report
end
def test_report_method_parameters_yield
c = @tl.add_class RDoc::NormalClass, 'C'
c.record_location @tl
c.add_comment 'C', @tl
m = RDoc::AnyMethod.new nil, 'm'
m.record_location @tl
m.call_seq = <<-SEQ
m(a) { |c| ... }
m(a, b) { |c, d| ... }
SEQ
m.comment = 'Stuff with +a+, yields +c+ for you to do stuff with'
c.add_method m
@store.complete :public
@s.coverage_level = 1
report = @s.report
expected =
doc(
para('The following items are not documented:'),
blank_line,
verb(
"class C # is documented\n",
"\n",
" # in file file.rb\n",
" # +b+, +d+ is not documented\n",
" def m; end\n",
"\n",
"end\n"),
blank_line)
assert_equal expected, report
end
def test_summary
c = @tl.add_class RDoc::NormalClass, 'C'
c.record_location @tl
m = @tl.add_module RDoc::NormalModule, 'M'
m.record_location @tl
a = RDoc::Attr.new nil, 'a', 'RW', nil
a.record_location @tl
c.add_attribute a
c_c = RDoc::Constant.new 'C', nil, nil
c_c.record_location @tl
c.add_constant c_c
m = RDoc::AnyMethod.new nil, 'm'
m.record_location @tl
c.add_method m
@store.complete :public
summary = @s.summary.accept to_rdoc
summary.sub!(/ Elapsed:.*/m, '')
expected = <<-EXPECTED
Files: 0
Classes: 1 (1 undocumented)
Modules: 1 (1 undocumented)
Constants: 1 (1 undocumented)
Attributes: 1 (1 undocumented)
Methods: 1 (1 undocumented)
Total: 5 (5 undocumented)
0.00% documented
EXPECTED
assert_equal summary, expected
end
def test_summary_level_false
c = @tl.add_class RDoc::NormalClass, 'C'
c.record_location @tl
@store.complete :public
@s.coverage_level = false
summary = @s.summary.accept to_rdoc
summary.sub!(/ Elapsed:.*/m, '')
expected = <<-EXPECTED
Files: 0
Classes: 1 (1 undocumented)
Modules: 0 (0 undocumented)
Constants: 0 (0 undocumented)
Attributes: 0 (0 undocumented)
Methods: 0 (0 undocumented)
Total: 1 (1 undocumented)
0.00% documented
EXPECTED
assert_equal summary, expected
end
def test_summary_level_1
c = @tl.add_class RDoc::NormalClass, 'C'
c.record_location @tl
c.add_comment 'C', @tl
m = RDoc::AnyMethod.new nil, 'm'
m.record_location @tl
m.params = '(p1, p2)'
m.comment = 'Stuff with +p1+'
c.add_method m
@store.complete :public
@s.coverage_level = 1
@s.report
summary = @s.summary.accept to_rdoc
summary.sub!(/ Elapsed:.*/m, '')
expected = <<-EXPECTED
Files: 0
Classes: 1 (0 undocumented)
Modules: 0 (0 undocumented)
Constants: 0 (0 undocumented)
Attributes: 0 (0 undocumented)
Methods: 1 (0 undocumented)
Parameters: 2 (1 undocumented)
Total: 4 (1 undocumented)
75.00% documented
EXPECTED
assert_equal summary, expected
end
def to_rdoc
RDoc::Markup::ToRdoc.new
end
def test_undoc_params
method = RDoc::AnyMethod.new [], 'm'
method.params = '(a)'
method.comment = comment 'comment'
total, undoc = @s.undoc_params method
assert_equal 1, total
assert_equal %w[a], undoc
end
def test_undoc_params_block
method = RDoc::AnyMethod.new [], 'm'
method.params = '(&a)'
method.comment = comment '+a+'
total, undoc = @s.undoc_params method
assert_equal 1, total
assert_empty undoc
end
def test_undoc_params_documented
method = RDoc::AnyMethod.new [], 'm'
method.params = '(a)'
method.comment = comment '+a+'
total, undoc = @s.undoc_params method
assert_equal 1, total
assert_empty undoc
end
def test_undoc_params_keywords
method = RDoc::AnyMethod.new [], 'm'
method.params = '(**a)'
method.comment = comment '+a+'
total, undoc = @s.undoc_params method
assert_equal 1, total
assert_empty undoc
end
def test_undoc_params_splat
method = RDoc::AnyMethod.new [], 'm'
method.params = '(*a)'
method.comment = comment '+a+'
total, undoc = @s.undoc_params method
assert_equal 1, total
assert_empty undoc
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/tcllib/ntext.rb
|
<gh_stars>1-10
#
# tkextlib/tcllib/ntext.rb
# by <NAME> (<EMAIL>)
#
# * Part of tcllib extension
# * Ntext bindtag
#
require 'tk'
require 'tkextlib/tcllib.rb'
# TkPackage.require('ntext', '0.81')
TkPackage.require('ntext')
module Tk::Tcllib
Ntext = TkBindTag.new_by_name('Ntext')
end
# variables
Tk::Tcllib::Ntext.instance_eval{
# boolean
@classicAnchor = TkVarAccess.new('::ntext::classicAnchor')
@classicExtras = TkVarAccess.new('::ntext::classicExtras')
@classicMouseSelect = TkVarAccess.new('::ntext::classicMouseSelect')
@classicWordBreak = TkVarAccess.new('::ntext::classicWordBreak')
@classicWrap = TkVarAccess.new('::ntext::classicWrap')
@overwrite = TkVarAccess.new('::ntext::overwrite')
# regexp
@newWrapRegexp = TkVarAccess.new('::ntext::newWrapRegexp')
# variables (advanced use)
@tcl_match_wordBreakAfter = TkVarAccess.new('::ntext::tcl_match_wordBreakAfter')
@tcl_match_wordBreakBefore = TkVarAccess.new('::ntext::tcl_match_wordBreakBefore')
@tcl_match_endOfWord = TkVarAccess.new('::ntext::tcl_match_endOfWord')
@tcl_match_startOfNextWord = TkVarAccess.new('::ntext::tcl_match_startOfNextWord')
@tcl_match_startOfPreviousWord = TkVarAccess.new('::ntext::tcl_match_startOfPreviousWord')
}
class << Tk::Tcllib::Ntext
def wrapIndent(txt, *args)
TK.tk_call('::next::wrapIndent', txt, *args)
end
def initializeMatchPatterns
TK.tk_call('::next::initializeMatchPatterns')
self
end
def createMatchPatterns(*args)
TK.tk_call('::next::createMatchPatterns', *args)
self
end
# functions (advanced use)
#ntext::new_wordBreakAfter
#ntext::new_wordBreakBefore
#ntext::new_endOfWord
#ntext::new_startOfNextWord
#ntext::new_startOfPreviousWord
# accessor
def classicAnchor
@classicAnchor.bool
end
def classicAnchor=(mode)
@classicAnchor.bool = mode
end
def classicExtras
@classicExtras.bool
end
def classicExtras=(mode)
@classicExtras.bool = mode
end
def classicMouseSelect
@classicMouseSelect.bool
end
def classicMouseSelect=(mode)
@classicMouseSelect.bool = mode
end
def classicWordBreak
@classicWordBreak.bool
end
def classicWordBreak=(mode)
@classicWordBreak.bool = mode
end
def classicWrap
@classicWrap.bool
end
def classicWrap=(mode)
@classicWrap.bool = mode
end
def overwrite
@overwrite.bool
end
def overwrite=(mode)
@classic.bool = mode
end
def newWrapRegexp
@newWrapRegexp.value
end
def newWrapRegexp=(val)
@newWrapRegexp.value = val
end
def tcl_match_wordBreakAfter
@tcl_match_wordBreakAfter.value
end
def tcl_match_wordBreakAfter=(val)
@tcl_match_wordBreakAfter.value = val
end
def tcl_match_wordBreakBefore
@tcl_match_wordBreakBefore.value
end
def tcl_match_wordBreakBefore=(val)
@tcl_match_wordBreakBefore.value = val
end
def tcl_match_endOfWord
@tcl_match_endOfWord.value
end
def tcl_match_endOfWord=(val)
@tcl_match_endOfWord.value = val
end
def tcl_match_startOfNextWord
@tcl_match_startOfNextWord.value
end
def tcl_match_startOfNextWord=(val)
@tcl_match_startOfNextWord.value = val
end
def tcl_match_startOfPreviousWord
@tcl_match_startOfPreviousWord.value
end
def tcl_match_startOfPreviousWord=(val)
@tcl_match_startOfPreviousWord.value = val
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/lib/shell/filter.rb
|
<gh_stars>0
#
# shell/filter.rb -
# $Release Version: 0.7 $
# $Revision: 31641 $
# by <NAME>(<EMAIL>)
#
# --
#
#
#
class Shell
#
# Filter
# A method to require
# each()
#
class Filter
include Enumerable
def initialize(sh)
@shell = sh # parent shell
@input = nil # input filter
end
attr_reader :input
def input=(filter)
@input = filter
end
def each(rs = nil)
rs = @shell.record_separator unless rs
if @input
@input.each(rs){|l| yield l}
end
end
def < (src)
case src
when String
cat = Cat.new(@shell, src)
cat | self
when IO
self.input = src
self
else
Shell.Fail Error::CantApplyMethod, "<", to.class
end
end
def > (to)
case to
when String
dst = @shell.open(to, "w")
begin
each(){|l| dst << l}
ensure
dst.close
end
when IO
each(){|l| to << l}
else
Shell.Fail Error::CantApplyMethod, ">", to.class
end
self
end
def >> (to)
begin
Shell.cd(@shell.pwd).append(to, self)
rescue CantApplyMethod
Shell.Fail Error::CantApplyMethod, ">>", to.class
end
end
def | (filter)
filter.input = self
if active?
@shell.process_controller.start_job filter
end
filter
end
def + (filter)
Join.new(@shell, self, filter)
end
def to_a
ary = []
each(){|l| ary.push l}
ary
end
def to_s
str = ""
each(){|l| str.concat l}
str
end
def inspect
if @shell.debug.kind_of?(Integer) && @shell.debug > 2
super
else
to_s
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/tool/id2token.rb
|
<gh_stars>0
#! /usr/bin/ruby -p
# -*- coding: us-ascii -*-
BEGIN {
require 'optparse'
$:.unshift(File.dirname(__FILE__))
require 'vpath'
vpath = VPath.new
header = nil
opt = OptionParser.new do |o|
vpath.def_options(o)
header = o.order!(ARGV).shift
end or abort opt.opt_s
TOKENS = {}
h = vpath.read(header) rescue abort("#{header} not found in #{vpath.inspect}")
h.scan(/^#define\s+RUBY_TOKEN_(\w+)\s+(\d+)/) do |token, id|
TOKENS[token] = id
end
TOKENS_RE = /\bRUBY_TOKEN\((#{TOKENS.keys.join('|')})\)\s*(?=\s)/
}
$_.gsub!(TOKENS_RE) {TOKENS[$1]} if /^%token/ =~ $_
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/demos-en/paned2.rb
|
# paned2.rb --
#
# This demonstration script creates a toplevel window containing
# a paned window that separates two windows vertically.
#
# based on "Id: paned2.tcl,v 1.1 2002/02/22 14:07:01 dkf Exp"
if defined?($paned2_demo) && $paned2_demo
$paned2_demo.destroy
$paned2_demo = nil
end
$paned2_demo = TkToplevel.new {|w|
title("Vertical Paned Window Demonstration")
iconname("paned2")
positionWindow(w)
}
base_frame = TkFrame.new($paned2_demo).pack(:fill=>:both, :expand=>true)
TkLabel.new(base_frame,
:font=>$font, :wraplength=>'4i', :justify=>:left,
:text=><<EOL).pack(:side=>:top)
The sash between the two scrolled windows below can be used to divide the area between them. Use the left mouse button to resize without redrawing by just moving the sash, and use the middle mouse button to resize opaquely (always redrawing the windows in each position.)
If your Tk library linked to Ruby doesn't include a 'panedwindow', this demo doesn't work. Please use later version of Tk which supports a 'panedwindow'.
EOL
# The bottom buttons
TkFrame.new(base_frame){|f|
pack(:side=>:bottom, :fill=>:x, :pady=>'2m')
TkButton.new(f, :text=>'Dismiss', :width=>15, :command=>proc{
$paned2_demo.destroy
$paned2_demo = nil
}).pack(:side=>:left, :expand=>true)
TkButton.new(f, :text=>'See Code', :width=>15, :command=>proc{
showCode 'paned2'
}).pack(:side=>:left, :expand=>true)
}
paneList = TkVariable.new # define as normal variable (not array)
paneList.value = [ # ruby's array --> tcl's list
'List of Ruby/Tk Widgets',
'TkButton',
'TkCanvas',
'TkCheckbutton',
'TkEntry',
'TkFrame',
'TkLabel',
'TkLabelframe',
'TkListbox',
'TkMenu',
'TkMenubutton',
'TkMessage',
'TkPanedwindow',
'TkRadiobutton',
'TkScale',
'TkScrollbar',
'TkSpinbox',
'TkText',
'TkToplevel'
]
# Create the pane itself
TkPanedwindow.new(base_frame, :orient=>:vertical){|f|
pack(:side=>:top, :expand=>true, :fill=>:both, :pady=>2, :padx=>'2m')
add(TkFrame.new(f){|paned2_top|
TkListbox.new(paned2_top, :listvariable=>paneList) {
# Invert the first item to highlight it
itemconfigure(0, :background=>self.cget(:foreground),
:foreground=>self.cget(:background) )
yscrollbar(TkScrollbar.new(paned2_top).pack(:side=>:right,
:fill=>:y))
pack(:fill=>:both, :expand=>true)
}
},
TkFrame.new(f, :height=>120) {|paned2_bottom|
# The bottom window is a text widget with scrollbar
paned2_xscr = TkScrollbar.new(paned2_bottom)
paned2_yscr = TkScrollbar.new(paned2_bottom)
paned2_text = TkText.new(paned2_bottom, :width=>30, :wrap=>:non) {
insert('1.0', "This is just a normal text widget")
xscrollbar(paned2_xscr)
yscrollbar(paned2_yscr)
}
Tk.grid(paned2_text, paned2_yscr, :sticky=>'nsew')
Tk.grid(paned2_xscr, :sticky=>'nsew')
TkGrid.columnconfigure(paned2_bottom, 0, :weight=>1)
TkGrid.rowconfigure(paned2_bottom, 0, :weight=>1)
} )
}
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/win32ole/extconf.rb
|
<reponame>arnab0073/idea
#----------------------------------
# extconf.rb
# $Revision: 31121 $
#----------------------------------
require 'mkmf'
case RUBY_PLATFORM
when /cygwin/
inc = nil
lib = '/usr/lib/w32api'
end
dir_config("win32", inc, lib)
def create_win32ole_makefile
if have_library("ole32") and
have_library("oleaut32") and
have_library("uuid", "&CLSID_CMultiLanguage", "mlang.h") and
have_library("user32") and
have_library("kernel32") and
have_library("advapi32") and
have_header("windows.h")
unless have_type("IMultiLanguage2", "mlang.h")
have_type("IMultiLanguage", "mlang.h")
end
create_makefile("win32ole")
end
end
case RUBY_PLATFORM
when /mswin/
$CFLAGS += ' /W3'
end
create_win32ole_makefile
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/date/test_date_conv.rb
|
<gh_stars>1-10
# frozen_string_literal: false
require 'test/unit'
require 'date'
class TestDateConv < Test::Unit::TestCase
def test_to_class
[Time.now, Date.today, DateTime.now].each do |o|
assert_instance_of(Time, o.to_time)
assert_instance_of(Date, o.to_date)
assert_instance_of(DateTime, o.to_datetime)
end
end
def test_to_time__from_time
t = Time.mktime(2004, 9, 19, 1, 2, 3, 456789)
t2 = t.to_time
assert_equal([2004, 9, 19, 1, 2, 3, 456789],
[t2.year, t2.mon, t2.mday, t2.hour, t2.min, t2.sec, t2.usec])
t = Time.utc(2004, 9, 19, 1, 2, 3, 456789)
t2 = t.to_time.utc
assert_equal([2004, 9, 19, 1, 2, 3, 456789],
[t2.year, t2.mon, t2.mday, t2.hour, t2.min, t2.sec, t2.usec])
end
def test_to_time__from_date
d = Date.new(2004, 9, 19)
t = d.to_time
assert_equal([2004, 9, 19, 0, 0, 0, 0],
[t.year, t.mon, t.mday, t.hour, t.min, t.sec, t.usec])
end
def test_to_time__from_datetime
d = DateTime.new(2004, 9, 19, 1, 2, 3, 9.to_r/24) + 456789.to_r/86400000000
t = d.to_time
if t.utc_offset == 9*60*60
assert_equal([2004, 9, 19, 1, 2, 3, 456789],
[t.year, t.mon, t.mday, t.hour, t.min, t.sec, t.usec])
end
d = DateTime.new(2004, 9, 19, 1, 2, 3, 0) + 456789.to_r/86400000000
t = d.to_time.utc
assert_equal([2004, 9, 19, 1, 2, 3, 456789],
[t.year, t.mon, t.mday, t.hour, t.min, t.sec, t.usec])
if Time.allocate.respond_to?(:nsec)
d = DateTime.new(2004, 9, 19, 1, 2, 3, 0) + 456789123.to_r/86400000000000
t = d.to_time.utc
assert_equal([2004, 9, 19, 1, 2, 3, 456789123],
[t.year, t.mon, t.mday, t.hour, t.min, t.sec, t.nsec])
end
if Time.allocate.respond_to?(:subsec)
d = DateTime.new(2004, 9, 19, 1, 2, 3, 0) + 456789123456789123.to_r/86400000000000000000000
t = d.to_time.utc
assert_equal([2004, 9, 19, 1, 2, 3, Rational(456789123456789123,1000000000000000000)],
[t.year, t.mon, t.mday, t.hour, t.min, t.sec, t.subsec])
end
end
def test_to_date__from_time
t = Time.mktime(2004, 9, 19, 1, 2, 3, 456789)
d = t.to_date
assert_equal([2004, 9, 19, 0], [d.year, d.mon, d.mday, d.day_fraction])
t = Time.utc(2004, 9, 19, 1, 2, 3, 456789)
d = t.to_date
assert_equal([2004, 9, 19, 0], [d.year, d.mon, d.mday, d.day_fraction])
end
def test_to_date__from_date
d = Date.new(2004, 9, 19) + 1.to_r/2
d2 = d.to_date
assert_equal([2004, 9, 19, 1.to_r/2],
[d2.year, d2.mon, d2.mday, d2.day_fraction])
end
def test_to_date__from_datetime
d = DateTime.new(2004, 9, 19, 1, 2, 3, 9.to_r/24) + 456789.to_r/86400000000
d2 = d.to_date
assert_equal([2004, 9, 19, 0], [d2.year, d2.mon, d2.mday, d2.day_fraction])
d = DateTime.new(2004, 9, 19, 1, 2, 3, 0) + 456789.to_r/86400000000
d2 = d.to_date
assert_equal([2004, 9, 19, 0], [d2.year, d2.mon, d2.mday, d2.day_fraction])
end
def test_to_datetime__from_time
t = Time.mktime(2004, 9, 19, 1, 2, 3, 456789)
d = t.to_datetime
assert_equal([2004, 9, 19, 1, 2, 3,
456789.to_r/1000000,
t.utc_offset.to_r/86400],
[d.year, d.mon, d.mday, d.hour, d.min, d.sec,
d.sec_fraction, d.offset])
t = Time.utc(2004, 9, 19, 1, 2, 3, 456789)
d = t.to_datetime
assert_equal([2004, 9, 19, 1, 2, 3,
456789.to_r/1000000,
0],
[d.year, d.mon, d.mday, d.hour, d.min, d.sec,
d.sec_fraction, d.offset])
t = Time.now
d = t.to_datetime
require 'time'
assert_equal(t.iso8601(10), d.iso8601(10))
end
def test_to_datetime__from_date
d = Date.new(2004, 9, 19) + 1.to_r/2
d2 = d.to_datetime
assert_equal([2004, 9, 19, 0, 0, 0, 0, 0],
[d2.year, d2.mon, d2.mday, d2.hour, d2.min, d2.sec,
d2.sec_fraction, d2.offset])
end
def test_to_datetime__from_datetime
d = DateTime.new(2004, 9, 19, 1, 2, 3, 9.to_r/24) + 456789.to_r/86400000000
d2 = d.to_datetime
assert_equal([2004, 9, 19, 1, 2, 3,
456789.to_r/1000000,
9.to_r/24],
[d2.year, d2.mon, d2.mday, d2.hour, d2.min, d2.sec,
d2.sec_fraction, d2.offset])
d = DateTime.new(2004, 9, 19, 1, 2, 3, 0) + 456789.to_r/86400000000
d2 = d.to_datetime
assert_equal([2004, 9, 19, 1, 2, 3,
456789.to_r/1000000,
0],
[d2.year, d2.mon, d2.mday, d2.hour, d2.min, d2.sec,
d2.sec_fraction, d2.offset])
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/demos-en/paned1.rb
|
# paned1.rb
#
# This demonstration script creates a toplevel window containing
# a paned window that separates two windows horizontally.
#
# based on "Id: paned1.tcl,v 1.1 2002/02/22 14:07:01 dkf Exp"
if defined?($paned1_demo) && $paned1_demo
$paned1_demo.destroy
$paned1_demo = nil
end
$paned1_demo = TkToplevel.new {|w|
title("Horizontal Paned Window Demonstration")
iconname("paned1")
positionWindow(w)
}
base_frame = TkFrame.new($paned1_demo).pack(:fill=>:both, :expand=>true)
TkLabel.new(base_frame,
:font=>$font, :wraplength=>'4i', :justify=>:left,
:text=><<EOL).pack(:side=>:top)
The sash between the two coloured windows below can be used to divide the area between them. Use the left mouse button to resize without redrawing by just moving the sash, and use the middle mouse button to resize opaquely (always redrawing the windows in each position.)
If your Tk library linked to Ruby doesn't include a 'panedwindow', this demo doesn't work. Please use later version of Tk which supports a 'panedwindow'.
EOL
# The bottom buttons
TkFrame.new(base_frame){|f|
pack(:side=>:bottom, :fill=>:x, :pady=>'2m')
TkButton.new(f, :text=>'Dismiss', :width=>15, :command=>proc{
$paned1_demo.destroy
$paned1_demo = nil
}).pack(:side=>:left, :expand=>true)
TkButton.new(f, :text=>'See Code', :width=>15, :command=>proc{
showCode 'paned1'
}).pack(:side=>:left, :expand=>true)
}
TkPanedwindow.new(base_frame, :orient=>:horizontal){|f|
add(Tk::Label.new(f, :text=>"This is the\nleft side", :bg=>'yellow'),
Tk::Label.new(f, :text=>"This is the\nright side", :bg=>'cyan'))
pack(:side=>:top, :expand=>true, :fill=>:both, :pady=>2, :padx=>'2m')
}
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/tile/tframe.rb
|
#
# tframe widget
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tkextlib/tile.rb'
module Tk
module Tile
class TFrame < Tk::Frame
end
Frame = TFrame
end
end
class Tk::Tile::TFrame < Tk::Frame
include Tk::Tile::TileWidget
if Tk::Tile::USE_TTK_NAMESPACE
TkCommandNames = ['::ttk::frame'.freeze].freeze
else
TkCommandNames = ['::tframe'.freeze].freeze
end
WidgetClassName = 'TFrame'.freeze
WidgetClassNames[WidgetClassName] ||= self
def self.style(*args)
[self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
end
end
#Tk.__set_toplevel_aliases__(:Ttk, Tk::Tile::Frame, :TkFrame)
Tk.__set_loaded_toplevel_aliases__('tkextlib/tile/tframe.rb',
:Ttk, Tk::Tile::Frame, :TkFrame)
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/-test-/funcall/extconf.rb
|
require 'mkmf'
create_makefile("-test-/funcall/funcall")
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tk/busy.rb
|
#
# tk/busy.rb: support 'tk busy' command (Tcl/Tk8.6 or later)
#
require 'tk'
module Tk::Busy
include TkCore
extend TkCore
extend TkItemConfigMethod
end
class << Tk::Busy
def __item_cget_cmd(win)
# maybe need to override
['tk', 'busy', 'cget', win.path]
end
private :__item_cget_cmd
def __item_config_cmd(win)
# maybe need to override
['tk', 'busy', 'configure', win.path]
end
private :__item_config_cmd
def __item_confinfo_cmd(win)
# maybe need to override
__item_config_cmd(win)
end
private :__item_confinfo_cmd
alias cget_tkstring itemcget_tkstring
alias cget itemcget
alias cget_strict itemcget_strict
alias configure itemconfigure
alias configinfo itemconfiginfo
alias current_configinfo current_itemconfiginfo
private :itemcget_tkstring, :itemcget, :itemcget_strict
private :itemconfigure, :itemconfiginfo, :current_itemconfiginfo
def method_missing(id, *args)
name = id.id2name
case args.length
when 1
if name[-1] == ?=
configure name[0..-2], args[0]
args[0]
else
configure name, args[0]
self
end
when 0
begin
cget(name)
rescue
super(id, *args)
end
else
super(id, *args)
end
end
def hold(win, keys={})
tk_call_without_enc('tk', 'busy', 'hold', win, *hash_kv(keys))
win
end
def forget(*wins)
tk_call_without_enc('tk', 'busy', 'forget', *wins)
self
end
def current(pat=None)
list(tk_call('tk', 'busy', 'current', pat))
end
def status(win)
bool(tk_call_without_enc('tk', 'busy', 'status', win))
end
end
module Tk::Busy
def busy_configinfo(option=nil)
Tk::Busy.configinfo(self, option)
end
def busy_current_configinfo(option=nil)
Tk::Busy.current_configinfo(self, option)
end
def busy_configure(option, value=None)
Tk::Busy.configure(self, option, value)
self
end
def busy_cget(option)
Tk::Busy.configure(self, option)
end
def busy(keys={})
Tk::Busy.hold(self, keys)
self
end
alias busy_hold busy
def busy_forget
Tk::Busy.forget(self)
self
end
def busy_current?
! Tk::Busy.current(self.path).empty?
end
def busy_status
Tk::Busy.status(self)
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/tests/google/models/compute/backend_service_tests.rb
|
require 'securerandom'
Shindo.tests("Fog::Compute[:google] | backend service model", ['google']) do
random_string = SecureRandom.hex
model_tests(Fog::Compute[:google].backend_services, {:name => "fog-test-backend-service-#{random_string}",
:health_checks => [@health_check]})
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/version.rb
|
<gh_stars>0
module Fog
VERSION = '1.29.0'
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/tile/treeview.rb
|
#
# treeview widget
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tkextlib/tile.rb'
module Tk
module Tile
class Treeview < TkWindow
end
end
end
module Tk::Tile::TreeviewConfig
include TkItemConfigMethod
def __item_configinfo_struct(id)
# maybe need to override
{:key=>0, :alias=>nil, :db_name=>nil, :db_class=>nil,
:default_value=>nil, :current_value=>1}
end
private :__item_configinfo_struct
def __itemconfiginfo_core(tagOrId, slot = nil)
if TkComm::GET_CONFIGINFO_AS_ARRAY
if (slot && slot.to_s =~ /^(|latin|ascii|kanji)(#{__item_font_optkeys(tagid(tagOrId)).join('|')})$/)
fontkey = $2
return [slot.to_s, tagfontobj(tagid(tagOrId), fontkey)]
else
if slot
slot = slot.to_s
alias_name, real_name = __item_optkey_aliases(tagid(tagOrId)).find{|k, v| k.to_s == slot}
if real_name
slot = real_name.to_s
end
case slot
when /^(#{__tile_specific_item_optkeys(tagid(tagOrId)).join('|')})$/
begin
# On tile-0.7.{2-8}, 'state' options has no '-' at its head.
val = tk_call(*(__item_confinfo_cmd(tagid(tagOrId)) << slot))
rescue
# Maybe, 'state' option has '-' in future.
val = tk_call(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))
end
return [slot, val]
when /^(#{__item_val2ruby_optkeys(tagid(tagOrId)).keys.join('|')})$/
method = _symbolkey2str(__item_val2ruby_optkeys(tagid(tagOrId)))[slot]
optval = tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))
begin
val = method.call(tagOrId, optval)
rescue => e
warn("Warning:: #{e.message} (when #{method}lcall(#{tagOrId.inspect}, #{optval.inspect})") if $DEBUG
val = optval
end
return [slot, val]
when /^(#{__item_methodcall_optkeys(tagid(tagOrId)).keys.join('|')})$/
method = _symbolkey2str(__item_methodcall_optkeys(tagid(tagOrId)))[slot]
return [slot, self.__send__(method, tagOrId)]
when /^(#{__item_numval_optkeys(tagid(tagOrId)).join('|')})$/
begin
val = number(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")))
rescue
val = nil
end
return [slot, val]
when /^(#{__item_numstrval_optkeys(tagid(tagOrId)).join('|')})$/
val = num_or_str(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")))
return [slot, val]
when /^(#{__item_boolval_optkeys(tagid(tagOrId)).join('|')})$/
begin
val = bool(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")))
rescue
val = nil
end
return [slot, val]
when /^(#{__item_listval_optkeys(tagid(tagOrId)).join('|')})$/
val = simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")))
return [slot, val]
when /^(#{__item_numlistval_optkeys(tagid(tagOrId)).join('|')})$/
val = tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))
if val =~ /^[0-9]/
return [slot, list(val)]
else
return [slot, val]
end
when /^(#{__item_strval_optkeys(tagid(tagOrId)).join('|')})$/
val = tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))
return [slot, val]
when /^(#{__item_tkvariable_optkeys(tagid(tagOrId)).join('|')})$/
val = tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))
if val.empty?
return [slot, nil]
else
return [slot, TkVarAccess.new(val)]
end
else
val = tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))
if val.index('{')
return [slot, tk_split_list(val)]
else
return [slot, tk_tcl2ruby(val)]
end
end
else # ! slot
ret = Hash[*(tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)))), false, false))].to_a.collect{|conf|
conf[0] = conf[0][1..-1] if conf[0][0] == ?-
case conf[0]
when /^(#{__item_val2ruby_optkeys(tagid(tagOrId)).keys.join('|')})$/
method = _symbolkey2str(__item_val2ruby_optkeys(tagid(tagOrId)))[conf[0]]
optval = conf[1]
begin
val = method.call(tagOrId, optval)
rescue => e
warn("Warning:: #{e.message} (when #{method}.call(#{tagOrId.inspect}, #{optval.inspect})") if $DEBUG
val = optval
end
conf[1] = val
when /^(#{__item_strval_optkeys(tagid(tagOrId)).join('|')})$/
# do nothing
when /^(#{__item_numval_optkeys(tagid(tagOrId)).join('|')})$/
begin
conf[1] = number(conf[1])
rescue
conf[1] = nil
end
when /^(#{__item_numstrval_optkeys(tagid(tagOrId)).join('|')})$/
conf[1] = num_or_str(conf[1])
when /^(#{__item_boolval_optkeys(tagid(tagOrId)).join('|')})$/
begin
conf[1] = bool(conf[1])
rescue
conf[1] = nil
end
when /^(#{__item_listval_optkeys(tagid(tagOrId)).join('|')})$/
conf[1] = simplelist(conf[1])
when /^(#{__item_numlistval_optkeys(tagid(tagOrId)).join('|')})$/
if conf[1] =~ /^[0-9]/
conf[1] = list(conf[1])
end
when /^(#{__item_tkvariable_optkeys(tagid(tagOrId)).join('|')})$/
if conf[1].empty?
conf[1] = nil
else
conf[1] = TkVarAccess.new(conf[1])
end
else
if conf[1].index('{')
conf[1] = tk_split_list(conf[1])
else
conf[1] = tk_tcl2ruby(conf[1])
end
end
conf
}
__item_font_optkeys(tagid(tagOrId)).each{|optkey|
optkey = optkey.to_s
fontconf = ret.assoc(optkey)
if fontconf
ret.delete_if{|inf| inf[0] =~ /^(|latin|ascii|kanji)#{optkey}$/}
fontconf[1] = tagfontobj(tagid(tagOrId), optkey)
ret.push(fontconf)
end
}
__item_methodcall_optkeys(tagid(tagOrId)).each{|optkey, method|
ret << [optkey.to_s, self.__send__(method, tagOrId)]
}
ret
end
end
else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
if (slot && slot.to_s =~ /^(|latin|ascii|kanji)(#{__item_font_optkeys(tagid(tagOrId)).join('|')})$/)
fontkey = $2
return {slot.to_s => tagfontobj(tagid(tagOrId), fontkey)}
else
if slot
slot = slot.to_s
alias_name, real_name = __item_optkey_aliases(tagid(tagOrId)).find{|k, v| k.to_s == slot}
if real_name
slot = real_name.to_s
end
case slot
when /^(#{__tile_specific_item_optkeys(tagid(tagOrId)).join('|')})$/
begin
# On tile-0.7.{2-8}, 'state' option has no '-' at its head.
val = tk_call(*(__item_confinfo_cmd(tagid(tagOrId)) << slot))
rescue
# Maybe, 'state' option has '-' in future.
val = tk_call(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))
end
return {slot => val}
when /^(#{__item_val2ruby_optkeys(tagid(tagOrId)).keys.join('|')})$/
method = _symbolkey2str(__item_val2ruby_optkeys(tagid(tagOrId)))[slot]
optval = tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))
begin
val = method.call(tagOrId, optval)
rescue => e
warn("Warning:: #{e.message} (when #{method}lcall(#{tagOrId.inspect}, #{optval.inspect})") if $DEBUG
val = optval
end
return {slot => val}
when /^(#{__item_methodcall_optkeys(tagid(tagOrId)).keys.join('|')})$/
method = _symbolkey2str(__item_methodcall_optkeys(tagid(tagOrId)))[slot]
return {slot => self.__send__(method, tagOrId)}
when /^(#{__item_numval_optkeys(tagid(tagOrId)).join('|')})$/
begin
val = number(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")))
rescue
val = nil
end
return {slot => val}
when /^(#{__item_numstrval_optkeys(tagid(tagOrId)).join('|')})$/
val = num_or_str(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")))
return {slot => val}
when /^(#{__item_boolval_optkeys(tagid(tagOrId)).join('|')})$/
begin
val = bool(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")))
rescue
val = nil
end
return {slot => val}
when /^(#{__item_listval_optkeys(tagid(tagOrId)).join('|')})$/
val = simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")))
return {slot => val}
when /^(#{__item_numlistval_optkeys(tagid(tagOrId)).join('|')})$/
val = tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))
if val =~ /^[0-9]/
return {slot => list(val)}
else
return {slot => val}
end
when /^(#{__item_strval_optkeys(tagid(tagOrId)).join('|')})$/
val = tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))
return {slot => val}
when /^(#{__item_tkvariable_optkeys(tagid(tagOrId)).join('|')})$/
val = tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))
if val.empty?
return {slot => nil}
else
return {slot => TkVarAccess.new(val)}
end
else
val = tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))
if val.index('{')
return {slot => tk_split_list(val)}
else
return {slot => tk_tcl2ruby(val)}
end
end
else # ! slot
ret = {}
ret = Hash[*(tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)))), false, false))].to_a.collect{|conf|
conf[0] = conf[0][1..-1] if conf[0][0] == ?-
optkey = conf[0]
case optkey
when /^(#{__item_val2ruby_optkeys(tagid(tagOrId)).keys.join('|')})$/
method = _symbolkey2str(__item_val2ruby_optkeys(tagid(tagOrId)))[optkey]
optval = conf[1]
begin
val = method.call(tagOrId, optval)
rescue => e
warn("Warning:: #{e.message} (when #{method}.call(#{tagOrId.inspect}, #{optval.inspect})") if $DEBUG
val = optval
end
conf[1] = val
when /^(#{__item_strval_optkeys(tagid(tagOrId)).join('|')})$/
# do nothing
when /^(#{__item_numval_optkeys(tagid(tagOrId)).join('|')})$/
begin
conf[1] = number(conf[1])
rescue
conf[1] = nil
end
when /^(#{__item_numstrval_optkeys(tagid(tagOrId)).join('|')})$/
conf[1] = num_or_str(conf[1])
when /^(#{__item_boolval_optkeys(tagid(tagOrId)).join('|')})$/
begin
conf[1] = bool(conf[1])
rescue
conf[1] = nil
end
when /^(#{__item_listval_optkeys(tagid(tagOrId)).join('|')})$/
conf[1] = simplelist(conf[1])
when /^(#{__item_numlistval_optkeys(tagid(tagOrId)).join('|')})$/
if conf[1] =~ /^[0-9]/
conf[1] = list(conf[1])
end
when /^(#{__item_tkvariable_optkeys(tagid(tagOrId)).join('|')})$/
if conf[1].empty?
conf[1] = nil
else
conf[1] = TkVarAccess.new(conf[1])
end
else
if conf[1].index('{')
return [slot, tk_split_list(conf[1])]
else
return [slot, tk_tcl2ruby(conf[1])]
end
end
ret[conf[0]] = conf[1]
}
__item_font_optkeys(tagid(tagOrId)).each{|optkey|
optkey = optkey.to_s
fontconf = ret[optkey]
if fontconf.kind_of?(Array)
ret.delete(optkey)
ret.delete('latin' << optkey)
ret.delete('ascii' << optkey)
ret.delete('kanji' << optkey)
fontconf[1] = tagfontobj(tagid(tagOrId), optkey)
ret[optkey] = fontconf
end
}
__item_methodcall_optkeys(tagid(tagOrId)).each{|optkey, method|
ret[optkey.to_s] = self.__send__(method, tagOrId)
}
ret
end
end
end
end
###################
def __item_cget_cmd(id)
[self.path, *id]
end
private :__item_cget_cmd
def __item_config_cmd(id)
[self.path, *id]
end
private :__item_config_cmd
def __item_numstrval_optkeys(id)
case id[0]
when :item, 'item'
['width']
when :column, 'column'
super(id[1]) + ['minwidth']
when :tag, 'tag'
super(id[1])
when :heading, 'heading'
super(id[1])
else
super(id[1])
end
end
private :__item_numstrval_optkeys
def __item_strval_optkeys(id)
case id[0]
when :item, 'item'
super(id) + ['id']
when :column, 'column'
super(id[1])
when :tag, 'tag'
super(id[1])
when :heading, 'heading'
super(id[1])
else
super(id[1])
end
end
private :__item_strval_optkeys
def __item_boolval_optkeys(id)
case id[0]
when :item, 'item'
['open']
when :column, 'column'
super(id[1]) + ['stretch']
when :tag, 'tag'
super(id[1])
when :heading, 'heading'
super(id[1])
end
end
private :__item_boolval_optkeys
def __item_listval_optkeys(id)
case id[0]
when :item, 'item'
['values']
when :column, 'column'
[]
when :heading, 'heading'
[]
else
[]
end
end
private :__item_listval_optkeys
def __item_val2ruby_optkeys(id)
case id[0]
when :item, 'item'
{
'tags'=>proc{|arg_id, val|
simplelist(val).collect{|tag|
Tk::Tile::Treeview::Tag.id2obj(self, tag)
}
}
}
when :column, 'column'
{}
when :heading, 'heading'
{}
else
{}
end
end
private :__item_val2ruby_optkeys
def __tile_specific_item_optkeys(id)
case id[0]
when :item, 'item'
[]
when :column, 'column'
[]
when :heading, 'heading'
['state'] # On tile-0.7.{2-8}, 'state' options has no '-' at its head.
else
[]
end
end
private :__item_val2ruby_optkeys
def itemconfiginfo(tagOrId, slot = nil)
__itemconfiginfo_core(tagOrId, slot)
end
def current_itemconfiginfo(tagOrId, slot = nil)
if TkComm::GET_CONFIGINFO_AS_ARRAY
if slot
org_slot = slot
begin
conf = __itemconfiginfo_core(tagOrId, slot)
if ( ! __item_configinfo_struct(tagid(tagOrId))[:alias] \
|| conf.size > __item_configinfo_struct(tagid(tagOrId))[:alias] + 1 )
return {conf[0] => conf[-1]}
end
slot = conf[__item_configinfo_struct(tagid(tagOrId))[:alias]]
end while(org_slot != slot)
fail RuntimeError,
"there is a configure alias loop about '#{org_slot}'"
else
ret = {}
__itemconfiginfo_core(tagOrId).each{|conf|
if ( ! __item_configinfo_struct(tagid(tagOrId))[:alias] \
|| conf.size > __item_configinfo_struct(tagid(tagOrId))[:alias] + 1 )
ret[conf[0]] = conf[-1]
end
}
ret
end
else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
ret = {}
__itemconfiginfo_core(tagOrId, slot).each{|key, conf|
ret[key] = conf[-1] if conf.kind_of?(Array)
}
ret
end
end
alias __itemcget_tkstring itemcget_tkstring
alias __itemcget itemcget
alias __itemcget_strict itemcget_strict
alias __itemconfigure itemconfigure
alias __itemconfiginfo itemconfiginfo
alias __current_itemconfiginfo current_itemconfiginfo
private :__itemcget_tkstring, :__itemcget, :__itemcget_strict
private :__itemconfigure, :__itemconfiginfo, :__current_itemconfiginfo
# Treeview Item
def itemcget_tkstring(tagOrId, option)
__itemcget_tkstring([:item, tagOrId], option)
end
def itemcget(tagOrId, option)
__itemcget([:item, tagOrId], option)
end
def itemcget_strict(tagOrId, option)
__itemcget_strict([:item, tagOrId], option)
end
def itemconfigure(tagOrId, slot, value=None)
__itemconfigure([:item, tagOrId], slot, value)
end
def itemconfiginfo(tagOrId, slot=nil)
__itemconfiginfo([:item, tagOrId], slot)
end
def current_itemconfiginfo(tagOrId, slot=nil)
__current_itemconfiginfo([:item, tagOrId], slot)
end
# Treeview Column
def columncget_tkstring(tagOrId, option)
__itemcget_tkstring([:column, tagOrId], option)
end
def columncget(tagOrId, option)
__itemcget([:column, tagOrId], option)
end
def columncget_strict(tagOrId, option)
__itemcget_strict([:column, tagOrId], option)
end
def columnconfigure(tagOrId, slot, value=None)
__itemconfigure([:column, tagOrId], slot, value)
end
def columnconfiginfo(tagOrId, slot=nil)
__itemconfiginfo([:column, tagOrId], slot)
end
def current_columnconfiginfo(tagOrId, slot=nil)
__current_itemconfiginfo([:column, tagOrId], slot)
end
alias column_cget_tkstring columncget_tkstring
alias column_cget columncget
alias column_cget_strict columncget_strict
alias column_configure columnconfigure
alias column_configinfo columnconfiginfo
alias current_column_configinfo current_columnconfiginfo
# Treeview Heading
def headingcget_tkstring(tagOrId, option)
if __tile_specific_item_optkeys([:heading, tagOrId]).index(option.to_s)
begin
# On tile-0.7.{2-8}, 'state' options has no '-' at its head.
tk_call(*(__item_cget_cmd([:heading, tagOrId]) << option.to_s))
rescue
# Maybe, 'state' option has '-' in future.
tk_call(*(__item_cget_cmd([:heading, tagOrId]) << "-#{option}"))
end
else
__itemcget_tkstring([:heading, tagOrId], option)
end
end
def headingcget_strict(tagOrId, option)
if __tile_specific_item_optkeys([:heading, tagOrId]).index(option.to_s)
begin
# On tile-0.7.{2-8}, 'state' options has no '-' at its head.
tk_call(*(__item_cget_cmd([:heading, tagOrId]) << option.to_s))
rescue
# Maybe, 'state' option has '-' in future.
tk_call(*(__item_cget_cmd([:heading, tagOrId]) << "-#{option}"))
end
else
__itemcget_strict([:heading, tagOrId], option)
end
end
def headingcget(tagOrId, option)
unless TkItemConfigMethod.__IGNORE_UNKNOWN_CONFIGURE_OPTION__
headingcget_strict(tagOrId, option)
else
begin
headingcget_strict(tagOrId, option)
rescue => e
begin
if current_headingconfiginfo(tagOrId).has_key?(option.to_s)
# not tag error & option is known -> error on known option
fail e
else
# not tag error & option is unknown
nil
end
rescue
fail e # tag error
end
end
end
end
def headingconfigure(tagOrId, slot, value=None)
if slot.kind_of?(Hash)
slot = _symbolkey2str(slot)
sp_kv = []
__tile_specific_item_optkeys([:heading, tagOrId]).each{|k|
sp_kv << k << _get_eval_string(slot.delete(k)) if slot.has_key?(k)
}
tk_call(*(__item_config_cmd([:heading, tagOrId]).concat(sp_kv)))
tk_call(*(__item_config_cmd([:heading, tagOrId]).concat(hash_kv(slot))))
elsif __tile_specific_item_optkeys([:heading, tagOrId]).index(slot.to_s)
begin
# On tile-0.7.{2-8}, 'state' options has no '-' at its head.
tk_call(*(__item_cget_cmd([:heading, tagOrId]) << slot.to_s << value))
rescue
# Maybe, 'state' option has '-' in future.
tk_call(*(__item_cget_cmd([:heading, tagOrId]) << "-#{slot}" << value))
end
else
__itemconfigure([:heading, tagOrId], slot, value)
end
self
end
def headingconfiginfo(tagOrId, slot=nil)
__itemconfiginfo([:heading, tagOrId], slot)
end
def current_headingconfiginfo(tagOrId, slot=nil)
__current_itemconfiginfo([:heading, tagOrId], slot)
end
alias heading_cget_tkstring headingcget_tkstring
alias heading_cget headingcget
alias heading_cget_strict headingcget_strict
alias heading_configure headingconfigure
alias heading_configinfo headingconfiginfo
alias current_heading_configinfo current_headingconfiginfo
# Treeview Tag
def tagcget_tkstring(tagOrId, option)
__itemcget_tkstring([:tag, :configure, tagOrId], option)
end
def tagcget(tagOrId, option)
__itemcget([:tag, :configure, tagOrId], option)
end
def tagcget_strict(tagOrId, option)
__itemcget_strict([:tag, :configure, tagOrId], option)
end
def tagconfigure(tagOrId, slot, value=None)
__itemconfigure([:tag, :configure, tagOrId], slot, value)
end
def tagconfiginfo(tagOrId, slot=nil)
__itemconfiginfo([:tag, :configure, tagOrId], slot)
end
def current_tagconfiginfo(tagOrId, slot=nil)
__current_itemconfiginfo([:tag, :configure, tagOrId], slot)
end
alias tag_cget_tkstring tagcget_tkstring
alias tag_cget tagcget
alias tag_cget_strict tagcget_strict
alias tag_configure tagconfigure
alias tag_configinfo tagconfiginfo
alias current_tag_configinfo current_tagconfiginfo
end
########################
class Tk::Tile::Treeview::Item < TkObject
ItemID_TBL = TkCore::INTERP.create_table
TkCore::INTERP.init_ip_env{
Tk::Tile::Treeview::Item::ItemID_TBL.mutex.synchronize{
Tk::Tile::Treeview::Item::ItemID_TBL.clear
}
}
def self.id2obj(tree, id)
tpath = tree.path
Tk::Tile::Treeview::Item::ItemID_TBL.mutex.synchronize{
if Tk::Tile::Treeview::Item::ItemID_TBL[tpath]
(Tk::Tile::Treeview::Item::ItemID_TBL[tpath][id])? \
Tk::Tile::Treeview::Item::ItemID_TBL[tpath][id]: id
else
id
end
}
end
def self.assign(tree, id)
tpath = tree.path
obj = nil
Tk::Tile::Treeview::Item::ItemID_TBL.mutex.synchronize{
if Tk::Tile::Treeview::Item::ItemID_TBL[tpath] &&
Tk::Tile::Treeview::Item::ItemID_TBL[tpath][id]
return Tk::Tile::Treeview::Item::ItemID_TBL[tpath][id]
end
obj = self.allocate
obj.instance_eval{
@parent = @t = tree
@tpath = tpath
@path = @id = id
}
Tk::Tile::Treeview::Item::ItemID_TBL[tpath] ||= {}
Tk::Tile::Treeview::Item::ItemID_TBL[tpath][id] = obj
}
obj
end
def _insert_item(tree, parent_item, idx, keys={})
keys = _symbolkey2str(keys)
id = keys.delete('id')
if id
num_or_str(tk_call(tree, 'insert',
parent_item, idx, '-id', id, *hash_kv(keys)))
else
num_or_str(tk_call(tree, 'insert', parent_item, idx, *hash_kv(keys)))
end
end
private :_insert_item
def initialize(tree, parent_item = '', idx = 'end', keys = {})
if parent_item.kind_of?(Hash)
keys = parent_item
idx = 'end'
parent_item = ''
elsif idx.kind_of?(Hash)
keys = idx
idx = 'end'
end
@parent = @t = tree
@tpath = tree.path
@path = @id = _insert_item(@t, parent_item, idx, keys)
Tk::Tile::Treeview::Item::ItemID_TBL.mutex.synchronize{
ItemID_TBL[@tpath] = {} unless ItemID_TBL[@tpath]
ItemID_TBL[@tpath][@id] = self
}
end
def id
@id
end
def cget_tkstring(option)
@t.itemcget_tkstring(@id, option)
end
def cget(option)
@t.itemcget(@id, option)
end
def cget_strict(option)
@t.itemcget_strict(@id, option)
end
def configure(key, value=None)
@t.itemconfigure(@id, key, value)
self
end
def configinfo(key=nil)
@t.itemconfiginfo(@id, key)
end
def current_configinfo(key=nil)
@t.current_itemconfiginfo(@id, key)
end
def open?
cget('open')
end
def open
configure('open', true)
self
end
def close
configure('open', false)
self
end
def tag_has?(tag)
@t.tag_has?(tag, @id)
end
alias has_tag? tag_has?
def bbox(column=None)
@t.bbox(@id, column)
end
def children
@t.children(@id)
end
def set_children(*items)
@t.set_children(@id, *items)
self
end
def delete
@t.delete(@id)
self
end
def detach
@t.detach(@id)
self
end
def exist?
@t.exist?(@id)
end
def focus
@t.focus_item(@id)
end
def index
@t.index(@id)
end
def insert(idx='end', keys={})
@t.insert(@id, idx, keys)
end
def move(parent, idx)
@t.move(@id, parent, idx)
self
end
def next_item
@t.next_item(@id)
end
def parent_item
@t.parent_item(@id)
end
def prev_item
@t.prev_item(@id)
end
def see
@t.see(@id)
self
end
def selection_add
@t.selection_add(@id)
self
end
def selection_remove
@t.selection_remove(@id)
self
end
def selection_set
@t.selection_set(@id)
self
end
def selection_toggle
@t.selection_toggle(@id)
self
end
def get_directory
@t.get_directory(@id)
end
alias get_dictionary get_directory
def get(col)
@t.get(@id, col)
end
def set(col, value)
@t.set(@id, col, value)
end
end
########################
class Tk::Tile::Treeview::Root < Tk::Tile::Treeview::Item
def self.new(tree, keys = {})
tpath = tree.path
obj = nil
Tk::Tile::Treeview::Item::ItemID_TBL.mutex.synchronize{
if Tk::Tile::Treeview::Item::ItemID_TBL[tpath] &&
Tk::Tile::Treeview::Item::ItemID_TBL[tpath]['']
obj = Tk::Tile::Treeview::Item::ItemID_TBL[tpath]['']
else
#super(tree, keys)
(obj = self.allocate).instance_eval{
@parent = @t = tree
@tpath = tree.path
@path = @id = ''
Tk::Tile::Treeview::Item::ItemID_TBL[@tpath] ||= {}
Tk::Tile::Treeview::Item::ItemID_TBL[@tpath][@id] = self
}
end
}
obj.configure(keys) if keys && ! keys.empty?
obj
end
def initialize(tree, keys = {})
# dummy:: not called by 'new' method
@parent = @t = tree
@tpath = tree.path
@path = @id = ''
Tk::Tile::Treeview::Item::ItemID_TBL.mutex.synchronize{
Tk::Tile::Treeview::Item::ItemID_TBL[@tpath] ||= {}
Tk::Tile::Treeview::Item::ItemID_TBL[@tpath][@id] = self
}
end
end
########################
class Tk::Tile::Treeview::Tag < TkObject
include TkTreatTagFont
TagID_TBL = TkCore::INTERP.create_table
(Tag_ID = ['tile_treeview_tag'.freeze, TkUtil.untrust('00000')]).instance_eval{
@mutex = Mutex.new
def mutex; @mutex; end
freeze
}
TkCore::INTERP.init_ip_env{
Tk::Tile::Treeview::Tag::TagID_TBL.mutex.synchronize{
Tk::Tile::Treeview::Tag::TagID_TBL.clear
}
}
def self.id2obj(tree, id)
tpath = tree.path
Tk::Tile::Treeview::Tag::TagID_TBL.mutex.synchronize{
if Tk::Tile::Treeview::Tag::TagID_TBL[tpath]
(Tk::Tile::Treeview::Tag::TagID_TBL[tpath][id])? \
Tk::Tile::Treeview::Tag::TagID_TBL[tpath][id]: id
else
id
end
}
end
def initialize(tree, keys=nil)
@parent = @t = tree
@tpath = tree.path
Tag_ID.mutex.synchronize{
@path = @id = Tag_ID.join(TkCore::INTERP._ip_id_)
Tag_ID[1].succ!
}
TagID_TBL.mutex.synchronize{
TagID_TBL[@tpath] = {} unless TagID_TBL[@tpath]
TagID_TBL[@tpath][@id] = self
}
if keys && keys != None
tk_call_without_enc(@tpath, 'tag', 'configure', @id, *hash_kv(keys,true))
end
end
def id
@id
end
def tag_has?(item)
@t.tag_has?(@id, item)
end
alias added? tag_has?
def bind(seq, *args)
if TkComm._callback_entry?(args[0]) || !block_given?
cmd = args.shift
else
cmd = Proc.new
end
@t.tag_bind(@id, seq, cmd, *args)
self
end
def bind_append(seq, *args)
if TkComm._callback_entry?(args[0]) || !block_given?
cmd = args.shift
else
cmd = Proc.new
end
@t.tag_bind_append(@id, seq, cmd, *args)
self
end
def bind_remove(seq)
@t.tag_bind_remove(@id, seq)
self
end
def bindinfo(seq=nil)
@t.tag_bindinfo(@id, seq)
end
def cget_tkstring(option)
@t.tagcget_tkstring(@id, option)
end
def cget(option)
@t.tagcget(@id, option)
end
def cget_strict(option)
@t.tagcget_strict(@id, option)
end
def configure(key, value=None)
@t.tagconfigure(@id, key, value)
self
end
def configinfo(key=nil)
@t.tagconfiginfo(@id, key)
end
def current_configinfo(key=nil)
@t.current_tagconfiginfo(@id, key)
end
end
########################
class Tk::Tile::Treeview < TkWindow
include Tk::Tile::TileWidget
include Scrollable
include Tk::Tile::TreeviewConfig
if Tk::Tile::USE_TTK_NAMESPACE
TkCommandNames = ['::ttk::treeview'.freeze].freeze
else
TkCommandNames = ['::treeview'.freeze].freeze
end
WidgetClassName = 'Treeview'.freeze
WidgetClassNames[WidgetClassName] ||= self
def __destroy_hook__
Tk::Tile::Treeview::Item::ItemID_TBL.mutex.synchronize{
Tk::Tile::Treeview::Item::ItemID_TBL.delete(@path)
}
Tk::Tile::Treeview::Tag::ItemID_TBL.mutex.synchronize{
Tk::Tile::Treeview::Tag::ItemID_TBL.delete(@path)
}
end
def self.style(*args)
[self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
end
def tagid(id)
if id.kind_of?(Tk::Tile::Treeview::Item) ||
id.kind_of?(Tk::Tile::Treeview::Tag)
id.id
elsif id.kind_of?(Array)
# size is 2 or 3
id[0..-2] << _get_eval_string(id[-1])
else
_get_eval_string(id)
end
end
def root
Tk::Tile::Treeview::Root.new(self)
end
def bbox(item, column=None)
list(tk_send('item', 'bbox', item, column))
end
def children(item)
simplelist(tk_send_without_enc('children', item)).collect{|id|
Tk::Tile::Treeview::Item.id2obj(self, id)
}
end
def set_children(item, *items)
tk_send_without_enc('children', item,
array2tk_list(items.flatten, true))
self
end
def delete(*items)
tk_send_without_enc('delete', array2tk_list(items.flatten, true))
self
end
def detach(*items)
tk_send_without_enc('detach', array2tk_list(items.flatten, true))
self
end
def exist?(item)
bool(tk_send_without_enc('exists', _get_eval_enc_str(item)))
end
def focus_item(item = nil)
if item
tk_send('focus', item)
item
else
id = tk_send('focus')
(id.empty?)? nil: Tk::Tile::Treeview::Item.id2obj(self, id)
end
end
def identify(x, y)
# tile-0.7.2 or previous
ret = simplelist(tk_send('identify', x, y))
case ret[0]
when 'heading', 'separator'
ret[-1] = num_or_str(ret[-1])
when 'cell'
ret[1] = Tk::Tile::Treeview::Item.id2obj(self, ret[1])
ret[-1] = num_or_str(ret[-1])
when 'item', 'row'
ret[1] = Tk::Tile::Treeview::Item.id2obj(self, ret[1])
end
end
def identify_region(x, y)
tk_send('identify', 'region', x, y)
end
def identify_item(x, y)
id = tk_send('identify', 'item', x, y)
(id.empty?)? nil: Tk::Tile::Treeview::Item.id2obj(self, id)
end
def identify_element(x, y)
tk_send('identify', 'element', x, y)
end
def row_identify(x, y)
id = tk_send('identify', 'row', x, y)
(id.empty?)? nil: Tk::Tile::Treeview::Item.id2obj(self, id)
end
alias identify_row row_identify
def column_identify(x, y)
tk_send('identify', 'column', x, y)
end
alias identify_column column_identify
def index(item)
number(tk_send('index', item))
end
# def insert(parent, idx='end', keys={})
# keys = _symbolkey2str(keys)
# id = keys.delete('id')
# if id
# num_or_str(tk_send('insert', parent, idx, '-id', id, *hash_kv(keys)))
# else
# num_or_str(tk_send('insert', parent, idx, *hash_kv(keys)))
# end
# end
def insert(parent, idx='end', keys={})
Tk::Tile::Treeview::Item.new(self, parent, idx, keys)
end
# def instate(spec, cmd=Proc.new)
# tk_send('instate', spec, cmd)
# end
# def state(spec=None)
# tk_send('state', spec)
# end
def move(item, parent, idx)
tk_send('move', item, parent, idx)
self
end
def next_item(item)
id = tk_send('next', item)
(id.empty?)? nil: Tk::Tile::Treeview::Item.id2obj(self, id)
end
def parent_item(item)
if (id = tk_send('parent', item)).empty?
Tk::Tile::Treeview::Root.new(self)
else
Tk::Tile::Treeview::Item.id2obj(self, id)
end
end
def prev_item(item)
id = tk_send('prev', item)
(id.empty?)? nil: Tk::Tile::Treeview::Item.id2obj(self, id)
end
def see(item)
tk_send('see', item)
self
end
def selection
simplelist(tk_send('selection')).collect{|id|
Tk::Tile::Treeview::Item.id2obj(self, id)
}
end
alias selection_get selection
def selection_add(*items)
tk_send('selection', 'add', array2tk_list(items.flatten, true))
self
end
def selection_remove(*items)
tk_send('selection', 'remove', array2tk_list(items.flatten, true))
self
end
def selection_set(*items)
tk_send('selection', 'set', array2tk_list(items.flatten, true))
self
end
def selection_toggle(*items)
tk_send('selection', 'toggle', array2tk_list(items.flatten, true))
self
end
def get_directory(item)
# tile-0.7+
ret = []
lst = simplelist(tk_send('set', item))
until lst.empty?
col = lst.shift
val = lst.shift
ret << [col, val]
end
ret
end
alias get_dictionary get_directory
def get(item, col)
tk_send('set', item, col)
end
def set(item, col, value)
tk_send('set', item, col, value)
self
end
def tag_has?(tag, item)
bool(tk_send('tag', 'has', tagid(tag), tagid(item)))
end
def tag_has(tag)
tk_split_simplelist(tk_send('tag', 'has', tagid(tag))).collect{|id|
Tk::Tile::Treeview::Item.id2obj(self, id)
}
end
def tag_bind(tag, seq, *args)
if TkComm._callback_entry?(args[0]) || !block_given?
cmd = args.shift
else
cmd = Proc.new
end
_bind([@path, 'tag', 'bind', tag], seq, cmd, *args)
self
end
alias tagbind tag_bind
def tag_bind_append(tag, seq, *args)
if TkComm._callback_entry?(args[0]) || !block_given?
cmd = args.shift
else
cmd = Proc.new
end
_bind_append([@path, 'tag', 'bind', tag], seq, cmd, *args)
self
end
alias tagbind_append tag_bind_append
def tag_bind_remove(tag, seq)
_bind_remove([@path, 'tag', 'bind', tag], seq)
self
end
alias tagbind_remove tag_bind_remove
def tag_bindinfo(tag, context=nil)
_bindinfo([@path, 'tag', 'bind', tag], context)
end
alias tagbindinfo tag_bindinfo
end
#Tk.__set_toplevel_aliases__(:Ttk, Tk::Tile::Treeview, :TkTreeview)
Tk.__set_loaded_toplevel_aliases__('tkextlib/tile/treeview.rb',
:Ttk, Tk::Tile::Treeview, :TkTreeview)
|
arnab0073/idea
|
.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/gem-wrappers-1.2.7/test/gem-wrappers/command_test.rb
|
<reponame>arnab0073/idea<filename>.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/gem-wrappers-1.2.7/test/gem-wrappers/command_test.rb
require 'test_helper'
require 'tempfile'
require 'gem-wrappers/command'
require 'gem-wrappers/fakes'
describe WrappersCommand do
subject do
WrappersCommand.new
end
before do
@fake_installer = GemWrappers::Fake.new
subject.instance_variable_set(:@gem_wrappers, @fake_installer)
$stdout = StringIO.new
$stderr = StringIO.new
end
after do
$stdout = STDOUT
$stderr = STDERR
end
it "has some strings" do
subject.arguments.class.must_equal(String)
subject.usage.class.must_equal(String)
subject.defaults_str.class.must_equal(String)
subject.description.class.must_equal(String)
subject.program_name.class.must_equal(String)
end
it "shows help on unknown command" do
subject.options[:args] = ['wrong']
subject.execute
$stderr.string.must_equal("Unknown wrapper subcommand: wrong\n")
$stdout.string.must_equal(subject.description)
end
it "does show" do
subject.options[:args] = ["show", "rake"]
subject.execute
$stderr.string.must_equal("")
$stdout.string.must_equal(<<-EXPECTED)
#{subject.description.strip}
Wrappers path: /path/to/wrappers
Environment file: /path/to/environment
Executables: rake
EXPECTED
end
it "regenerates wrappers" do
subject.instance_variable_set(:@executables, %w{rake})
subject.options[:args] = ['regenerate']
subject.execute
@fake_installer.executables.must_equal(%w{rake})
end
describe "script wrappers" do
before do
@file = Tempfile.new('command-wrappers')
end
after do
@file.close
@file.unlink
end
it "generates script wrapper full path" do
subject.options[:args] = [@file.path]
subject.execute
@fake_installer.executables.must_equal([@file.path])
end
it "generates script wrapper relative" do
Dir.chdir(File.dirname(@file.path)) do
subject.options[:args] = [File.basename(@file.path)]
subject.execute
@fake_installer.executables.must_equal([@file.path])
end
end
end
it "finds gem executables" do
subject.send(:executables).must_include('rake')
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/net-ssh-3.1.1/test/integration/test_id_rsa_keys.rb
|
require 'common'
require 'fileutils'
require 'tmpdir'
require 'net/ssh'
# see Vagrantfile,playbook for env.
# we're running as net_ssh_1 user password <PASSWORD>
# and usually connecting to net_ssh_2 user password <PASSWORD>
class TestIDRSAPKeys < Test::Unit::TestCase
include IntegrationTestHelpers
def test_in_file_no_password
tmpdir do |dir|
sh "rm -rf #{dir}/id_rsa #{dir}/id_rsa.pub"
sh "ssh-keygen -f #{dir}/id_rsa -t rsa -N ''"
set_authorized_key('net_ssh_1',"#{dir}/id_rsa.pub")
sshopts = '-vvvv -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
#sh "ssh -i #{dir}/id_rsa #{sshopts} net_ssh_1@localhost echo 'hello'"
ret = Net::SSH.start("localhost", "net_ssh_1", {keys: "#{dir}/id_rsa"}) do |ssh|
ssh.exec! 'echo "hello from:$USER"'
end
assert_equal "hello from:net_ssh_1\n", ret
end
end
def test_ssh_agent
tmpdir do |dir|
with_agent do
sh "rm -rf #{dir}/id_rsa #{dir}/id_rsa.pub"
sh "ssh-keygen -f #{dir}/id_rsa -t rsa -N 'pwd123'"
set_authorized_key('net_ssh_1',"#{dir}/id_rsa.pub")
ssh_add("#{dir}/id_rsa","pwd123")
ret = Net::SSH.start("localhost", "net_ssh_1",verbose: :debug) do |ssh|
ssh.exec! 'echo "hello from:$USER"'
end
assert_equal "hello from:net_ssh_1\n", ret
end
end
end
def test_ssh_agent_ignores_if_already_in_agent
tmpdir do |dir|
with_agent do
sh "rm -rf #{dir}/id_rsa #{dir}/id_rsa.pub"
sh "ssh-keygen -f #{dir}/id_rsa -t rsa -N 'pwd123'"
set_authorized_key('net_ssh_1',"#{dir}/id_rsa.pub")
ssh_add("#{dir}/id_rsa","pwd123")
ret = Net::SSH.start("localhost", "net_ssh_1",verbose: :debug, keys: ["#{dir}/id_rsa"]) do |ssh|
ssh.exec! 'echo "hello from:$USER"'
end
assert_equal "hello from:net_ssh_1\n", ret
end
end
end
def test_in_file_with_password
tmpdir do |dir|
sh "rm -rf #{dir}/id_rsa #{dir}/id_rsa.pub"
sh "ssh-keygen -f #{dir}/id_rsa -t rsa -N 'pwd12'"
set_authorized_key('net_ssh_1',"#{dir}/id_rsa.pub")
sshopts = '-vvvv -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
#sh "ssh -i #{dir}/id_rsa #{sshopts} net_ssh_1@localhost echo 'hello'"
ret = Net::SSH.start("localhost", "net_ssh_1", {keys: "#{dir}/id_rsa",
passphrase: '<PASSWORD>', verbose: :debug}) do |ssh|
ssh.exec! 'echo "hello from:$USER"'
end
assert_equal "hello from:net_ssh_1\n", ret
end
end
def test_asks_for_passwords_when_read_from_memory
tmpdir do |dir|
sh "rm -rf #{dir}/id_rsa #{dir}/id_rsa.pub"
sh "ssh-keygen -f #{dir}/id_rsa -t rsa -N 'pwd12'"
set_authorized_key('net_ssh_1',"#{dir}/id_rsa.pub")
private_key = File.read("#{dir}/id_rsa")
options = {keys: [], key_data: [private_key]}
key_manager = Net::SSH::Authentication::KeyManager.new(nil, options)
Net::SSH::KeyFactory.expects(:prompt).with('Enter passphrase for :', false).returns('pwd12')
Net::SSH.start("localhost", "net_ssh_1", options) do |ssh|
ssh.exec! 'whoami'
end
end
end
end
|
arnab0073/idea
|
.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/rvm-1.11.3.9/lib/rvm/shell/abstract_wrapper.rb
|
require 'yaml'
module RVM
module Shell
# Provides the most common functionality expected of a shell wrapper.
# Namely, implements general utility methods and tools to extract output
# from a given command but doesn't actually run any commands itself,
# leaving that up to concrete implementations.
#
# == Usage
#
# Commands are run inside of a shell (usually bash) and can either be exectuted in
# two situations (each with wrapper methods available) - silently or verbosely.
#
# Silent commands (via run_silently and run_command) do exactly as
# they say - that can modify the environment etc but anything they print (to stdout
# or stderr) will be discarded.
#
# Verbose commands will run the command and then print the command epilog (which
# contains the output stastus and the current env in yaml format). This allows us
# to not only capture all output but to also return the exit status and environment
# variables in a way that makes persisted shell sessions possible.
#
# Under the hood, #run and run_silently are the preferred ways of invoking commands - if
# passed a single command, they'll run it as is (much like system in ruby) but when
# given multiple arguments anything after the first will be escaped (e.g. you can
# hence pass code etc). #run will also parse the results of this epilog into a usable
# RVM::Shell::Result object.
#
# run_command and run_command_silently do the actual hard work for these behind the scenes,
# running a string as the shell command. Hence, these two commands are what must be
# implemented in non-abstract wrappers.
#
# For an example of the shell wrapper functionality in action, see RVM::Environment
# which delegates most of the work to a shell wrapper.
class AbstractWrapper
# Used the mark the end of a commands output and the start of the rvm env.
COMMAND_EPILOG_START = "---------------RVM-RESULTS-START---------------"
# Used to mark the end of the commands epilog.
COMMAND_EPILOG_END = "----------------RVM-RESULTS-END----------------"
# The location of the shell file with the epilog function definition.
WRAPPER_LOCATION = File.expand_path('./shell_wrapper.sh', File.dirname(__FILE__))
# Defines the shell exectuable.
attr_reader :shell_executable
# Initializes a new shell wrapper, including setting the
# default setup block. Implementations must override this method
# but must ensure that they call super to perform the expected
# standard setup.
def initialize(sh = 'bash', &setup_block)
setup &setup_block
@shell_executable = sh
end
# Defines a setup block to be run when initiating a wrapper session.
# Usually used for doing things such as sourcing the rvm file. Please note
# that the wrapper file is automatically source.
#
# The setup block should be automatically run by wrapper implementations.
def setup(&blk)
@setup_block = blk
end
# Runs the gives command (with optional arguments), returning an
# RVM::Shell::Result object, including stdout / stderr streams.
# Under the hood, uses run_command to actually process it all.
def run(command, *arguments)
expanded_command = build_cli_call(command, arguments)
status, out, err = run_command(expanded_command)
Result.new(expanded_command, status, out, err)
end
# Wrapper around run_command_silently that correctly escapes arguments.
# Essentially, #run but using run_command_silently.
def run_silently(command, *arguments)
run_command_silently build_cli_call(command, arguments)
end
# Given a command, it will execute it in the current wrapper
# and once done, will return:
# - the hash from the epilog output.
# - a string representing stdout.
# - a string representing stderr.
def run_command(full_command)
raise NotImplementedError.new("run_command is only available in concrete implementations")
end
# Like run_command, but doesn't care about output.
def run_command_silently(full_command)
raise NotImplementedError.new("run_command_silently is only available in concrete implementations")
end
# Returns a given environment variables' value.
def [](var_name)
run(:true)[var_name]
end
protected
# When called, will use the current environment to source the wrapper scripts
# as well as invoking the current setup block. as defined on initialization / via #setup.
def invoke_setup!
source_command_wrapper
@setup_block.call(self) if @setup_block
end
# Uses run_silently to source the wrapper file.
def source_command_wrapper
run_silently :source, WRAPPER_LOCATION
end
# Returns a command followed by the call to show the epilog.
def wrapped_command(command)
"#{command}; __rvm_show_command_epilog"
end
# Wraps a command in a way that it prints no output.
def silent_command(command)
"{ #{command}; } >/dev/null 2>&1"
end
# Checks whether the given command includes a epilog, marked by
# epilog start and end lines.
def command_complete?(c)
start_index, end_index = c.index(COMMAND_EPILOG_START), c.index(COMMAND_EPILOG_END)
start_index && end_index && start_index < end_index
end
# Takes a raw string from a processes STDIO and returns three things:
# 1. The actual stdout, minus epilogue.
# 2. YAML output of the process results.
# 3. Any left over from the STDIO text.
def raw_stdout_to_parts(c)
raise IncompleteCommandError if !command_complete?(c)
before, after = c.split(COMMAND_EPILOG_START, 2)
epilog, after = after.split(COMMAND_EPILOG_END, 2)
return before, YAML.load(epilog.strip), after
end
include RVM::Shell::Utility
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/benchmark/bm_app_strconcat.rb
|
i=0
while i<2_000_000
"#{1+1} #{1+1} #{1+1}"
i+=1
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/test_unicode_normalize.rb
|
# coding: utf-8
# frozen_string_literal: false
# Copyright <NAME> (野島 歩) and <NAME> (<EMAIL>)
require 'test/unit'
require 'unicode_normalize/normalize'
class TestUnicodeNormalize < Test::Unit::TestCase
UNICODE_VERSION = UnicodeNormalize::UNICODE_VERSION
NormTest = Struct.new :source, :NFC, :NFD, :NFKC, :NFKD, :line
def read_tests
IO.readlines(File.expand_path("../enc/unicode/data/#{UNICODE_VERSION}/NormalizationTest.txt", __dir__), encoding: 'utf-8')
.tap { |lines| assert_include(lines[0], "NormalizationTest-#{UNICODE_VERSION}.txt")}
.collect.with_index { |linedata, linenumber| [linedata, linenumber]}
.reject { |line| line[0] =~ /^[\#@]/ }
.collect do |line|
NormTest.new(*(line[0].split(';').take(5).collect do |code_string|
code_string.split(/\s/).collect { |cp| cp.to_i(16) }.pack('U*')
end + [line[1]+1]))
end
end
def to_codepoints(string)
string.codepoints.collect { |cp| cp.to_s(16).upcase.rjust(4, '0') }
end
def setup
@@tests ||= read_tests
rescue Errno::ENOENT => e
@@tests ||= []
skip e.message
end
def self.generate_test_normalize(target, normalization, source, prechecked)
define_method "test_normalize_to_#{target}_from_#{source}_with_#{normalization}" do
expected = actual = test = nil
mesg = proc {"#{to_codepoints(expected)} expected but was #{to_codepoints(actual)} on line #{test[:line]} (#{normalization})"}
@@tests.each do |t|
test = t
if prechecked.nil? or test[prechecked]==test[source]
expected = test[target]
actual = test[source].unicode_normalize(normalization)
assert_equal expected, actual, mesg
end
end
end
end
# source; NFC; NFD; NFKC; NFKD
# NFC
# :NFC == toNFC(:source) == toNFC(:NFC) == toNFC(:NFD)
generate_test_normalize :NFC, :nfc, :source, nil
generate_test_normalize :NFC, :nfc, :NFC, :source
generate_test_normalize :NFC, :nfc, :NFD, :source
# :NFKC == toNFC(:NFKC) == toNFC(:NFKD)
generate_test_normalize :NFKC, :nfc, :NFKC, nil
generate_test_normalize :NFKC, :nfc, :NFKD, :NFKC
#
# NFD
# :NFD == toNFD(:source) == toNFD(:NFC) == toNFD(:NFD)
generate_test_normalize :NFD, :nfd, :source, nil
generate_test_normalize :NFD, :nfd, :NFC, :source
generate_test_normalize :NFD, :nfd, :NFD, :source
# :NFKD == toNFD(:NFKC) == toNFD(:NFKD)
generate_test_normalize :NFKD, :nfd, :NFKC, nil
generate_test_normalize :NFKD, :nfd, :NFKD, :NFKC
#
# NFKC
# :NFKC == toNFKC(:source) == toNFKC(:NFC) == toNFKC(:NFD) == toNFKC(:NFKC) == toNFKC(:NFKD)
generate_test_normalize :NFKC, :nfkc, :source, nil
generate_test_normalize :NFKC, :nfkc, :NFC, :source
generate_test_normalize :NFKC, :nfkc, :NFD, :source
generate_test_normalize :NFKC, :nfkc, :NFKC, :NFC
generate_test_normalize :NFKC, :nfkc, :NFKD, :NFD
#
# NFKD
# :NFKD == toNFKD(:source) == toNFKD(:NFC) == toNFKD(:NFD) == toNFKD(:NFKC) == toNFKD(:NFKD)
generate_test_normalize :NFKD, :nfkd, :source, nil
generate_test_normalize :NFKD, :nfkd, :NFC, :source
generate_test_normalize :NFKD, :nfkd, :NFD, :source
generate_test_normalize :NFKD, :nfkd, :NFKC, :NFC
generate_test_normalize :NFKD, :nfkd, :NFKD, :NFD
def self.generate_test_check_true(source, normalization)
define_method "test_check_true_#{source}_as_#{normalization}" do
test = nil
mesg = proc {"#{to_codepoints(test[source])} should check as #{normalization} but does not on line #{test[:line]}"}
@@tests.each do |t|
test = t
actual = test[source].unicode_normalized?(normalization)
assert_equal true, actual, mesg
end
end
end
def self.generate_test_check_false(source, compare, normalization)
define_method "test_check_false_#{source}_as_#{normalization}" do
test = nil
mesg = proc {"#{to_codepoints(test[source])} should not check as #{normalization} but does on line #{test[:line]}"}
@@tests.each do |t|
test = t
if test[source] != test[compare]
actual = test[source].unicode_normalized?(normalization)
assert_equal false, actual, mesg
end
end
end
end
generate_test_check_true :NFC, :nfc
generate_test_check_true :NFD, :nfd
generate_test_check_true :NFKC, :nfc
generate_test_check_true :NFKC, :nfkc
generate_test_check_true :NFKD, :nfd
generate_test_check_true :NFKD, :nfkd
generate_test_check_false :source, :NFD, :nfd
generate_test_check_false :NFC, :NFD, :nfd
generate_test_check_false :NFKC, :NFKD, :nfd
generate_test_check_false :source, :NFC, :nfc
generate_test_check_false :NFD, :NFC, :nfc
generate_test_check_false :NFKD, :NFKC, :nfc
generate_test_check_false :source, :NFKD, :nfkd
generate_test_check_false :NFC, :NFKD, :nfkd
generate_test_check_false :NFD, :NFKD, :nfkd
generate_test_check_false :NFKC, :NFKD, :nfkd
generate_test_check_false :source, :NFKC, :nfkc
generate_test_check_false :NFC, :NFKC, :nfkc
generate_test_check_false :NFD, :NFKC, :nfkc
generate_test_check_false :NFKD, :NFKC, :nfkc
def test_non_UTF_8
assert_equal "\u1E0A".encode('UTF-16BE'), "D\u0307".encode('UTF-16BE').unicode_normalize(:nfc)
assert_equal true, "\u1E0A".encode('UTF-16BE').unicode_normalized?(:nfc)
assert_equal false, "D\u0307".encode('UTF-16BE').unicode_normalized?(:nfc)
end
def test_singleton_with_accents
assert_equal "\u0136", "\u212A\u0327".unicode_normalize(:nfc)
end
def test_partial_jamo_compose
assert_equal "\uAC01", "\uAC00\u11A8".unicode_normalize(:nfc)
end
def test_partial_jamo_decompose
assert_equal "\u1100\u1161\u11A8", "\uAC00\u11A8".unicode_normalize(:nfd)
end
def test_hangul_plus_accents
assert_equal "\uAC00\u0323\u0300", "\uAC00\u0300\u0323".unicode_normalize(:nfc)
assert_equal "\uAC00\u0323\u0300", "\u1100\u1161\u0300\u0323".unicode_normalize(:nfc)
assert_equal "\u1100\u1161\u0323\u0300", "\uAC00\u0300\u0323".unicode_normalize(:nfd)
assert_equal "\u1100\u1161\u0323\u0300", "\u1100\u1161\u0300\u0323".unicode_normalize(:nfd)
end
def test_raise_exception_for_non_unicode_encoding
assert_raise(Encoding::CompatibilityError) { "abc".force_encoding('ISO-8859-1').unicode_normalize }
assert_raise(Encoding::CompatibilityError) { "abc".force_encoding('ISO-8859-1').unicode_normalize! }
assert_raise(Encoding::CompatibilityError) { "abc".force_encoding('ISO-8859-1').unicode_normalized? }
end
def test_us_ascii
ascii_string = 'abc'.encode('US-ASCII')
assert_equal ascii_string, ascii_string.unicode_normalize
assert_equal ascii_string, ascii_string.unicode_normalize(:nfd)
assert_equal ascii_string, ascii_string.unicode_normalize(:nfkc)
assert_equal ascii_string, ascii_string.unicode_normalize(:nfkd)
assert_equal ascii_string, ascii_string.unicode_normalize!
assert_equal ascii_string, ascii_string.unicode_normalize!(:nfd)
assert_equal ascii_string, ascii_string.unicode_normalize!(:nfkc)
assert_equal ascii_string, ascii_string.unicode_normalize!(:nfkd)
assert_equal true, ascii_string.unicode_normalized?
assert_equal true, ascii_string.unicode_normalized?(:nfd)
assert_equal true, ascii_string.unicode_normalized?(:nfkc)
assert_equal true, ascii_string.unicode_normalized?(:nfkd)
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/knife-windows-1.4.1/spec/unit/knife/windows_listener_create_spec.rb
|
#
# Author:: <NAME> <<EMAIL>>
# Copyright:: Copyright (c) 2014-2016 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'spec_helper'
require 'chef/knife/windows_listener_create'
describe Chef::Knife::WindowsListenerCreate do
context "on Windows" do
before do
allow(Chef::Platform).to receive(:windows?).and_return(true)
@listener = Chef::Knife::WindowsListenerCreate.new
end
it "creates winrm listener" do
@listener.config[:hostname] = "host"
@listener.config[:cert_thumbprint] = "CERT-THUMBPRINT"
@listener.config[:port] = "5986"
expect(@listener).to receive(:`).with("winrm create winrm/config/Listener?Address=*+Transport=HTTPS @{Hostname=\"host\";CertificateThumbprint=\"CERT-THUMBPRINT\";Port=\"5986\"}")
expect(@listener.ui).to receive(:info).with("WinRM listener created with Port: 5986 and CertificateThumbprint: CERT-THUMBPRINT")
@listener.run
end
it "raise an error on command failure" do
@listener.config[:hostname] = "host"
@listener.config[:cert_thumbprint] = "CERT-THUMBPRINT"
@listener.config[:port] = "5986"
@listener.config[:basic_auth] = true
expect(@listener).to receive(:`).with("winrm create winrm/config/Listener?Address=*+Transport=HTTPS @{Hostname=\"host\";CertificateThumbprint=\"CERT-THUMBPRINT\";Port=\"5986\"}")
expect($?).to receive(:exitstatus).and_return(100)
expect(@listener.ui).to receive(:error).with("Error creating WinRM listener. use -VV for more details.")
expect(@listener.ui).to_not receive(:info).with("WinRM listener created with Port: 5986 and CertificateThumbprint: CERT-THUMBPRINT")
expect { @listener.run }.to raise_error(SystemExit)
end
it "creates winrm listener with cert install option" do
@listener.config[:hostname] = "host"
@listener.config[:cert_thumbprint] = "CERT-THUMBPRINT"
@listener.config[:port] = "5986"
@listener.config[:cert_install] = true
allow(@listener).to receive(:get_cert_passphrase).and_return("your-secret!")
expect(@listener).to receive(:`).with("powershell.exe -Command \" 'your-secret!' | certutil -importPFX 'true' AT_KEYEXCHANGE\"")
expect(@listener).to receive(:`).with("powershell.exe -Command \" echo (Get-PfxCertificate true).thumbprint \"")
expect(@listener.ui).to receive(:info).with("Certificate installed to Certificate Store")
expect(@listener.ui).to receive(:info).with("Certificate Thumbprint: ")
allow(@listener).to receive(:puts)
@listener.run
end
end
context "not on Windows" do
before do
allow(Chef::Platform).to receive(:windows?).and_return(false)
@listener = Chef::Knife::WindowsListenerCreate.new
end
it "exits with an error" do
expect(@listener.ui).to receive(:error)
expect { @listener.run }.to raise_error(SystemExit)
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/rdoc/test_rdoc_class_module.rb
|
# frozen_string_literal: false
require File.expand_path '../xref_test_case', __FILE__
class TestRDocClassModule < XrefTestCase
def test_add_comment
tl1 = @store.add_file 'one.rb'
tl2 = @store.add_file 'two.rb'
tl3 = @store.add_file 'three.rb'
cm = RDoc::ClassModule.new 'Klass'
cm.add_comment '# comment 1', tl1
assert_equal [['comment 1', tl1]], cm.comment_location
assert_equal 'comment 1', cm.comment
cm.add_comment '# comment 2', tl2
assert_equal [['comment 1', tl1], ['comment 2', tl2]], cm.comment_location
assert_equal "comment 1\n---\ncomment 2", cm.comment
cm.add_comment "# * comment 3", tl3
assert_equal [['comment 1', tl1],
['comment 2', tl2],
['* comment 3', tl3]], cm.comment_location
assert_equal "comment 1\n---\ncomment 2\n---\n* comment 3", cm.comment
end
def test_add_comment_comment
cm = RDoc::ClassModule.new 'Klass'
cm.add_comment comment('comment'), @top_level
assert_equal 'comment', cm.comment.text
end
def test_add_comment_duplicate
tl1 = @store.add_file 'one.rb'
cm = RDoc::ClassModule.new 'Klass'
cm.add_comment '# comment 1', tl1
cm.add_comment '# comment 2', tl1
assert_equal [['comment 2', tl1]], cm.comment_location
end
def test_add_comment_stopdoc
tl = @store.add_file 'file.rb'
cm = RDoc::ClassModule.new 'Klass'
cm.stop_doc
cm.add_comment '# comment 1', tl
assert_empty cm.comment
end
def test_ancestors
assert_equal [@parent, "Object"], @child.ancestors
end
def test_comment_equals
cm = RDoc::ClassModule.new 'Klass'
cm.comment = '# comment 1'
assert_equal 'comment 1', cm.comment
cm.comment = '# comment 2'
assert_equal "comment 1\n---\ncomment 2", cm.comment
cm.comment = "# * comment 3"
assert_equal "comment 1\n---\ncomment 2\n---\n* comment 3", cm.comment
end
def test_comment_equals_comment
cm = RDoc::ClassModule.new 'Klass'
cm.comment = comment 'comment'
assert_equal 'comment', cm.comment.text
end
def test_docuent_self_or_methods
assert @c1.document_self_or_methods
@c1.document_self = false
assert @c1.document_self_or_methods
@c1_m.document_self = false
assert @c1.document_self_or_methods
@c1__m.document_self = false
refute @c1.document_self_or_methods
end
def test_documented_eh
cm = RDoc::ClassModule.new 'C'
refute cm.documented?, 'no comments, no markers'
cm.add_comment '', @top_level
refute cm.documented?, 'empty comment'
cm.add_comment 'hi', @top_level
assert cm.documented?, 'commented'
cm.comment_location.clear
refute cm.documented?, 'no comment'
cm.document_self = nil # notify :nodoc:
assert cm.documented?, ':nodoc:'
end
def test_each_ancestor
assert_equal [@parent], @child.each_ancestor.to_a
end
def test_each_ancestor_cycle
m_incl = RDoc::Include.new 'M', nil
m = @top_level.add_module RDoc::NormalModule, 'M'
m.add_include m_incl
assert_empty m.each_ancestor.to_a
end
# handle making a short module alias of yourself
def test_find_class_named
@c2.classes_hash['C2'] = @c2
assert_nil @c2.find_class_named('C1')
end
def test_from_module_comment
tl = @store.add_file 'file.rb'
klass = tl.add_class RDoc::NormalModule, 'Klass'
klass.add_comment 'really a class', tl
klass = RDoc::ClassModule.from_module RDoc::NormalClass, klass
assert_equal [['really a class', tl]], klass.comment_location
end
def test_marshal_dump
@store.path = Dir.tmpdir
tl = @store.add_file 'file.rb'
ns = tl.add_module RDoc::NormalModule, 'Namespace'
cm = ns.add_class RDoc::NormalClass, 'Klass', 'Super'
cm.document_self = true
cm.record_location tl
a1 = RDoc::Attr.new nil, 'a1', 'RW', ''
a1.record_location tl
a2 = RDoc::Attr.new nil, 'a2', 'RW', '', true
a2.record_location tl
m1 = RDoc::AnyMethod.new nil, 'm1'
m1.record_location tl
c1 = RDoc::Constant.new 'C1', nil, ''
c1.record_location tl
i1 = RDoc::Include.new 'I1', ''
i1.record_location tl
e1 = RDoc::Extend.new 'E1', ''
e1.record_location tl
section_comment = RDoc::Comment.new('section comment')
section_comment.location = tl
assert_equal 1, cm.sections.length, 'sanity, default section only'
s0 = cm.sections.first
s1 = cm.add_section 'section', section_comment
cm.add_attribute a1
cm.add_attribute a2
cm.add_method m1
cm.add_constant c1
cm.add_include i1
cm.add_extend e1
cm.add_comment 'this is a comment', tl
loaded = Marshal.load Marshal.dump cm
loaded.store = @store
assert_equal cm, loaded
inner = RDoc::Markup::Document.new(
RDoc::Markup::Paragraph.new('this is a comment'))
inner.file = tl
comment = RDoc::Markup::Document.new inner
assert_equal [a2, a1], loaded.attributes.sort
assert_equal comment, loaded.comment
assert_equal [c1], loaded.constants
assert_equal 'Namespace::Klass', loaded.full_name
assert_equal [i1], loaded.includes
assert_equal [e1], loaded.extends
assert_equal [m1], loaded.method_list
assert_equal 'Klass', loaded.name
assert_equal 'Super', loaded.superclass
assert_equal [tl], loaded.in_files
assert_equal 'Namespace', loaded.parent.name
expected = { nil => s0, 'section' => s1 }
assert_equal expected, loaded.sections_hash
assert_equal tl, loaded.attributes.first.file
assert_equal tl, loaded.constants.first.file
assert_equal tl, loaded.includes.first.file
assert_equal tl, loaded.extends.first.file
assert_equal tl, loaded.method_list.first.file
end
def test_marshal_dump_visibilty
@store.path = Dir.tmpdir
tl = @store.add_file 'file.rb'
ns = tl.add_module RDoc::NormalModule, 'Namespace'
cm = ns.add_class RDoc::NormalClass, 'Klass', 'Super'
cm.record_location tl
a1 = RDoc::Attr.new nil, 'a1', 'RW', ''
a1.record_location tl
a1.document_self = false
m1 = RDoc::AnyMethod.new nil, 'm1'
m1.record_location tl
m1.document_self = false
c1 = RDoc::Constant.new 'C1', nil, ''
c1.record_location tl
c1.document_self = false
i1 = RDoc::Include.new 'I1', ''
i1.record_location tl
i1.document_self = false
e1 = RDoc::Extend.new 'E1', ''
e1.record_location tl
e1.document_self = false
section_comment = RDoc::Comment.new('section comment')
section_comment.location = tl
assert_equal 1, cm.sections.length, 'sanity, default section only'
cm.add_attribute a1
cm.add_method m1
cm.add_constant c1
cm.add_include i1
cm.add_extend e1
cm.add_comment 'this is a comment', tl
loaded = Marshal.load Marshal.dump cm
loaded.store = @store
assert_equal cm, loaded
assert_empty loaded.attributes
assert_empty loaded.constants
assert_empty loaded.includes
assert_empty loaded.extends
assert_empty loaded.method_list
end
def test_marshal_load_version_0
tl = @store.add_file 'file.rb'
ns = tl.add_module RDoc::NormalModule, 'Namespace'
cm = ns.add_class RDoc::NormalClass, 'Klass', 'Super'
a = RDoc::Attr.new(nil, 'a1', 'RW', '')
m = RDoc::AnyMethod.new(nil, 'm1')
c = RDoc::Constant.new('C1', nil, '')
i = RDoc::Include.new('I1', '')
s0 = cm.sections.first
cm.add_attribute a
cm.add_method m
cm.add_constant c
cm.add_include i
cm.add_comment 'this is a comment', tl
loaded = Marshal.load "\x04\bU:\x16RDoc::NormalClass[\x0Ei\x00\"\nKlass" +
"\"\x15Namespace::KlassI\"\nSuper\x06:\x06EF" +
"o:\eRDoc::Markup::Document\x06:\v@parts[\x06" +
"o:\x1CRDoc::Markup::Paragraph\x06;\b[\x06I" +
"\"\x16this is a comment\x06;\x06F[\x06[\aI" +
"\"\aa1\x06;\x06FI\"\aRW\x06;\x06F[\x06[\aI" +
"\"\aC1\x06;\x06Fo;\a\x06;\b[\x00[\x06[\aI" +
"\"\aI1\x06;\x06Fo;\a\x06;\b[\x00[\a[\aI" +
"\"\nclass\x06;\x06F[\b[\a:\vpublic[\x00[\a" +
":\x0Eprotected[\x00[\a:\fprivate[\x00[\aI" +
"\"\rinstance\x06;\x06F[\b[\a;\n[\x06I" +
"\"\am1\x06;\x06F[\a;\v[\x00[\a;\f[\x00"
loaded.store = @store
assert_equal cm, loaded
comment = RDoc::Markup::Document.new(
RDoc::Markup::Paragraph.new('this is a comment'))
assert_equal [a], loaded.attributes
assert_equal comment, loaded.comment
assert_equal [c], loaded.constants
assert_equal 'Namespace::Klass', loaded.full_name
assert_equal [i], loaded.includes
assert_equal [m], loaded.method_list
assert_equal 'Klass', loaded.name
assert_equal 'Super', loaded.superclass
assert_nil loaded.file
assert_empty loaded.in_files
assert_nil loaded.parent
assert loaded.current_section
expected = { nil => s0 }
assert_equal expected, loaded.sections_hash
assert loaded.display?
end
def test_marshal_load_version_1
tl = @store.add_file 'file.rb'
ns = tl.add_module RDoc::NormalModule, 'Namespace'
cm = ns.add_class RDoc::NormalClass, 'Klass', 'Super'
cm.record_location tl
a1 = RDoc::Attr.new nil, 'a1', 'RW', ''
a1.record_location tl
a2 = RDoc::Attr.new nil, 'a2', 'RW', '', true
a2.record_location tl
m1 = RDoc::AnyMethod.new nil, 'm1'
m1.record_location tl
c1 = RDoc::Constant.new 'C1', nil, ''
c1.record_location tl
i1 = RDoc::Include.new 'I1', ''
i1.record_location tl
s0 = cm.sections.first
cm.add_attribute a1
cm.add_attribute a2
cm.add_method m1
cm.add_constant c1
cm.add_include i1
cm.add_comment 'this is a comment', tl
loaded = Marshal.load "\x04\bU:\x16RDoc::NormalClass[\x0Ei\x06I\"\nKlass" +
"\x06:\x06EFI\"\x15Namespace::Klass\x06;\x06FI" +
"\"\nSuper\x06;\x06Fo:\eRDoc::Markup::Document\a" +
":\v@parts[\x06o;\a\a;\b[\x06o" +
":\x1CRDoc::Markup::Paragraph\x06;\b" +
"[\x06I\"\x16this is a comment\x06;\x06F" +
":\n@fileI\"\ffile.rb\x06;\x06F;\n0[\a[\nI" +
"\"\aa2\x06;\x06FI\"\aRW\x06;\x06F:\vpublicT@\x11" +
"[\nI\"\aa1\x06;\x06FI\"\aRW\x06;\x06F;\vF@\x11" +
"[\x06[\bI\"\aC1\x06;\x06Fo;\a\a;\b[\x00;\n0@\x11" +
"[\x06[\bI\"\aI1\x06;\x06Fo;\a\a;\b[\x00;\n0@\x11" +
"[\a[\aI\"\nclass\x06;\x06F[\b[\a;\v[\x00" +
"[\a:\x0Eprotected[\x00[\a:\fprivate[\x00[\aI" +
"\"\rinstance\x06;\x06F[\b[\a;\v[\x06[\aI" +
"\"\am1\x06;\x06F@\x11[\a;\f[\x00[\a;\r[\x00"
loaded.store = @store
assert_equal cm, loaded
inner = RDoc::Markup::Document.new(
RDoc::Markup::Paragraph.new('this is a comment'))
inner.file = tl
comment = RDoc::Markup::Document.new inner
assert_equal [a2, a1], loaded.attributes.sort
assert_equal comment, loaded.comment
assert_equal [c1], loaded.constants
assert_equal 'Namespace::Klass', loaded.full_name
assert_equal [i1], loaded.includes
assert_empty loaded.extends
assert_equal [m1], loaded.method_list
assert_equal 'Klass', loaded.name
assert_equal 'Super', loaded.superclass
assert_empty loaded.in_files
assert_nil loaded.parent
assert loaded.current_section
assert_equal tl, loaded.attributes.first.file
assert_equal tl, loaded.constants.first.file
assert_equal tl, loaded.includes.first.file
assert_equal tl, loaded.method_list.first.file
expected = { nil => s0 }
assert_equal expected, loaded.sections_hash
end
def test_marshal_load_version_2
tl = @store.add_file 'file.rb'
ns = tl.add_module RDoc::NormalModule, 'Namespace'
cm = ns.add_class RDoc::NormalClass, 'Klass', 'Super'
cm.record_location tl
a1 = RDoc::Attr.new nil, 'a1', 'RW', ''
a1.record_location tl
a2 = RDoc::Attr.new nil, 'a2', 'RW', '', true
a2.record_location tl
m1 = RDoc::AnyMethod.new nil, 'm1'
m1.record_location tl
c1 = RDoc::Constant.new 'C1', nil, ''
c1.record_location tl
i1 = RDoc::Include.new 'I1', ''
i1.record_location tl
e1 = RDoc::Extend.new 'E1', ''
e1.record_location tl
s0 = cm.sections.first
cm.add_attribute a1
cm.add_attribute a2
cm.add_method m1
cm.add_constant c1
cm.add_include i1
cm.add_extend e1
cm.add_comment 'this is a comment', tl
loaded = Marshal.load "\x04\bU:\x16RDoc::NormalClass[\x0Fi\aI\"\nKlass" +
"\x06:\x06EFI\"\x15Namespace::Klass\x06;\x06FI" +
"\"\nSuper\x06;\x06Fo:\eRDoc::Markup::Document\a" +
":\v@parts[\x06o;\a\a;\b[\x06o" +
":\x1CRDoc::Markup::Paragraph\x06;\b" +
"[\x06I\"\x16this is a comment\x06;\x06F" +
":\n@fileI\"\ffile.rb\x06;\x06F;\n0[\a[\nI" +
"\"\aa2\x06;\x06FI\"\aRW\x06;\x06F:\vpublicT@\x11" +
"[\nI\"\aa1\x06;\x06FI\"\aRW\x06;\x06F;\vF@\x11" +
"[\x06[\bI\"\aC1\x06;\x06Fo;\a\a;\b[\x00;\n0@\x11" +
"[\x06[\bI\"\aI1\x06;\x06Fo;\a\a;\b[\x00;\n0@\x11" +
"[\a[\aI\"\nclass\x06;\x06F[\b[\a;\v[\x00" +
"[\a:\x0Eprotected[\x00[\a:\fprivate[\x00[\aI" +
"\"\rinstance\x06;\x06F[\b[\a;\v[\x06[\aI" +
"\"\am1\x06;\x06F@\x11[\a;\f[\x00[\a;\r[\x00" +
"[\x06[\bI\"\aE1\x06;\x06Fo;\a\a;\b[\x00;\n0@\x11"
loaded.store = @store
assert_equal cm, loaded
inner = RDoc::Markup::Document.new(
RDoc::Markup::Paragraph.new('this is a comment'))
inner.file = tl
comment = RDoc::Markup::Document.new inner
assert_equal [a2, a1], loaded.attributes.sort
assert_equal comment, loaded.comment
assert_equal [c1], loaded.constants
assert_equal 'Namespace::Klass', loaded.full_name
assert_equal [i1], loaded.includes
assert_equal [e1], loaded.extends
assert_equal [m1], loaded.method_list
assert_equal 'Klass', loaded.name
assert_equal 'Super', loaded.superclass
assert_empty loaded.in_files
assert_nil loaded.parent
assert loaded.current_section
assert_equal tl, loaded.attributes. first.file
assert_equal tl, loaded.constants. first.file
assert_equal tl, loaded.includes. first.file
assert_equal tl, loaded.extends. first.file
assert_equal tl, loaded.method_list.first.file
expected = { nil => s0 }
assert_equal expected, loaded.sections_hash
end
def test_marshal_load_version_3
tl = @store.add_file 'file.rb'
ns = tl.add_module RDoc::NormalModule, 'Namespace'
cm = ns.add_class RDoc::NormalClass, 'Klass', 'Super'
cm.record_location tl
a1 = RDoc::Attr.new nil, 'a1', 'RW', ''
a1.record_location tl
a2 = RDoc::Attr.new nil, 'a2', 'RW', '', true
a2.record_location tl
m1 = RDoc::AnyMethod.new nil, 'm1'
m1.record_location tl
c1 = RDoc::Constant.new 'C1', nil, ''
c1.record_location tl
i1 = RDoc::Include.new 'I1', ''
i1.record_location tl
e1 = RDoc::Extend.new 'E1', ''
e1.record_location tl
section_comment = RDoc::Comment.new('section comment')
section_comment.location = tl
assert_equal 1, cm.sections.length, 'sanity, default section only'
s0 = cm.sections.first
s1 = cm.add_section 'section', section_comment
cm.add_attribute a1
cm.add_attribute a2
cm.add_method m1
cm.add_constant c1
cm.add_include i1
cm.add_extend e1
cm.add_comment 'this is a comment', tl
loaded = Marshal.load "\x04\bU:\x16RDoc::NormalClass[\x13i\bI\"\nKlass" +
"\x06:\x06ETI\"\x15Namespace::Klass\x06;\x06TI" +
"\"\nSuper\x06;\x06To:\eRDoc::Markup::Document\a" +
":\v@parts[\x06o;\a\a;\b[\x06o" +
":\x1CRDoc::Markup::Paragraph\x06;\b[\x06I" +
"\"\x16this is a comment\x06;\x06T:\n@fileI" +
"\"\ffile.rb\x06;\x06T;\n0[\a[\nI\"\aa2\x06;" +
"\x06TI\"\aRW\x06;\x06T:\vpublicT@\x11[\nI" +
"\"\aa1\x06;\x06TI\"\aRW\x06;\x06T;\vF@\x11" +
"[\x06U:\x13RDoc::Constant[\x0Fi\x00I\"\aC1\x06" +
";\x06TI\"\x19Namespace::Klass::C1\x06;\x06T00o" +
";\a\a;\b[\x00;\n0@\x11@\ac\x16RDoc::NormalClass0" +
"[\x06[\bI\"\aI1\x06;\x06To;\a\a;\b[\x00;\n0@\x11" +
"[\a[\aI\"\nclass\x06;\x06T[\b[\a;\v[\x00[\a" +
":\x0Eprotected[\x00[\a:\fprivate[\x00[\aI" +
"\"\rinstance\x06;\x06T[\b[\a;\v[\x06[\aI" +
"\"\am1\x06;\x06T@\x11[\a;\r[\x00[\a;\x0E[\x00" +
"[\x06[\bI\"\aE1\x06;\x06To;\a\a;\b[\x00;\n0@\x11" +
"[\aU:\eRDoc::Context::Section[\bi\x000o;\a\a;\b" +
"[\x00;\n0U;\x0F[\bi\x00I\"\fsection\x06;\x06To" +
";\a\a;\b[\x06o;\a\a;\b[\x06o;\t\x06;\b[\x06I" +
"\"\x14section comment\x06;\x06T;\n@\x11;\n0" +
"[\x06@\x11I\"\x0ENamespace\x06" +
";\x06Tc\x17RDoc::NormalModule"
loaded.store = @store
assert_equal cm, loaded
inner = RDoc::Markup::Document.new(
RDoc::Markup::Paragraph.new('this is a comment'))
inner.file = tl
comment = RDoc::Markup::Document.new inner
assert_equal [a2, a1], loaded.attributes.sort
assert_equal comment, loaded.comment
assert_equal [c1], loaded.constants
assert_equal 'Namespace::Klass', loaded.full_name
assert_equal [i1], loaded.includes
assert_equal [e1], loaded.extends
assert_equal [m1], loaded.method_list
assert_equal 'Klass', loaded.name
assert_equal 'Super', loaded.superclass
assert_equal 'Namespace', loaded.parent.name
assert loaded.current_section
expected = {
nil => s0,
'section' => s1,
}
assert_equal expected, loaded.sections_hash
assert_equal [tl], loaded.in_files
assert_equal tl, loaded.attributes. first.file
assert_equal tl, loaded.constants. first.file
assert_equal tl, loaded.includes. first.file
assert_equal tl, loaded.extends. first.file
assert_equal tl, loaded.method_list.first.file
end
def test_merge
tl = @store.add_file 'one.rb'
p1 = tl.add_class RDoc::NormalClass, 'Parent'
c1 = p1.add_class RDoc::NormalClass, 'Klass'
c2 = RDoc::NormalClass.new 'Klass'
c2.merge c1
assert_equal 'Parent', c1.parent_name, 'original parent name'
assert_equal 'Parent', c2.parent_name, 'merged parent name'
assert c1.current_section, 'original current_section'
assert c2.current_section, 'merged current_section'
end
def test_merge_attributes
tl1 = @store.add_file 'one.rb'
tl2 = @store.add_file 'two.rb'
cm1 = RDoc::ClassModule.new 'Klass'
attr = cm1.add_attribute RDoc::Attr.new(nil, 'a1', 'RW', '')
attr.record_location tl1
attr = cm1.add_attribute RDoc::Attr.new(nil, 'a3', 'R', '')
attr.record_location tl1
attr = cm1.add_attribute RDoc::Attr.new(nil, 'a4', 'R', '')
attr.record_location tl1
cm2 = RDoc::ClassModule.new 'Klass'
# TODO allow merging when comment == ''
cm2.instance_variable_set :@comment, @RM::Document.new
attr = cm2.add_attribute RDoc::Attr.new(nil, 'a2', 'RW', '')
attr.record_location tl2
attr = cm2.add_attribute RDoc::Attr.new(nil, 'a3', 'W', '')
attr.record_location tl1
attr = cm2.add_attribute RDoc::Attr.new(nil, 'a4', 'W', '')
attr.record_location tl1
cm1.merge cm2
expected = [
RDoc::Attr.new(nil, 'a2', 'RW', ''),
RDoc::Attr.new(nil, 'a3', 'W', ''),
RDoc::Attr.new(nil, 'a4', 'W', ''),
]
expected.each do |a| a.parent = cm1 end
assert_equal expected, cm1.attributes.sort
end
def test_merge_attributes_version_0
tl1 = @store.add_file 'one.rb'
cm1 = RDoc::ClassModule.new 'Klass'
attr = cm1.add_attribute RDoc::Attr.new(nil, 'a1', 'RW', '')
attr.record_location tl1
attr = cm1.add_attribute RDoc::Attr.new(nil, 'a3', 'R', '')
attr.record_location tl1
attr = cm1.add_attribute RDoc::Attr.new(nil, 'a4', 'R', '')
attr.record_location tl1
cm2 = RDoc::ClassModule.new 'Klass'
# TODO allow merging when comment == ''
cm2.instance_variable_set :@comment, @RM::Document.new
attr = cm2.add_attribute RDoc::Attr.new(nil, 'a2', 'RW', '')
attr = cm2.add_attribute RDoc::Attr.new(nil, 'a3', 'W', '')
attr = cm2.add_attribute RDoc::Attr.new(nil, 'a4', 'W', '')
cm1.merge cm2
expected = [
RDoc::Attr.new(nil, 'a1', 'RW', ''),
RDoc::Attr.new(nil, 'a2', 'RW', ''),
RDoc::Attr.new(nil, 'a3', 'RW', ''),
RDoc::Attr.new(nil, 'a4', 'RW', ''),
]
expected.each do |a| a.parent = cm1 end
assert_equal expected, cm1.attributes.sort
end
def test_merge_collections_drop
tl = @store.add_file 'file'
cm1 = RDoc::ClassModule.new 'C'
cm1.record_location tl
const = cm1.add_constant RDoc::Constant.new('CONST', nil, nil)
const.record_location tl
cm2 = RDoc::ClassModule.new 'C'
cm2.record_location tl
added = []
removed = []
cm1.merge_collections cm1.constants, cm2.constants, cm2.in_files do |add, c|
if add then
added << c
else
removed << c
end
end
assert_empty added
assert_equal [const], removed
end
def test_merge_comment
tl1 = @store.add_file 'one.rb'
tl2 = @store.add_file 'two.rb'
cm1 = tl1.add_class RDoc::ClassModule, 'Klass'
cm1.add_comment 'klass 1', tl1
cm1.record_location tl1
cm2 = tl1.add_class RDoc::NormalClass, 'Klass'
cm2.add_comment 'klass 2', tl2
cm2.add_comment 'klass 3', tl1
cm2.record_location tl1
cm2.record_location tl2
cm2 = Marshal.load Marshal.dump cm2
cm2.store = @store
cm1.merge cm2
inner1 = @RM::Document.new @RM::Paragraph.new 'klass 3'
inner1.file = 'one.rb'
inner2 = @RM::Document.new @RM::Paragraph.new 'klass 2'
inner2.file = 'two.rb'
expected = @RM::Document.new inner2, inner1
assert_equal expected, cm1.comment
end
def test_merge_comment_version_0
tl = @store.add_file 'file.rb'
cm1 = RDoc::ClassModule.new 'Klass'
cm1.add_comment 'klass 1', tl
cm2 = RDoc::ClassModule.new 'Klass'
cm2.instance_variable_set(:@comment,
@RM::Document.new(
@RM::Paragraph.new('klass 2')))
cm2.instance_variable_set :@comment_location, @RM::Document.new(cm2.comment)
cm1.merge cm2
inner = @RM::Document.new @RM::Paragraph.new 'klass 1'
inner.file = 'file.rb'
expected = @RM::Document.new \
inner,
@RM::Document.new(@RM::Paragraph.new('klass 2'))
assert_equal expected, cm1.comment
end
def test_merge_constants
tl1 = @store.add_file 'one.rb'
tl2 = @store.add_file 'two.rb'
cm1 = tl1.add_class RDoc::ClassModule, 'Klass'
const = cm1.add_constant RDoc::Constant.new('C1', nil, 'one')
const.record_location tl1
const = cm1.add_constant RDoc::Constant.new('C3', nil, 'one')
const.record_location tl1
store = RDoc::Store.new
tl = store.add_file 'one.rb'
cm2 = tl.add_class RDoc::ClassModule, 'Klass'
cm2.instance_variable_set :@comment, @RM::Document.new
const = cm2.add_constant RDoc::Constant.new('C2', nil, 'two')
const.record_location tl2
const = cm2.add_constant RDoc::Constant.new('C3', nil, 'one')
const.record_location tl1
const = cm2.add_constant RDoc::Constant.new('C4', nil, 'one')
const.record_location tl1
cm1.merge cm2
expected = [
RDoc::Constant.new('C2', nil, 'two'),
RDoc::Constant.new('C3', nil, 'one'),
RDoc::Constant.new('C4', nil, 'one'),
]
expected.each do |a| a.parent = cm1 end
assert_equal expected, cm1.constants.sort
end
def test_merge_constants_version_0
tl1 = @store.add_file 'one.rb'
cm1 = tl1.add_class RDoc::ClassModule, 'Klass'
const = cm1.add_constant RDoc::Constant.new('C1', nil, 'one')
const.record_location tl1
const = cm1.add_constant RDoc::Constant.new('C3', nil, 'one')
const.record_location tl1
store = RDoc::Store.new
tl = store.add_file 'one.rb'
cm2 = tl.add_class RDoc::ClassModule, 'Klass'
cm2.instance_variable_set :@comment, @RM::Document.new
const = cm2.add_constant RDoc::Constant.new('C2', nil, 'two')
const = cm2.add_constant RDoc::Constant.new('C3', nil, 'two')
const = cm2.add_constant RDoc::Constant.new('C4', nil, 'two')
cm1.merge cm2
expected = [
RDoc::Constant.new('C1', nil, 'one'),
RDoc::Constant.new('C2', nil, 'two'),
RDoc::Constant.new('C3', nil, 'one'),
RDoc::Constant.new('C4', nil, 'two'),
]
expected.each do |a| a.parent = cm1 end
assert_equal expected, cm1.constants.sort
end
def test_merge_extends
tl1 = @store.add_file 'one.rb'
cm1 = tl1.add_class RDoc::ClassModule, 'Klass'
ext = cm1.add_extend RDoc::Extend.new('I1', 'one')
ext.record_location tl1
ext = cm1.add_extend RDoc::Extend.new('I3', 'one')
ext.record_location tl1
tl2 = @store.add_file 'two.rb'
tl2.store = RDoc::Store.new
cm2 = tl2.add_class RDoc::ClassModule, 'Klass'
cm2.instance_variable_set :@comment, @RM::Document.new
ext = cm2.add_extend RDoc::Extend.new('I2', 'two')
ext.record_location tl2
ext = cm2.add_extend RDoc::Extend.new('I3', 'one')
ext.record_location tl1
ext = cm2.add_extend RDoc::Extend.new('I4', 'one')
ext.record_location tl1
cm1.merge cm2
expected = [
RDoc::Extend.new('I2', 'two'),
RDoc::Extend.new('I3', 'one'),
RDoc::Extend.new('I4', 'one'),
]
expected.each do |a| a.parent = cm1 end
assert_equal expected, cm1.extends.sort
end
def test_merge_includes
tl1 = @store.add_file 'one.rb'
cm1 = tl1.add_class RDoc::ClassModule, 'Klass'
incl = cm1.add_include RDoc::Include.new('I1', 'one')
incl.record_location tl1
incl = cm1.add_include RDoc::Include.new('I3', 'one')
incl.record_location tl1
tl2 = @store.add_file 'two.rb'
tl2.store = RDoc::Store.new
cm2 = tl2.add_class RDoc::ClassModule, 'Klass'
cm2.instance_variable_set :@comment, @RM::Document.new
incl = cm2.add_include RDoc::Include.new('I2', 'two')
incl.record_location tl2
incl = cm2.add_include RDoc::Include.new('I3', 'one')
incl.record_location tl1
incl = cm2.add_include RDoc::Include.new('I4', 'one')
incl.record_location tl1
cm1.merge cm2
expected = [
RDoc::Include.new('I2', 'two'),
RDoc::Include.new('I3', 'one'),
RDoc::Include.new('I4', 'one'),
]
expected.each do |a| a.parent = cm1 end
assert_equal expected, cm1.includes.sort
end
def test_merge_includes_version_0
tl1 = @store.add_file 'one.rb'
cm1 = tl1.add_class RDoc::ClassModule, 'Klass'
incl = cm1.add_include RDoc::Include.new('I1', 'one')
incl.record_location tl1
incl = cm1.add_include RDoc::Include.new('I3', 'one')
incl.record_location tl1
tl2 = @store.add_file 'one.rb'
tl2.store = RDoc::Store.new
cm2 = tl2.add_class RDoc::ClassModule, 'Klass'
cm2.instance_variable_set :@comment, @RM::Document.new
incl = cm2.add_include RDoc::Include.new('I2', 'two')
incl = cm2.add_include RDoc::Include.new('I3', 'two')
incl = cm2.add_include RDoc::Include.new('I4', 'two')
cm1.merge cm2
expected = [
RDoc::Include.new('I1', 'one'),
RDoc::Include.new('I2', 'two'),
RDoc::Include.new('I3', 'one'),
RDoc::Include.new('I4', 'two'),
]
expected.each do |a| a.parent = cm1 end
assert_equal expected, cm1.includes.sort
end
def test_merge_methods
tl1 = @store.add_file 'one.rb'
tl2 = @store.add_file 'two.rb'
cm1 = tl1.add_class RDoc::NormalClass, 'Klass'
meth = cm1.add_method RDoc::AnyMethod.new(nil, 'm1')
meth.record_location tl1
meth = cm1.add_method RDoc::AnyMethod.new(nil, 'm3')
meth.record_location tl1
cm2 = RDoc::ClassModule.new 'Klass'
cm2.store = @store
cm2.instance_variable_set :@comment, @RM::Document.new
meth = cm2.add_method RDoc::AnyMethod.new(nil, 'm2')
meth.record_location tl2
meth = cm2.add_method RDoc::AnyMethod.new(nil, 'm3')
meth.record_location tl1
meth = cm2.add_method RDoc::AnyMethod.new(nil, 'm4')
meth.record_location tl1
cm1.merge cm2
expected = [
RDoc::AnyMethod.new(nil, 'm2'),
RDoc::AnyMethod.new(nil, 'm3'),
RDoc::AnyMethod.new(nil, 'm4'),
]
expected.each do |a| a.parent = cm1 end
assert_equal expected, cm1.method_list.sort
end
def test_merge_methods_version_0
tl1 = @store.add_file 'one.rb'
cm1 = tl1.add_class RDoc::NormalClass, 'Klass'
meth = cm1.add_method RDoc::AnyMethod.new(nil, 'm1')
meth.record_location tl1
meth = cm1.add_method RDoc::AnyMethod.new(nil, 'm3')
meth.record_location tl1
cm2 = RDoc::ClassModule.new 'Klass'
cm2.store = @store
cm2.instance_variable_set :@comment, @RM::Document.new
meth = cm2.add_method RDoc::AnyMethod.new(nil, 'm2')
meth = cm2.add_method RDoc::AnyMethod.new(nil, 'm3')
meth = cm2.add_method RDoc::AnyMethod.new(nil, 'm4')
cm1.merge cm2
expected = [
RDoc::AnyMethod.new(nil, 'm1'),
RDoc::AnyMethod.new(nil, 'm2'),
RDoc::AnyMethod.new(nil, 'm3'),
RDoc::AnyMethod.new(nil, 'm4'),
]
expected.each do |a| a.parent = cm1 end
assert_equal expected, cm1.method_list.sort
end
def test_merge_sections
store1 = @store
tl1_1 = store1.add_file 'one.rb'
cm1 = tl1_1.add_class RDoc::ClassModule, 'Klass'
cm1.record_location tl1_1
s1_0 = cm1.sections.first
s1_1 = cm1.add_section 'section 1', comment('comment 1', tl1_1)
cm1.add_section 'section 2', comment('comment 2 a', tl1_1)
cm1.add_section 'section 4', comment('comment 4 a', tl1_1)
store2 = RDoc::Store.new
tl2_1 = store2.add_file 'one.rb'
tl2_2 = store2.add_file 'two.rb'
cm2 = tl2_1.add_class RDoc::ClassModule, 'Klass'
cm2.record_location tl2_1
cm2.record_location tl2_2
cm2.sections.first
s2_2 = cm2.add_section 'section 2', comment('comment 2 b', tl2_1)
s2_3 = cm2.add_section 'section 3', comment('comment 3', tl2_2)
cm2.add_section 'section 4', comment('comment 4 b', tl2_2)
cm1.merge cm2
expected = [
s1_0,
s1_1,
s2_2,
s2_3,
RDoc::Context::Section.new(cm1, 'section 4', nil)
]
merged_sections = cm1.sections.sort_by do |s|
s.title || ''
end
assert_equal expected, merged_sections
assert_equal [comment('comment 2 b', tl2_1)],
cm1.sections_hash['section 2'].comments
expected_s4_comments = [
comment('comment 4 a', tl2_1),
comment('comment 4 b', tl2_2),
]
assert_equal expected_s4_comments, cm1.sections_hash['section 4'].comments
end
def test_merge_sections_overlap
store1 = @store
tl1_1 = store1.add_file 'one.rb'
tl1_3 = store1.add_file 'three.rb'
cm1 = tl1_1.add_class RDoc::ClassModule, 'Klass'
cm1.record_location tl1_1
cm1.add_section 'section', comment('comment 1 a', tl1_1)
cm1.add_section 'section', comment('comment 3', tl1_3)
store2 = RDoc::Store.new
tl2_1 = store2.add_file 'one.rb'
tl2_2 = store2.add_file 'two.rb'
tl2_3 = store2.add_file 'three.rb'
cm2 = tl2_1.add_class RDoc::ClassModule, 'Klass'
cm2.record_location tl2_1
cm2.record_location tl2_2
s2_0 = cm2.sections.first
s2_1 = cm2.add_section 'section', comment('comment 1 b', tl1_1)
cm2.add_section 'section', comment('comment 2', tl2_2)
cm1.merge_sections cm2
expected = [
s2_0,
s2_1,
]
merged_sections = cm1.sections.sort_by do |s|
s.title || ''
end
assert_equal expected, merged_sections
expected = [
comment('comment 1 b', tl2_1),
comment('comment 3', tl2_3),
comment('comment 2', tl2_2),
]
comments = cm1.sections_hash['section'].comments
assert_equal expected, comments.sort_by { |c| c.file.name }
end
def test_parse
tl1 = @store.add_file 'one.rb'
tl2 = @store.add_file 'two.rb'
cm = RDoc::ClassModule.new 'Klass'
cm.add_comment 'comment 1', tl1
cm.add_comment 'comment 2', tl2
doc1 = @RM::Document.new @RM::Paragraph.new 'comment 1'
doc1.file = tl1
doc2 = @RM::Document.new @RM::Paragraph.new 'comment 2'
doc2.file = tl2
expected = @RM::Document.new doc1, doc2
assert_equal expected, cm.parse(cm.comment_location)
end
def test_parse_comment
tl1 = @store.add_file 'one.rb'
cm = RDoc::ClassModule.new 'Klass'
cm.comment = comment 'comment 1', tl1
doc = @RM::Document.new @RM::Paragraph.new 'comment 1'
doc.file = tl1
assert_equal doc, cm.parse(cm.comment)
end
def test_parse_comment_format
tl1 = @store.add_file 'one.rb'
cm = RDoc::ClassModule.new 'Klass'
cm.comment = comment 'comment ((*1*))', tl1
cm.comment.format = 'rd'
doc = @RM::Document.new @RM::Paragraph.new 'comment <em>1</em>'
doc.file = tl1
assert_equal doc, cm.parse(cm.comment)
end
def test_parse_comment_location
tl1 = @store.add_file 'one.rb'
tl2 = @store.add_file 'two.rb'
cm = tl1.add_class RDoc::NormalClass, 'Klass'
cm.add_comment 'comment 1', tl1
cm.add_comment 'comment 2', tl2
cm = Marshal.load Marshal.dump cm
doc1 = @RM::Document.new @RM::Paragraph.new 'comment 1'
doc1.file = tl1
doc2 = @RM::Document.new @RM::Paragraph.new 'comment 2'
doc2.file = tl2
assert_same cm.comment_location, cm.parse(cm.comment_location)
end
def test_remove_nodoc_children
parent = @top_level.add_class RDoc::ClassModule, 'A'
parent.modules_hash.replace 'B' => true, 'C' => true
@store.modules_hash.replace 'A::B' => true
parent.classes_hash.replace 'D' => true, 'E' => true
@store.classes_hash.replace 'A::D' => true
parent.remove_nodoc_children
assert_equal %w[B], parent.modules_hash.keys
assert_equal %w[D], parent.classes_hash.keys
end
def test_search_record
@c2_c3.add_comment 'This is a comment.', @xref_data
expected = [
'C3',
'C2::C3',
'C2::C3',
'',
'C2/C3.html',
'',
"<p>This is a comment.\n"
]
assert_equal expected, @c2_c3.search_record
end
def test_search_record_merged
@c2_c3.add_comment 'comment A', @store.add_file('a.rb')
@c2_c3.add_comment 'comment B', @store.add_file('b.rb')
expected = [
'C3',
'C2::C3',
'C2::C3',
'',
'C2/C3.html',
'',
"<p>comment A\n<p>comment B\n"
]
assert_equal expected, @c2_c3.search_record
end
def test_store_equals
# version 2
loaded = Marshal.load "\x04\bU:\x16RDoc::NormalClass[\x0Fi\aI\"\nKlass" +
"\x06:\x06EFI\"\x15Namespace::Klass\x06;\x06FI" +
"\"\nSuper\x06;\x06Fo:\eRDoc::Markup::Document\a" +
":\v@parts[\x06o;\a\a;\b[\x06o" +
":\x1CRDoc::Markup::Paragraph\x06;\b" +
"[\x06I\"\x16this is a comment\x06;\x06F" +
":\n@fileI\"\ffile.rb\x06;\x06F;\n0[\a[\nI" +
"\"\aa2\x06;\x06FI\"\aRW\x06;\x06F:\vpublicT@\x11" +
"[\nI\"\aa1\x06;\x06FI\"\aRW\x06;\x06F;\vF@\x11" +
"[\x06[\bI\"\aC1\x06;\x06Fo;\a\a;\b[\x00;\n0@\x11" +
"[\x06[\bI\"\aI1\x06;\x06Fo;\a\a;\b[\x00;\n0@\x11" +
"[\a[\aI\"\nclass\x06;\x06F[\b[\a;\v[\x00" +
"[\a:\x0Eprotected[\x00[\a:\fprivate[\x00[\aI" +
"\"\rinstance\x06;\x06F[\b[\a;\v[\x06[\aI" +
"\"\am1\x06;\x06F@\x11[\a;\f[\x00[\a;\r[\x00" +
"[\x06[\bI\"\aE1\x06;\x06Fo;\a\a;\b[\x00;\n0@\x11"
loaded.store = @store
assert_same @store, loaded.store
a = loaded.attributes.first
assert_same @store, a.store
assert_same @store, a.file.store
c = loaded.constants.first
assert_same @store, c.store
assert_same @store, c.file.store
i = loaded.includes.first
assert_same @store, i.store
assert_same @store, i.file.store
e = loaded.extends.first
assert_same @store, e.store
assert_same @store, e.file.store
m = loaded.method_list.first
assert_same @store, m.store
assert_same @store, m.file.store
end
def test_superclass
assert_equal @c3_h1, @c3_h2.superclass
end
def test_update_aliases_class
n1 = @xref_data.add_module RDoc::NormalClass, 'N1'
n1_k2 = n1.add_module RDoc::NormalClass, 'N2'
n1.add_module_alias n1_k2, 'A1', @xref_data
n1_a1_c = n1.constants.find { |c| c.name == 'A1' }
refute_nil n1_a1_c
assert_equal n1_k2, n1_a1_c.is_alias_for, 'sanity check'
n1.update_aliases
n1_a1_k = @xref_data.find_class_or_module 'N1::A1'
refute_nil n1_a1_k
assert_equal n1_k2, n1_a1_k.is_alias_for
refute_equal n1_k2, n1_a1_k
assert_equal 1, n1_k2.aliases.length
assert_equal n1_a1_k, n1_k2.aliases.first
assert_equal 'N1::N2', n1_k2.full_name
assert_equal 'N1::A1', n1_a1_k.full_name
end
def test_update_aliases_module
n1 = @xref_data.add_module RDoc::NormalModule, 'N1'
n1_n2 = n1.add_module RDoc::NormalModule, 'N2'
n1.add_module_alias n1_n2, 'A1', @xref_data
n1_a1_c = n1.constants.find { |c| c.name == 'A1' }
refute_nil n1_a1_c
assert_equal n1_n2, n1_a1_c.is_alias_for, 'sanity check'
n1.update_aliases
n1_a1_m = @xref_data.find_class_or_module 'N1::A1'
refute_nil n1_a1_m
assert_equal n1_n2, n1_a1_m.is_alias_for
refute_equal n1_n2, n1_a1_m
assert_equal 1, n1_n2.aliases.length
assert_equal n1_a1_m, n1_n2.aliases.first
assert_equal 'N1::N2', n1_n2.full_name
assert_equal 'N1::A1', n1_a1_m.full_name
end
def test_update_aliases_reparent
l1 = @xref_data.add_module RDoc::NormalModule, 'L1'
l1_l2 = l1.add_module RDoc::NormalModule, 'L2'
o1 = @xref_data.add_module RDoc::NormalModule, 'O1'
o1.add_module_alias l1_l2, 'A1', @xref_data
o1_a1_c = o1.constants.find { |c| c.name == 'A1' }
refute_nil o1_a1_c
assert_equal l1_l2, o1_a1_c.is_alias_for
refute_equal l1_l2, o1_a1_c
o1.update_aliases
o1_a1_m = @xref_data.find_class_or_module 'O1::A1'
refute_nil o1_a1_m
assert_equal l1_l2, o1_a1_m.is_alias_for
assert_equal 1, l1_l2.aliases.length
assert_equal o1_a1_m, l1_l2.aliases[0]
assert_equal 'L1::L2', l1_l2.full_name
assert_equal 'O1::A1', o1_a1_m.full_name
end
def test_update_aliases_reparent_root
store = RDoc::Store.new
top_level = store.add_file 'file.rb'
klass = top_level.add_class RDoc::NormalClass, 'Klass'
object = top_level.add_class RDoc::NormalClass, 'Object'
const = RDoc::Constant.new 'A', nil, ''
const.record_location top_level
const.is_alias_for = klass
top_level.add_module_alias klass, 'A', top_level
object.add_constant const
object.update_aliases
assert_equal %w[A Klass Object], store.classes_hash.keys.sort
assert_equal 'A', store.classes_hash['A'].full_name
assert_equal 'Klass', store.classes_hash['Klass'].full_name
end
def test_update_includes
a = RDoc::Include.new 'M1', nil
b = RDoc::Include.new 'M2', nil
c = RDoc::Include.new 'C', nil
@c1.add_include a
@c1.add_include b
@c1.add_include c
@c1.ancestors # cache included modules
@m1_m2.document_self = nil
assert @m1_m2.remove_from_documentation?
assert @store.modules_hash.key? @m1_m2.full_name
refute @store.modules_hash[@m1_m2.full_name].nil?
@store.remove_nodoc @store.modules_hash
refute @store.modules_hash.key? @m1_m2.full_name
@c1.update_includes
assert_equal [a, c], @c1.includes
end
def test_update_includes_trim
a = RDoc::Include.new 'D::M', nil
b = RDoc::Include.new 'D::M', nil
@c1.add_include a
@c1.add_include b
@c1.ancestors # cache included modules
@c1.update_includes
assert_equal [a], @c1.includes
end
def test_update_includes_with_colons
a = RDoc::Include.new 'M1', nil
b = RDoc::Include.new 'M1::M2', nil
c = RDoc::Include.new 'C', nil
@c1.add_include a
@c1.add_include b
@c1.add_include c
@c1.ancestors # cache included modules
@m1_m2.document_self = nil
assert @m1_m2.remove_from_documentation?
assert @store.modules_hash.key? @m1_m2.full_name
refute @store.modules_hash[@m1_m2.full_name].nil?
@store.remove_nodoc @store.modules_hash
refute @store.modules_hash.key? @m1_m2.full_name
@c1.update_includes
assert_equal [a, c], @c1.includes
end
def test_update_extends
a = RDoc::Extend.new 'M1', nil
b = RDoc::Extend.new 'M2', nil
c = RDoc::Extend.new 'C', nil
@c1.add_extend a
@c1.add_extend b
@c1.add_extend c
@c1.each_extend do |extend| extend.module end # cache extended modules
@m1_m2.document_self = nil
assert @m1_m2.remove_from_documentation?
assert @store.modules_hash.key? @m1_m2.full_name
refute @store.modules_hash[@m1_m2.full_name].nil?
@store.remove_nodoc @store.modules_hash
refute @store.modules_hash.key? @m1_m2.full_name
@c1.update_extends
assert_equal [a, b, c], @c1.extends
end
def test_update_extends_trim
a = RDoc::Extend.new 'D::M', nil
b = RDoc::Extend.new 'D::M', nil
@c1.add_extend a
@c1.add_extend b
@c1.each_extend do |extend| extend.module end # cache extended modules
@c1.update_extends
assert_equal [a], @c1.extends
end
def test_update_extends_with_colons
a = RDoc::Extend.new 'M1', nil
b = RDoc::Extend.new 'M1::M2', nil
c = RDoc::Extend.new 'C', nil
@c1.add_extend a
@c1.add_extend b
@c1.add_extend c
@c1.each_extend do |extend| extend.module end # cache extended modules
@m1_m2.document_self = nil
assert @m1_m2.remove_from_documentation?
assert @store.modules_hash.key? @m1_m2.full_name
refute @store.modules_hash[@m1_m2.full_name].nil?
@store.remove_nodoc @store.modules_hash
refute @store.modules_hash.key? @m1_m2.full_name
@c1.update_extends
assert_equal [a, c], @c1.extends
end
end
|
arnab0073/idea
|
.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/rvm-1.11.3.9/lib/rvm/shell/result.rb
|
module RVM
module Shell
# Represents the output of a shell command.
# This includes the exit status (and the helpful #successful? method)
# as well accessors for the command and stdout / stderr.
class Result
attr_reader :command, :stdout, :stderr, :raw_status
# Creates a new result object with the given details.
def initialize(command, status, stdout, stderr)
@command = command.dup.freeze
@raw_status = status
@environment = (@raw_status ? (@raw_status["environment"] || {}) : {})
@successful = (exit_status == 0)
@stdout = stdout.freeze
@stderr = stderr.freeze
end
# Returns the hash of the environment.
def env
@environment
end
# Whether or not the command had a successful exit status.
def successful?
@successful
end
# Returns a value from the outputs environment.
def [](key)
env[key.to_s]
end
# Returns the exit status for the program
def exit_status
@exit_status ||= (Integer(@raw_status["exit_status"]) rescue 1)
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/psych/test_merge_keys.rb
|
<reponame>arnab0073/idea<filename>.rvm/src/ruby-2.3.0/test/psych/test_merge_keys.rb<gh_stars>10-100
# frozen_string_literal: false
require_relative 'helper'
module Psych
class TestMergeKeys < TestCase
class Product
attr_reader :bar
end
def test_merge_key_with_bare_hash
doc = Psych.load <<-eodoc
map:
<<:
hello: world
eodoc
hash = { "map" => { "hello" => "world" } }
assert_equal hash, doc
end
def test_roundtrip_with_chevron_key
h = {}
v = { 'a' => h, '<<' => h }
assert_cycle v
end
def test_explicit_string
doc = Psych.load <<-eoyml
a: &me { hello: world }
b: { !!str '<<': *me }
eoyml
expected = {
"a" => { "hello" => "world" },
"b" => {
"<<" => { "hello" => "world" }
}
}
assert_equal expected, doc
end
def test_mergekey_with_object
s = <<-eoyml
foo: &foo
bar: 10
product:
!ruby/object:#{Product.name}
<<: *foo
eoyml
hash = Psych.load s
assert_equal({"bar" => 10}, hash["foo"])
product = hash["product"]
assert_equal 10, product.bar
end
def test_merge_nil
yaml = <<-eoyml
defaults: &defaults
development:
<<: *defaults
eoyml
assert_equal({'<<' => nil }, Psych.load(yaml)['development'])
end
def test_merge_array
yaml = <<-eoyml
foo: &hello
- 1
baz:
<<: *hello
eoyml
assert_equal({'<<' => [1]}, Psych.load(yaml)['baz'])
end
def test_merge_is_not_partial
yaml = <<-eoyml
default: &default
hello: world
foo: &hello
- 1
baz:
<<: [*hello, *default]
eoyml
doc = Psych.load yaml
refute doc['baz'].key? 'hello'
assert_equal({'<<' => [[1], {"hello"=>"world"}]}, Psych.load(yaml)['baz'])
end
def test_merge_seq_nil
yaml = <<-eoyml
foo: &hello
baz:
<<: [*hello]
eoyml
assert_equal({'<<' => [nil]}, Psych.load(yaml)['baz'])
end
def test_bad_seq_merge
yaml = <<-eoyml
defaults: &defaults [1, 2, 3]
development:
<<: *defaults
eoyml
assert_equal({'<<' => [1,2,3]}, Psych.load(yaml)['development'])
end
def test_missing_merge_key
yaml = <<-eoyml
bar:
<< : *foo
eoyml
exp = assert_raises(Psych::BadAlias) { Psych.load yaml }
assert_match 'foo', exp.message
end
# [ruby-core:34679]
def test_merge_key
yaml = <<-eoyml
foo: &foo
hello: world
bar:
<< : *foo
baz: boo
eoyml
hash = {
"foo" => { "hello" => "world"},
"bar" => { "hello" => "world", "baz" => "boo" } }
assert_equal hash, Psych.load(yaml)
end
def test_multiple_maps
yaml = <<-eoyaml
---
- &CENTER { x: 1, y: 2 }
- &LEFT { x: 0, y: 2 }
- &BIG { r: 10 }
- &SMALL { r: 1 }
# All the following maps are equal:
- # Merge multiple maps
<< : [ *CENTER, *BIG ]
label: center/big
eoyaml
hash = {
'x' => 1,
'y' => 2,
'r' => 10,
'label' => 'center/big'
}
assert_equal hash, Psych.load(yaml)[4]
end
def test_override
yaml = <<-eoyaml
---
- &CENTER { x: 1, y: 2 }
- &LEFT { x: 0, y: 2 }
- &BIG { r: 10 }
- &SMALL { r: 1 }
# All the following maps are equal:
- # Override
<< : [ *BIG, *LEFT, *SMALL ]
x: 1
label: center/big
eoyaml
hash = {
'x' => 1,
'y' => 2,
'r' => 10,
'label' => 'center/big'
}
assert_equal hash, Psych.load(yaml)[4]
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/-test-/bug-3662/extconf.rb
|
create_makefile("-test-/bug-3662/bug")
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/rdoc/test_rdoc_markup_attributes.rb
|
# frozen_string_literal: false
require 'rdoc/test_case'
class TestRDocMarkupAttributes < RDoc::TestCase
def setup
super
@as = RDoc::Markup::Attributes.new
end
def test_bitmap_for
assert_equal 2, @as.bitmap_for('two')
assert_equal 2, @as.bitmap_for('two')
assert_equal 4, @as.bitmap_for('three')
end
def test_as_string
@as.bitmap_for 'two'
@as.bitmap_for 'three'
assert_equal 'none', @as.as_string(0)
assert_equal '_SPECIAL_', @as.as_string(1)
assert_equal 'two', @as.as_string(2)
assert_equal '_SPECIAL_,two', @as.as_string(3)
end
def test_each_name_of
@as.bitmap_for 'two'
@as.bitmap_for 'three'
assert_equal %w[], @as.each_name_of(0).to_a
assert_equal %w[], @as.each_name_of(1).to_a
assert_equal %w[two], @as.each_name_of(2).to_a
assert_equal %w[three], @as.each_name_of(4).to_a
assert_equal %w[two three], @as.each_name_of(6).to_a
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/lib/rdoc/parser/text.rb
|
<filename>.rvm/src/ruby-2.3.0/lib/rdoc/parser/text.rb<gh_stars>10-100
# frozen_string_literal: false
##
# Indicates this parser is text and doesn't contain code constructs.
#
# Include this module in a RDoc::Parser subclass to make it show up as a file,
# not as part of a class or module.
#--
# This is not named File to avoid overriding ::File
module RDoc::Parser::Text
end
|
arnab0073/idea
|
.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/rvm-1.11.3.9/lib/rvm/environment/sets.rb
|
<reponame>arnab0073/idea
module RVM
class Environment
# Passed either something containing ruby code or
# a path to a ruby file, will attempt to exectute
# it in the current environment.
def ruby(runnable, options = {})
if runnable.respond_to?(:path)
# Call the path
ruby_run runnable.path, options
elsif runnable.respond_to?(:to_str)
runnable = runnable.to_str
File.exist?(runnable) ? ruby_run(runnable, options) : ruby_eval(runnable, options)
elsif runnable.respond_to?(:read)
ruby_run runnable.read
end
end
# Eval the given code within ruby.
def ruby_eval(code, options = {})
perform_set_operation :ruby, "-e", code.to_s, options
end
# Run the given path as a ruby script.
def ruby_run(path, options = {})
perform_set_operation :ruby, path.to_s, options
end
# Execute rake (optionally taking the path to a rake file),
# then change back.
def rake(file = nil, options = {})
if file.nil?
perform_set_operation :rake, options
else
file = File.expand_path(file)
chdir(File.dirname(file)) do
perform_set_operation(:rake, options.merge(:rakefile => file))
end
end
end
# Use the rvm test runner for unit tests.
def tests(options = {})
perform_set_operation :tests, options
end
# Use the rvm spec runner for specs.
def specs(options = {})
perform_set_operation :specs, options
end
# Like Kernel.system, but evaluates it within the environment.
# Also note that it doesn't support redirection etc.
def system(command, *args)
identifier = extract_identifier!(args)
args = [identifier, :exec, command, *args].compact
rvm(*args).successful?
end
# Executes a command, replacing the current shell.
# exec is a bit of an odd ball compared to the others, since
# it has to use the Kernel.exec builtin.
def exec(command, *args)
command = @shell_wrapper.build_cli_call(:exec, [command] + args)
Kernel.exec "bash", "-c", "source '#{env_path}'; #{command}"
end
protected
# Converts the given identifier to a rvm-friendly form.
# Unlike using sets directly, a nil identifier is set
# to mean the current ruby (not all). :all or "all" will
# instead return the a blank identifier / run it against
# all rubies.
def normalize_set_identifier(identifier)
case identifier
when nil, ""
@environment_name
when :all, "all"
nil
when Array
identifier.map { |i| normalize_set_identifier(i) }.uniq.join(",")
else
identifier.to_s
end
end
# From an options hash, extract the environment identifier.
def extract_environment!(options)
values = []
[:environment, :env, :rubies, :ruby].each do |k|
values << options.delete(k)
end
values.compact.first
end
# Shorthand to extra an identifier from args.
# Since we
def extract_identifier!(args)
options = extract_options!(args)
identifier = normalize_set_identifier(extract_environment!(options))
args << options
identifier
end
# Performs a set operation. If the :env or :environment option is given,
# it will return a yaml summary (instead of the stdout / stderr etc via
# a Result object.
def perform_set_operation(*args)
options = extract_options!(args)
environment = extract_environment!(options)
identifier = normalize_set_identifier(environment)
# Uses yaml when we have multiple identifiers.
uses_yaml = !environment.nil?
options.merge!(:yaml => true) if uses_yaml
args.unshift(identifier) unless identifier.nil?
args << options
result = rvm(*args)
uses_yaml ? YAML.load(result.stdout) : result
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/date/lib/date/format.rb
|
<gh_stars>100-1000
# format.rb: Written by <NAME> 1999-2011
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/net-ssh-multi-1.2.0/lib/net/ssh/multi/subsession.rb
|
require 'net/ssh/multi/session_actions'
module Net; module SSH; module Multi
# A trivial class for representing a subset of servers. It is used
# internally for restricting operations to a subset of all defined
# servers.
#
# subsession = session.with(:app)
# subsession.exec("hostname")
class Subsession
include SessionActions
# The master session that spawned this subsession.
attr_reader :master
# The list of servers that this subsession can operate on.
attr_reader :servers
# Create a new subsession of the given +master+ session, that operates
# on the given +server_list+.
def initialize(master, server_list)
@master = master
@servers = server_list.uniq
end
# Works as Array#slice, but returns a new subsession consisting of the
# given slice of servers in this subsession. The new subsession will have
# the same #master session as this subsession does.
#
# s1 = subsession.slice(0)
# s2 = subsession.slice(3, -1)
# s3 = subsession.slice(1..4)
def slice(*args)
Subsession.new(master, Array(servers.slice(*args)))
end
# Returns a new subsession that consists of only the first server in the
# server list of the current subsession. This is just convenience for
# #slice(0):
#
# s1 = subsession.first
def first
slice(0)
end
end
end; end; end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/yajl-ruby-1.2.1/lib/yajl/http_stream.rb
|
puts "DEPRECATION WARNING: Yajl::HttpStream is going to be removed in 2.0"
require 'socket'
require 'yajl'
require 'yajl/version' unless defined? Yajl::VERSION
require 'uri'
module Yajl
# This module is for making HTTP requests to which the response bodies (and possibly requests in the near future)
# are streamed directly into Yajl.
class HttpStream
# This Exception is thrown when an HTTP response isn't in ALLOWED_MIME_TYPES
# and therefore cannot be parsed.
class InvalidContentType < Exception; end
class HttpError < StandardError
attr_reader :message, :headers
def initialize(message, headers)
@message = message
@headers = headers
end
end
# The mime-type we expect the response to be. If it's anything else, we can't parse it
# and an InvalidContentType is raised.
ALLOWED_MIME_TYPES = ["application/json", "text/plain"]
# Makes a basic HTTP GET request to the URI provided
def self.get(uri, opts = {}, &block)
request("GET", uri, opts, &block)
end
# Makes a basic HTTP GET request to the URI provided allowing the user to terminate the connection
def get(uri, opts = {}, &block)
initialize_socket(uri, opts)
HttpStream::get(uri, opts, &block)
rescue IOError => e
raise e unless @intentional_termination
end
# Makes a basic HTTP POST request to the URI provided
def self.post(uri, body, opts = {}, &block)
request("POST", uri, opts.merge({:body => body}), &block)
end
# Makes a basic HTTP POST request to the URI provided allowing the user to terminate the connection
def post(uri, body, opts = {}, &block)
initialize_socket(uri, opts)
HttpStream::post(uri, body, opts, &block)
rescue IOError => e
raise e unless @intentional_termination
end
# Makes a basic HTTP PUT request to the URI provided
def self.put(uri, body, opts = {}, &block)
request("PUT", uri, opts.merge({:body => body}), &block)
end
# Makes a basic HTTP PUT request to the URI provided allowing the user to terminate the connection
def put(uri, body, opts = {}, &block)
initialize_socket(uri, opts)
HttpStream::put(uri, body, opts, &block)
rescue IOError => e
raise e unless @intentional_termination
end
# Makes a basic HTTP DELETE request to the URI provided
def self.delete(uri, opts = {}, &block)
request("DELETE", uri, opts, &block)
end
# Makes a basic HTTP DELETE request to the URI provided allowing the user to terminate the connection
def delete(uri, opts = {}, &block)
initialize_socket(uri, opts)
HttpStream::delete(uri, opts, &block)
rescue IOError => e
raise e unless @intentional_termination
end
# Terminate a running HTTPStream instance
def terminate
@intentional_termination = true
@socket.close
end
protected
def self.request(method, uri, opts = {}, &block)
if uri.is_a?(String)
uri = URI.parse(uri)
end
default_headers = {
"User-Agent" => opts["User-Agent"] || "Yajl::HttpStream #{Yajl::VERSION}",
"Accept" => "*/*",
"Accept-Charset" => "utf-8"
}
if method == "POST" || method == "PUT"
default_headers["Content-Type"] = opts["Content-Type"] || "application/x-www-form-urlencoded"
body = opts.delete(:body)
if body.is_a?(Hash)
body = body.keys.collect {|param| "#{URI.escape(param.to_s)}=#{URI.escape(body[param].to_s)}"}.join('&')
end
default_headers["Content-Length"] = body.length
end
unless uri.userinfo.nil?
default_headers["Authorization"] = "Basic #{[uri.userinfo].pack('m').strip!}\r\n"
end
encodings = []
encodings << "bzip2" if defined?(Yajl::Bzip2)
encodings << "gzip" if defined?(Yajl::Gzip)
encodings << "deflate" if defined?(Yajl::Deflate)
if encodings.any?
default_headers["Accept-Encoding"] = "#{encodings.join(',')}\r\n"
end
headers = default_headers.merge(opts[:headers] || {})
socket = opts.delete(:socket) || TCPSocket.new(uri.host, uri.port)
request = "#{method} #{uri.path}#{uri.query ? "?"+uri.query : nil} HTTP/1.1\r\n"
request << "Host: #{uri.host}\r\n"
headers.each do |k, v|
request << "#{k}: #{v}\r\n"
end
request << "\r\n"
if method == "POST" || method == "PUT"
request << body
end
socket.write(request)
response_head = {}
response_head[:headers] = {}
socket.each_line do |line|
if line == "\r\n" # end of the headers
break
else
header = line.split(": ")
if header.size == 1
header = header[0].split(" ")
response_head[:version] = header[0]
response_head[:code] = header[1].to_i
response_head[:msg] = header[2]
# this is the response code line
else
response_head[:headers][header[0]] = header[1].strip
end
end
end
if (response_head[:code] != 200)
raise HttpError.new("Code 200 expected got #{response_head[:code]}", response_head[:headers])
end
parser = Yajl::Parser.new(opts)
parser.on_parse_complete = block if block_given?
if response_head[:headers]["Transfer-Encoding"] == 'chunked'
if block_given?
chunkLeft = 0
while !socket.eof? && (line = socket.gets)
break if line.match /^0.*?\r\n/
next if line == "\r\n"
size = line.hex
json = socket.read(size)
next if json.nil?
chunkLeft = size-json.size
if chunkLeft == 0
parser << json
else
# received only part of the chunk, grab the rest
parser << socket.read(chunkLeft)
end
end
else
raise Exception, "Chunked responses detected, but no block given to handle the chunks."
end
else
content_type = response_head[:headers]["Content-Type"].split(';')
content_type = content_type.first
if ALLOWED_MIME_TYPES.include?(content_type)
case response_head[:headers]["Content-Encoding"]
when "gzip"
return Yajl::Gzip::StreamReader.parse(socket, opts, &block)
when "deflate"
return Yajl::Deflate::StreamReader.parse(socket, opts.merge({:deflate_options => -Zlib::MAX_WBITS}), &block)
when "bzip2"
return Yajl::Bzip2::StreamReader.parse(socket, opts, &block)
else
return parser.parse(socket)
end
else
raise InvalidContentType, "The response MIME type #{content_type}"
end
end
ensure
socket.close if !socket.nil? and !socket.closed?
end
private
# Initialize socket and add it to the opts
def initialize_socket(uri, opts = {})
return if opts[:socket]
@socket = TCPSocket.new(uri.host, uri.port)
opts.merge!({:socket => @socket})
@intentional_termination = false
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/net-ssh-2.6.8/test/authentication/methods/test_password.rb
|
<filename>.rvm/gems/ruby-2.3.0/gems/net-ssh-2.6.8/test/authentication/methods/test_password.rb
require 'common'
require 'net/ssh/authentication/methods/password'
require 'authentication/methods/common'
module Authentication; module Methods
class TestPassword < Test::Unit::TestCase
include Common
def test_authenticate_should_raise_if_password_disallowed
transport.expect do |t,packet|
assert_equal USERAUTH_REQUEST, packet.type
assert_equal "jamis", packet.read_string
assert_equal "ssh-connection", packet.read_string
assert_equal "password", packet.read_string
assert_equal false, packet.read_bool
assert_equal "the-password", packet.read_string
t.return(USERAUTH_FAILURE, :string, "publickey")
end
assert_raises Net::SSH::Authentication::DisallowedMethod do
subject.authenticate("ssh-connection", "jamis", "the-password")
end
end
def test_authenticate_when_password_is_acceptible_should_return_true
transport.expect do |t,packet|
assert_equal USERAUTH_REQUEST, packet.type
t.return(USERAUTH_SUCCESS)
end
assert subject.authenticate("ssh-connection", "jamis", "the-password")
end
def test_authenticate_should_return_false_if_password_change_request_is_received
transport.expect do |t,packet|
assert_equal USERAUTH_REQUEST, packet.type
t.return(USERAUTH_PASSWD_CHANGEREQ, :string, "Change your password:", :string, "")
end
assert !subject.authenticate("ssh-connection", "jamis", "the-password")
end
private
def subject(options={})
@subject ||= Net::SSH::Authentication::Methods::Password.new(session(options), options)
end
end
end; end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/test/setup.rb
|
<reponame>arnab0073/idea<gh_stars>1-10
# Equivalent to a header guard in C/C++
# Used to prevent the class/module from being loaded more than once
unless defined? LOGGING_TEST_SETUP
LOGGING_TEST_SETUP = true
require "rubygems"
require "test/unit"
if Test::Unit::TestCase.respond_to? :test_order=
Test::Unit::TestCase.test_order = :random
end
require File.expand_path("../../lib/logging", __FILE__)
module TestLogging
module LoggingTestCase
TMP = 'tmp'
def setup
super
Logging.reset
FileUtils.rm_rf TMP
FileUtils.mkdir TMP
end
def teardown
super
FileUtils.rm_rf TMP
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/rinda/test_rinda.rb
|
<reponame>arnab0073/idea
# frozen_string_literal: false
require 'test/unit'
require 'drb/drb'
require 'drb/eq'
require 'rinda/ring'
require 'rinda/tuplespace'
require 'timeout'
require 'singleton'
module Rinda
class MockClock
include Singleton
class MyTS < Rinda::TupleSpace
def keeper_thread
nil
end
end
def initialize
@now = 2
@reso = 1
@ts = MyTS.new
@ts.write([2, :now])
@inf = 2**31 - 1
end
def now
@now.to_f
end
def at(n)
n
end
def _forward(n=nil)
now ,= @ts.take([nil, :now])
@now = now + n
@ts.write([@now, :now])
end
def forward(n)
while n > 0
_forward(@reso)
n -= @reso
Thread.pass
end
end
def rewind
@ts.take([nil, :now])
@ts.write([@inf, :now])
@ts.take([nil, :now])
@now = 2
@ts.write([2, :now])
end
def sleep(n=nil)
now ,= @ts.read([nil, :now])
@ts.read([(now + n)..@inf, :now])
0
end
end
module Time
def sleep(n)
@m.sleep(n)
end
module_function :sleep
def at(n)
n
end
module_function :at
def now
defined?(@m) && @m ? @m.now : 2
end
module_function :now
def rewind
@m.rewind
end
module_function :rewind
def forward(n)
@m.forward(n)
end
module_function :forward
@m = MockClock.instance
end
class TupleSpace
def sleep(n)
Kernel.sleep(n * 0.01)
end
end
module TupleSpaceTestModule
def sleep(n)
if Thread.current == Thread.main
Time.forward(n)
else
Time.sleep(n)
end
end
def thread_join(th)
while th.alive?
Kernel.sleep(0.1)
sleep(1)
end
th.value
end
def test_00_tuple
tuple = Rinda::TupleEntry.new([1,2,3])
assert(!tuple.canceled?)
assert(!tuple.expired?)
assert(tuple.alive?)
end
def test_00_template
tmpl = Rinda::Template.new([1,2,3])
assert_equal(3, tmpl.size)
assert_equal(3, tmpl[2])
assert(tmpl.match([1,2,3]))
assert(!tmpl.match([1,nil,3]))
tmpl = Rinda::Template.new([/^rinda/i, nil, :hello])
assert_equal(3, tmpl.size)
assert(tmpl.match(['Rinda', 2, :hello]))
assert(!tmpl.match(['Rinda', 2, Symbol]))
assert(!tmpl.match([1, 2, :hello]))
assert(tmpl.match([/^rinda/i, 2, :hello]))
tmpl = Rinda::Template.new([Symbol])
assert_equal(1, tmpl.size)
assert(tmpl.match([:hello]))
assert(tmpl.match([Symbol]))
assert(!tmpl.match(['Symbol']))
tmpl = Rinda::Template.new({"message"=>String, "name"=>String})
assert_equal(2, tmpl.size)
assert(tmpl.match({"message"=>"Hello", "name"=>"Foo"}))
assert(!tmpl.match({"message"=>"Hello", "name"=>"Foo", "1"=>2}))
assert(!tmpl.match({"message"=>"Hi", "name"=>"Foo", "age"=>1}))
assert(!tmpl.match({"message"=>"Hello", "no_name"=>"Foo"}))
assert_raise(Rinda::InvalidHashTupleKey) do
Rinda::Template.new({:message=>String, "name"=>String})
end
tmpl = Rinda::Template.new({"name"=>String})
assert_equal(1, tmpl.size)
assert(tmpl.match({"name"=>"Foo"}))
assert(!tmpl.match({"message"=>"Hello", "name"=>"Foo"}))
assert(!tmpl.match({"message"=>:symbol, "name"=>"Foo", "1"=>2}))
assert(!tmpl.match({"message"=>"Hi", "name"=>"Foo", "age"=>1}))
assert(!tmpl.match({"message"=>"Hello", "no_name"=>"Foo"}))
tmpl = Rinda::Template.new({"message"=>String, "name"=>String})
assert_equal(2, tmpl.size)
assert(tmpl.match({"message"=>"Hello", "name"=>"Foo"}))
assert(!tmpl.match({"message"=>"Hello", "name"=>"Foo", "1"=>2}))
assert(!tmpl.match({"message"=>"Hi", "name"=>"Foo", "age"=>1}))
assert(!tmpl.match({"message"=>"Hello", "no_name"=>"Foo"}))
tmpl = Rinda::Template.new({"message"=>String})
assert_equal(1, tmpl.size)
assert(tmpl.match({"message"=>"Hello"}))
assert(!tmpl.match({"message"=>"Hello", "name"=>"Foo"}))
assert(!tmpl.match({"message"=>"Hello", "name"=>"Foo", "1"=>2}))
assert(!tmpl.match({"message"=>"Hi", "name"=>"Foo", "age"=>1}))
assert(!tmpl.match({"message"=>"Hello", "no_name"=>"Foo"}))
tmpl = Rinda::Template.new({"message"=>String, "name"=>nil})
assert_equal(2, tmpl.size)
assert(tmpl.match({"message"=>"Hello", "name"=>"Foo"}))
assert(!tmpl.match({"message"=>"Hello", "name"=>"Foo", "1"=>2}))
assert(!tmpl.match({"message"=>"Hi", "name"=>"Foo", "age"=>1}))
assert(!tmpl.match({"message"=>"Hello", "no_name"=>"Foo"}))
assert_raise(Rinda::InvalidHashTupleKey) do
@ts.write({:message=>String, "name"=>String})
end
@ts.write([1, 2, 3])
assert_equal([1, 2, 3], @ts.take([1, 2, 3]))
@ts.write({'1'=>1, '2'=>2, '3'=>3})
assert_equal({'1'=>1, '2'=>2, '3'=>3}, @ts.take({'1'=>1, '2'=>2, '3'=>3}))
entry = @ts.write(['1'=>1, '2'=>2, '3'=>3])
assert_raise(Rinda::RequestExpiredError) do
assert_equal({'1'=>1, '2'=>2, '3'=>3}, @ts.read({'1'=>1}, 0))
end
entry.cancel
end
def test_00_DRbObject
ro = DRbObject.new(nil, "druby://host:1234")
tmpl = Rinda::DRbObjectTemplate.new
assert(tmpl === ro)
tmpl = Rinda::DRbObjectTemplate.new("druby://host:1234")
assert(tmpl === ro)
tmpl = Rinda::DRbObjectTemplate.new("druby://host:12345")
assert(!(tmpl === ro))
tmpl = Rinda::DRbObjectTemplate.new(/^druby:\/\/host:/)
assert(tmpl === ro)
ro = DRbObject.new_with(12345, 1234)
assert(!(tmpl === ro))
ro = DRbObject.new_with("druby://foo:12345", 1234)
assert(!(tmpl === ro))
tmpl = Rinda::DRbObjectTemplate.new(/^druby:\/\/(foo|bar):/)
assert(tmpl === ro)
ro = DRbObject.new_with("druby://bar:12345", 1234)
assert(tmpl === ro)
ro = DRbObject.new_with("druby://baz:12345", 1234)
assert(!(tmpl === ro))
end
def test_inp_rdp
assert_raise(Rinda::RequestExpiredError) do
@ts.take([:empty], 0)
end
assert_raise(Rinda::RequestExpiredError) do
@ts.read([:empty], 0)
end
end
def test_ruby_talk_264062
th = Thread.new { @ts.take([:empty], 1) }
sleep(10)
assert_raise(Rinda::RequestExpiredError) do
thread_join(th)
end
th = Thread.new { @ts.read([:empty], 1) }
sleep(10)
assert_raise(Rinda::RequestExpiredError) do
thread_join(th)
end
end
def test_symbol_tuple
@ts.write([:symbol, :symbol])
@ts.write(['string', :string])
assert_equal([[:symbol, :symbol]], @ts.read_all([:symbol, nil]))
assert_equal([[:symbol, :symbol]], @ts.read_all([Symbol, nil]))
assert_equal([], @ts.read_all([:nil, nil]))
end
def test_core_01
5.times do
@ts.write([:req, 2])
end
assert_equal([[:req, 2], [:req, 2], [:req, 2], [:req, 2], [:req, 2]],
@ts.read_all([nil, nil]))
taker = Thread.new(5) do |count|
s = 0
count.times do
tuple = @ts.take([:req, Integer])
assert_equal(2, tuple[1])
s += tuple[1]
end
@ts.write([:ans, s])
s
end
assert_equal(10, thread_join(taker))
assert_equal([:ans, 10], @ts.take([:ans, 10]))
assert_equal([], @ts.read_all([nil, nil]))
end
def test_core_02
taker = Thread.new(5) do |count|
s = 0
count.times do
tuple = @ts.take([:req, Integer])
assert_equal(2, tuple[1])
s += tuple[1]
end
@ts.write([:ans, s])
s
end
5.times do
@ts.write([:req, 2])
end
assert_equal(10, thread_join(taker))
assert_equal([:ans, 10], @ts.take([:ans, 10]))
assert_equal([], @ts.read_all([nil, nil]))
end
def test_core_03_notify
notify1 = @ts.notify(nil, [:req, Integer])
notify2 = @ts.notify(nil, {"message"=>String, "name"=>String})
5.times do
@ts.write([:req, 2])
end
5.times do
tuple = @ts.take([:req, Integer])
assert_equal(2, tuple[1])
end
5.times do
assert_equal(['write', [:req, 2]], notify1.pop)
end
5.times do
assert_equal(['take', [:req, 2]], notify1.pop)
end
@ts.write({"message"=>"first", "name"=>"3"})
@ts.write({"message"=>"second", "name"=>"1"})
@ts.write({"message"=>"third", "name"=>"0"})
@ts.take({"message"=>"third", "name"=>"0"})
@ts.take({"message"=>"first", "name"=>"3"})
assert_equal(["write", {"message"=>"first", "name"=>"3"}], notify2.pop)
assert_equal(["write", {"message"=>"second", "name"=>"1"}], notify2.pop)
assert_equal(["write", {"message"=>"third", "name"=>"0"}], notify2.pop)
assert_equal(["take", {"message"=>"third", "name"=>"0"}], notify2.pop)
assert_equal(["take", {"message"=>"first", "name"=>"3"}], notify2.pop)
end
def test_cancel_01
entry = @ts.write([:removeme, 1])
assert_equal([[:removeme, 1]], @ts.read_all([nil, nil]))
entry.cancel
assert_equal([], @ts.read_all([nil, nil]))
template = nil
taker = Thread.new do
@ts.take([:take, nil], 10) do |t|
template = t
Thread.new do
template.cancel
end
end
end
sleep(2)
assert_raise(Rinda::RequestCanceledError) do
assert_nil(thread_join(taker))
end
assert(template.canceled?)
@ts.write([:take, 1])
assert_equal([[:take, 1]], @ts.read_all([nil, nil]))
end
def test_cancel_02
entry = @ts.write([:removeme, 1])
assert_equal([[:removeme, 1]], @ts.read_all([nil, nil]))
entry.cancel
assert_equal([], @ts.read_all([nil, nil]))
template = nil
reader = Thread.new do
@ts.read([:take, nil], 10) do |t|
template = t
Thread.new do
template.cancel
end
end
end
sleep(2)
assert_raise(Rinda::RequestCanceledError) do
assert_nil(thread_join(reader))
end
assert(template.canceled?)
@ts.write([:take, 1])
assert_equal([[:take, 1]], @ts.read_all([nil, nil]))
end
class SimpleRenewer
def initialize(sec, n = 1)
@sec = sec
@n = n
end
def renew
return -1 if @n <= 0
@n -= 1
return @sec
end
end
def test_00_renewer
tuple = Rinda::TupleEntry.new([1,2,3], true)
assert(!tuple.canceled?)
assert(tuple.expired?)
assert(!tuple.alive?)
tuple = Rinda::TupleEntry.new([1,2,3], 1)
assert(!tuple.canceled?)
assert(!tuple.expired?)
assert(tuple.alive?)
sleep(2)
assert(tuple.expired?)
assert(!tuple.alive?)
@renewer = SimpleRenewer.new(1,2)
tuple = Rinda::TupleEntry.new([1,2,3], @renewer)
assert(!tuple.canceled?)
assert(!tuple.expired?)
assert(tuple.alive?)
sleep(1)
assert(!tuple.canceled?)
assert(!tuple.expired?)
assert(tuple.alive?)
sleep(2)
assert(tuple.expired?)
assert(!tuple.alive?)
end
end
class TupleSpaceTest < Test::Unit::TestCase
include TupleSpaceTestModule
def setup
ThreadGroup.new.add(Thread.current)
@ts = Rinda::TupleSpace.new(1)
end
def teardown
# implementation-dependent
@ts.instance_eval{
if th = @keeper
th.kill
th.join
end
}
end
end
class TupleSpaceProxyTest < Test::Unit::TestCase
include TupleSpaceTestModule
def setup
ThreadGroup.new.add(Thread.current)
@ts_base = Rinda::TupleSpace.new(1)
@ts = Rinda::TupleSpaceProxy.new(@ts_base)
end
def teardown
# implementation-dependent
@ts_base.instance_eval{
if th = @keeper
th.kill
th.join
end
}
end
def test_remote_array_and_hash
# Don't remove ary/hsh local variables.
# These are necessary to protect objects from GC.
ary = [1, 2, 3]
@ts.write(DRbObject.new(ary))
assert_equal([1, 2, 3], @ts.take([1, 2, 3], 0))
hsh = {'head' => 1, 'tail' => 2}
@ts.write(DRbObject.new(hsh))
assert_equal({'head' => 1, 'tail' => 2},
@ts.take({'head' => 1, 'tail' => 2}, 0))
end
def test_take_bug_8215
service = DRb.start_service("druby://localhost:0", @ts_base)
uri = service.uri
args = [EnvUtil.rubybin, *%W[-rdrb/drb -rdrb/eq -rrinda/ring -rrinda/tuplespace -e]]
take = spawn(*args, <<-'end;', uri)
uri = ARGV[0]
DRb.start_service("druby://localhost:0")
ro = DRbObject.new_with_uri(uri)
ts = Rinda::TupleSpaceProxy.new(ro)
th = Thread.new do
ts.take([:test_take, nil])
end
Kernel.sleep(0.1)
th.raise(Interrupt) # causes loss of the taken tuple
ts.write([:barrier, :continue])
Kernel.sleep
end;
@ts_base.take([:barrier, :continue])
write = spawn(*args, <<-'end;', uri)
uri = ARGV[0]
DRb.start_service("druby://localhost:0")
ro = DRbObject.new_with_uri(uri)
ts = Rinda::TupleSpaceProxy.new(ro)
ts.write([:test_take, 42])
end;
status = Process.wait(write)
assert_equal([[:test_take, 42]], @ts_base.read_all([:test_take, nil]),
'[bug:8215] tuple lost')
ensure
service.stop_service if service
signal = /mswin|mingw/ =~ RUBY_PLATFORM ? "KILL" : "TERM"
Process.kill(signal, write) if write && status.nil?
Process.kill(signal, take) if take
Process.wait(write) if write && status.nil?
Process.wait(take) if take
end
@server = DRb.primary_server || DRb.start_service("druby://localhost:0")
end
module RingIPv6
def prepare_ipv6(r)
begin
Socket.getifaddrs.each do |ifaddr|
next unless ifaddr.addr
next unless ifaddr.addr.ipv6_linklocal?
next if ifaddr.name[0, 2] == "lo"
r.multicast_interface = ifaddr.ifindex
return ifaddr
end
rescue NotImplementedError
# ifindex() function may not be implemented on Windows.
return if
Socket.ip_address_list.any? { |addrinfo| addrinfo.ipv6? && !addrinfo.ipv6_loopback? }
end
skip 'IPv6 not available'
end
end
class TestRingServer < Test::Unit::TestCase
def setup
@port = Rinda::Ring_PORT
@ts = Rinda::TupleSpace.new
@rs = Rinda::RingServer.new(@ts, [], @port)
end
def teardown
# implementation-dependent
@ts.instance_eval{
if th = @keeper
th.kill
th.join
end
}
@rs.shutdown
end
def test_do_reply
with_timeout(10) {_test_do_reply}
end
def _test_do_reply
called = nil
callback = proc { |ts|
called = ts
}
callback = DRb::DRbObject.new callback
@ts.write [:lookup_ring, callback]
@rs.do_reply
wait_for(10) {called}
assert_same @ts, called
end
def test_do_reply_local
with_timeout(10) {_test_do_reply_local}
end
def _test_do_reply_local
called = nil
callback = proc { |ts|
called = ts
}
@ts.write [:lookup_ring, callback]
@rs.do_reply
wait_for(10) {called}
assert_same @ts, called
end
def test_make_socket_unicast
v4 = @rs.make_socket('127.0.0.1')
assert_equal('127.0.0.1', v4.local_address.ip_address)
assert_equal(@port, v4.local_address.ip_port)
end
def test_make_socket_ipv4_multicast
v4mc = @rs.make_socket('172.16.58.3')
if Socket.const_defined?(:SO_REUSEPORT) then
assert(v4mc.getsockopt(:SOCKET, :SO_REUSEPORT).bool)
else
assert(v4mc.getsockopt(:SOCKET, :SO_REUSEADDR).bool)
end
assert_equal('0.0.0.0', v4mc.local_address.ip_address)
assert_equal(@port, v4mc.local_address.ip_port)
end
def test_make_socket_ipv6_multicast
skip 'IPv6 not available' unless
Socket.ip_address_list.any? { |addrinfo| addrinfo.ipv6? && !addrinfo.ipv6_loopback? }
begin
v6mc = @rs.make_socket('fc00:db20:35b:7399::5')
rescue Errno::EADDRNOTAVAIL
return # IPv6 address for multicast not available
end
if Socket.const_defined?(:SO_REUSEPORT) then
assert v6mc.getsockopt(:SOCKET, :SO_REUSEPORT).bool
else
assert v6mc.getsockopt(:SOCKET, :SO_REUSEADDR).bool
end
assert_equal('::1', v6mc.local_address.ip_address)
assert_equal(@port, v6mc.local_address.ip_port)
end
def test_ring_server_ipv4_multicast
@rs.shutdown
@rs = Rinda::RingServer.new(@ts, [['172.16.58.3', '0.0.0.0']], @port)
v4mc = @rs.instance_variable_get('@sockets').first
if Socket.const_defined?(:SO_REUSEPORT) then
assert(v4mc.getsockopt(:SOCKET, :SO_REUSEPORT).bool)
else
assert(v4mc.getsockopt(:SOCKET, :SO_REUSEADDR).bool)
end
assert_equal('0.0.0.0', v4mc.local_address.ip_address)
assert_equal(@port, v4mc.local_address.ip_port)
end
def test_ring_server_ipv6_multicast
skip 'IPv6 not available' unless
Socket.ip_address_list.any? { |addrinfo| addrinfo.ipv6? && !addrinfo.ipv6_loopback? }
@rs.shutdown
begin
@rs = Rinda::RingServer.new(@ts, [['fc00:db20:35b:7399::5', '::1', 0]], @port)
rescue Errno::EADDRNOTAVAIL
return # IPv6 address for multicast not available
end
v6mc = @rs.instance_variable_get('@sockets').first
if Socket.const_defined?(:SO_REUSEPORT) then
assert v6mc.getsockopt(:SOCKET, :SO_REUSEPORT).bool
else
assert v6mc.getsockopt(:SOCKET, :SO_REUSEADDR).bool
end
assert_equal('::1', v6mc.local_address.ip_address)
assert_equal(@port, v6mc.local_address.ip_port)
end
def test_shutdown
@rs.shutdown
assert_nil(@rs.do_reply, 'otherwise should hang forever')
end
private
def with_timeout(n)
aoe = Thread.abort_on_exception
Thread.abort_on_exception = true
tl0 = Thread.list
tl = nil
th = Thread.new(Thread.current) do |mth|
sleep n
(tl = Thread.list - tl0).each {|t|t.raise(Timeout::Error)}
mth.raise(Timeout::Error)
end
tl0 << th
rescue Timeout::Error => e
if tl
bt = e.backtrace
tl.each do |t|
begin
t.value
rescue Timeout::Error => e
bt.unshift("")
bt[0, 0] = e.backtrace
end
end
end
raise Timeout::Error, "timeout", bt
ensure
if th
th.kill
th.join
end
Thread.abort_on_exception = aoe
end
def wait_for(n)
t = n + Process.clock_gettime(Process::CLOCK_MONOTONIC, :second)
until yield
if t < Process.clock_gettime(Process::CLOCK_MONOTONIC, :second)
flunk "timeout during waiting call"
end
sleep 0.1
end
end
end
class TestRingFinger < Test::Unit::TestCase
include RingIPv6
def setup
@rf = Rinda::RingFinger.new
end
def test_make_socket_unicast
v4 = @rf.make_socket('127.0.0.1')
assert(v4.getsockopt(:SOL_SOCKET, :SO_BROADCAST).bool)
ensure
v4.close if v4
end
def test_make_socket_ipv4_multicast
v4mc = @rf.make_socket('172.16.58.3')
assert_equal(1, v4mc.getsockopt(:IPPROTO_IP, :IP_MULTICAST_LOOP).ipv4_multicast_loop)
assert_equal(1, v4mc.getsockopt(:IPPROTO_IP, :IP_MULTICAST_TTL).ipv4_multicast_ttl)
ensure
v4mc.close if v4mc
end
def test_make_socket_ipv6_multicast
ifaddr = prepare_ipv6(@rf)
begin
v6mc = @rf.make_socket("fffc00:db20:35b:7399::5")
rescue Errno::EINVAL
# somehow Debian 6.0.7 needs ifname
v6mc = @rf.make_socket("fffc00:db20:35b:7399::5%#{ifaddr.name}")
end
assert_equal(1, v6mc.getsockopt(:IPPROTO_IPV6, :IPV6_MULTICAST_LOOP).int)
assert_equal(1, v6mc.getsockopt(:IPPROTO_IPV6, :IPV6_MULTICAST_HOPS).int)
ensure
v6mc.close if v6mc
end
def test_make_socket_ipv4_multicast_hops
@rf.multicast_hops = 2
v4mc = @rf.make_socket('2192.168.3.11')
assert_equal(2, v4mc.getsockopt(:IPPROTO_IP, :IP_MULTICAST_TTL).ipv4_multicast_ttl)
ensure
v4mc.close if v4mc
end
def test_make_socket_ipv6_multicast_hops
ifaddr = prepare_ipv6(@rf)
@rf.multicast_hops = 2
begin
v6mc = @rf.make_socket("fc00:db20:35b:7399::5")
rescue Errno::EINVAL
# somehow Debian 6.0.7 needs ifname
v6mc = @rf.make_socket("fffc00:db20:35b:7399::5%#{ifaddr.name}")
end
assert_equal(2, v6mc.getsockopt(:IPPROTO_IPV6, :IPV6_MULTICAST_HOPS).int)
ensure
v6mc.close if v6mc
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/iwidgets/promptdialog.rb
|
<reponame>arnab0073/idea<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/iwidgets/promptdialog.rb
#
# tkextlib/iwidgets/promptdialog.rb
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tkextlib/iwidgets.rb'
module Tk
module Iwidgets
class Promptdialog < Tk::Iwidgets::Dialog
end
end
end
class Tk::Iwidgets::Promptdialog
TkCommandNames = ['::iwidgets::promptdialog'.freeze].freeze
WidgetClassName = 'Promptdialog'.freeze
WidgetClassNames[WidgetClassName] ||= self
# index method is not available, because it shows index of the entry field
def default(name)
tk_call(@path, 'default', tagid(name))
self
end
def hide(name)
tk_call(@path, 'hide', tagid(name))
self
end
def invoke(name=nil)
if name
tk_call(@path, 'invoke', tagid(name))
else
tk_call(@path, 'invoke')
end
self
end
def show(name)
tk_call(@path, 'show', tagid(name))
self
end
# based on Tk::Iwidgets::Entryfield
def clear
tk_call(@path, 'clear')
self
end
def delete(first, last=None)
tk_send_without_enc('delete', first, last)
self
end
def value
_fromUTF8(tk_send_without_enc('get'))
end
def value= (val)
tk_send_without_enc('delete', 0, 'end')
tk_send_without_enc('insert', 0, _get_eval_enc_str(val))
val
end
alias get value
alias set value=
def cursor=(index)
tk_send_without_enc('icursor', index)
#self
index
end
alias icursor cursor=
def index(idx)
number(tk_send_without_enc('index', idx))
end
def insert(pos,text)
tk_send_without_enc('insert', pos, _get_eval_enc_str(text))
self
end
def mark(pos)
tk_send_without_enc('scan', 'mark', pos)
self
end
def dragto(pos)
tk_send_without_enc('scan', 'dragto', pos)
self
end
def selection_adjust(index)
tk_send_without_enc('selection', 'adjust', index)
self
end
def selection_clear
tk_send_without_enc('selection', 'clear')
self
end
def selection_from(index)
tk_send_without_enc('selection', 'from', index)
self
end
def selection_present()
bool(tk_send_without_enc('selection', 'present'))
end
def selection_range(s, e)
tk_send_without_enc('selection', 'range', s, e)
self
end
def selection_to(index)
tk_send_without_enc('selection', 'to', index)
self
end
def xview(*index)
if index.size == 0
list(tk_send_without_enc('xview'))
else
tk_send_without_enc('xview', *index)
self
end
end
def xview_moveto(*index)
xview('moveto', *index)
end
def xview_scroll(*index)
xview('scroll', *index)
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/coderay-1.1.1/lib/coderay/encoders/encoder.rb
|
module CodeRay
module Encoders
# = Encoder
#
# The Encoder base class. Together with Scanner and
# Tokens, it forms the highlighting triad.
#
# Encoder instances take a Tokens object and do something with it.
#
# The most common Encoder is surely the HTML encoder
# (CodeRay::Encoders::HTML). It highlights the code in a colorful
# html page.
# If you want the highlighted code in a div or a span instead,
# use its subclasses Div and Span.
class Encoder
extend Plugin
plugin_host Encoders
class << self
# If FILE_EXTENSION isn't defined, this method returns the
# downcase class name instead.
def const_missing sym
if sym == :FILE_EXTENSION
(defined?(@plugin_id) && @plugin_id || name[/\w+$/].downcase).to_s
else
super
end
end
# The default file extension for output file of this encoder class.
def file_extension
self::FILE_EXTENSION
end
end
# Subclasses are to store their default options in this constant.
DEFAULT_OPTIONS = { }
# The options you gave the Encoder at creating.
attr_accessor :options, :scanner
# Creates a new Encoder.
# +options+ is saved and used for all encode operations, as long
# as you don't overwrite it there by passing additional options.
#
# Encoder objects provide three encode methods:
# - encode simply takes a +code+ string and a +lang+
# - encode_tokens expects a +tokens+ object instead
#
# Each method has an optional +options+ parameter. These are
# added to the options you passed at creation.
def initialize options = {}
@options = self.class::DEFAULT_OPTIONS.merge options
@@CODERAY_TOKEN_INTERFACE_DEPRECATION_WARNING_GIVEN = false
end
# Encode a Tokens object.
def encode_tokens tokens, options = {}
options = @options.merge options
@scanner = tokens.scanner if tokens.respond_to? :scanner
setup options
compile tokens, options
finish options
end
# Encode the given +code+ using the Scanner for +lang+.
def encode code, lang, options = {}
options = @options.merge options
@scanner = Scanners[lang].new code, CodeRay.get_scanner_options(options).update(:tokens => self)
setup options
@scanner.tokenize
finish options
end
# You can use highlight instead of encode, if that seems
# more clear to you.
alias highlight encode
# The default file extension for this encoder.
def file_extension
self.class.file_extension
end
def << token
unless @@CODERAY_TOKEN_INTERFACE_DEPRECATION_WARNING_GIVEN
warn 'Using old Tokens#<< interface.'
@@CODERAY_TOKEN_INTERFACE_DEPRECATION_WARNING_GIVEN = true
end
self.token(*token)
end
# Called with +content+ and +kind+ of the currently scanned token.
# For simple scanners, it's enougth to implement this method.
#
# By default, it calls text_token, begin_group, end_group, begin_line,
# or end_line, depending on the +content+.
def token content, kind
case content
when String
text_token content, kind
when :begin_group
begin_group kind
when :end_group
end_group kind
when :begin_line
begin_line kind
when :end_line
end_line kind
else
raise ArgumentError, 'Unknown token content type: %p, kind = %p' % [content, kind]
end
end
# Called for each text token ([text, kind]), where text is a String.
def text_token text, kind
@out << text
end
# Starts a token group with the given +kind+.
def begin_group kind
end
# Ends a token group with the given +kind+.
def end_group kind
end
# Starts a new line token group with the given +kind+.
def begin_line kind
end
# Ends a new line token group with the given +kind+.
def end_line kind
end
protected
# Called with merged options before encoding starts.
# Sets @out to an empty string.
#
# See the HTML Encoder for an example of option caching.
def setup options
@out = get_output(options)
end
def get_output options
options[:out] || ''
end
# Append data.to_s to the output. Returns the argument.
def output data
@out << data.to_s
data
end
# Called with merged options after encoding starts.
# The return value is the result of encoding, typically @out.
def finish options
@out
end
# Do the encoding.
#
# The already created +tokens+ object must be used; it must be a
# Tokens object.
def compile tokens, options = {}
content = nil
for item in tokens
if item.is_a? Array
raise ArgumentError, 'Two-element array tokens are no longer supported.'
end
if content
token content, item
content = nil
else
content = item
end
end
raise 'odd number list for Tokens' if content
end
alias tokens compile
public :tokens
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/gems/did_you_mean-1.0.0/test/spell_checker_test.rb
|
require 'test_helper'
class SpellCheckerTest < Minitest::Test
SpellChecker = Struct.new(:input, :words) do
include DidYouMean::SpellCheckable
def candidates
{ input => words }
end
end
def test_spell_checker_corrects_mistypes
assert_spell 'foo', input: 'doo', dictionary: ['foo', 'fork']
assert_spell 'email', input: 'meail', dictionary: ['email', 'fail', 'eval']
assert_spell 'fail', input: 'fial', dictionary: ['email', 'fail', 'eval']
assert_spell 'fail', input: 'afil', dictionary: ['email', 'fail', 'eval']
assert_spell 'eval', input: 'eavl', dictionary: ['email', 'fail', 'eval']
assert_spell 'eval', input: 'veal', dictionary: ['email', 'fail', 'eval']
assert_spell 'sub!', input: 'suv!', dictionary: ['sub', 'gsub', 'sub!']
assert_spell 'sub', input: 'suv', dictionary: ['sub', 'gsub', 'sub!']
assert_spell %w(gsub! gsub), input: 'gsuv!', dictionary: %w(sub gsub gsub!)
assert_spell %w(sub! sub gsub!), input: 'ssub!', dictionary: %w(sub sub! gsub gsub!)
assert_spell %i(read rand), input: 'raed', dictionary: File.methods + File.private_methods
group_methods = %w(groups group_url groups_url group_path)
assert_spell 'groups', input: 'group', dictionary: group_methods
group_classes = %w(
GroupMembership
GroupMembershipPolicy
GroupMembershipDecorator
GroupMembershipSerializer
GroupHelper
Group
GroupMailer
NullGroupMembership
)
assert_spell 'GroupMembership', dictionary: group_classes, input: 'GroupMemberhip'
assert_spell 'GroupMembershipDecorator', dictionary: group_classes, input: 'GroupMemberhipDecorator'
names = %w(first_name_change first_name_changed? first_name_will_change!)
assert_spell names, input: 'first_name_change!', dictionary: names
assert_empty SpellChecker.new('product_path', ['proc']).corrections
assert_empty SpellChecker.new('fooo', ['fork']).corrections
end
def test_spell_checker_corrects_misspells
assert_spell 'descendants', input: 'dependents', dictionary: ['descendants']
assert_spell 'drag_to', input: 'drag', dictionary: ['drag_to']
assert_spell 'set_result_count', input: 'set_result', dictionary: ['set_result_count']
end
def test_spell_checker_sorts_results_by_simiarity
expected = %w(
name123456
name12345
name1234
name123
)
actual = SpellChecker.new("name123456", %w(
name12
name123
name1234
name12345
name123456
)).corrections
assert_equal expected, actual
end
private
def assert_spell(expected, input: , dictionary: )
corrections = SpellChecker.new(input, dictionary).corrections
assert_equal Array(expected), corrections, "Expected to suggest #{expected}, but got #{corrections.inspect}"
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/tkimg/pixmap.rb
|
#
# TkImg - format 'pixmap'
# by <NAME> (<EMAIL>)
#
require 'tk'
# call setup script for general 'tkextlib' libraries
require 'tkextlib/setup.rb'
# call setup script
require 'tkextlib/tkimg/setup.rb'
# TkPackage.require('img::pixmap', '1.3')
TkPackage.require('img::pixmap')
module Tk
module Img
module PIXMAP
PACKAGE_NAME = 'img::pixmap'.freeze
def self.package_name
PACKAGE_NAME
end
def self.package_version
begin
TkPackage.require('img::pixmap')
rescue
''
end
end
end
end
end
class TkPixmapImage<TkImage
def self.version
Tk::Img::PIXMAP.version
end
def initialize(*args)
@type = 'pixmap'
super(*args)
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/psych/lib/psych/json/yaml_events.rb
|
<filename>.rvm/src/ruby-2.3.0/ext/psych/lib/psych/json/yaml_events.rb
# frozen_string_literal: false
module Psych
module JSON
module YAMLEvents # :nodoc:
def start_document version, tag_directives, implicit
super(version, tag_directives, !streaming?)
end
def end_document implicit_end = !streaming?
super(implicit_end)
end
def start_mapping anchor, tag, implicit, style
super(anchor, nil, true, Nodes::Mapping::FLOW)
end
def start_sequence anchor, tag, implicit, style
super(anchor, nil, true, Nodes::Sequence::FLOW)
end
def scalar value, anchor, tag, plain, quoted, style
if "tag:yaml.org,2002:null" == tag
super('null', nil, nil, true, false, Nodes::Scalar::PLAIN)
else
super
end
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/lib/rdoc/ri/formatter.rb
|
# frozen_string_literal: false
##
# For RubyGems backwards compatibility
module RDoc::RI::Formatter # :nodoc:
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/tk/sample/demos-en/puzzle.rb
|
<gh_stars>0
# frozen_string_literal: false
# puzzle.rb
#
# This demonstration script creates a 15-puzzle game using a collection
# of buttons.
#
# widet demo 'puzzle' (called by 'widget')
#
# toplevel widget
if defined?($puzzle_demo) && $puzzle_demo
$puzzle_demo.destroy
$puzzle_demo = nil
end
# demo toplevel widget
$puzzle_demo = TkToplevel.new {|w|
title("15-Puzzle Demonstration")
iconname("15-Puzzle")
positionWindow(w)
}
base_frame = TkFrame.new($puzzle_demo).pack(:fill=>:both, :expand=>true)
# label
msg = TkLabel.new(base_frame) {
font $font
wraplength '4i'
justify 'left'
text "A 15-puzzle appears below as a collection of buttons. Click on any of the pieces next to the space, and that piece will slide over the space. Continue this until the pieces are arranged in numerical order from upper-left to lower-right."
}
msg.pack('side'=>'top')
# frame
TkFrame.new(base_frame) {|frame|
TkButton.new(frame) {
text 'Dismiss'
command proc{
tmppath = $puzzle_demo
$puzzle_demo = nil
tmppath.destroy
}
}.pack('side'=>'left', 'expand'=>'yes')
TkButton.new(frame) {
text 'Show Code'
command proc{showCode 'puzzle'}
}.pack('side'=>'left', 'expand'=>'yes')
}.pack('side'=>'bottom', 'fill'=>'x', 'pady'=>'2m')
# frame
# Special trick: select a darker color for the space by creating a
# scrollbar widget and using its trough color.
begin
if Tk.windowingsystem() == 'aqua'
frameWidth = 168
frameHeight = 168
elsif Tk.default_widget_set == :Ttk
frameWidth = 148
frameHeight = 124
else
frameWidth = 120
frameHeight = 120
end
rescue
frameWidth = 120
frameHeight = 120
end
# depend_on_button_width = true
depend_on_button_width = false
s = TkScrollbar.new(base_frame)
base = TkFrame.new(base_frame) {
width frameWidth
height frameHeight
borderwidth 2
relief 'sunken'
bg s['troughcolor']
}
s.destroy
base.pack('side'=>'top', 'padx'=>'1c', 'pady'=>'1c')
def def_puzzleswitch_proc(w, num)
proc{puzzleSwitch w, num}
end
$xpos = {}
$ypos = {}
order = [3,1,6,2,5,7,15,13,4,11,8,9,14,10,12]
(0..14).each{|i|
num = order[i]
$xpos[num] = (i % 4) * 0.25
$ypos[num] = (i / 4) * 0.25
TkButton.new(base) {|w|
relief 'raised'
text num
highlightthickness 0
command def_puzzleswitch_proc(w, num)
if depend_on_button_width && (w.winfo_reqwidth * 4 > base.width)
base.width = w.winfo_reqwidth * 4
end
}.place('relx'=>$xpos[num], 'rely'=>$ypos[num],
'relwidth'=>0.25, 'relheight'=>0.25)
}
$xpos['space'] = 0.75
$ypos['space'] = 0.75
# puzzleSwitch --
# This procedure is invoked when the user clicks on a particular button;
# if the button is next to the empty space, it moves the button into the
# empty space.
def puzzleSwitch(w, num)
if ( ($ypos[num] >= ($ypos['space'] - 0.01)) \
&& ($ypos[num] <= ($ypos['space'] + 0.01)) \
&& ($xpos[num] >= ($xpos['space'] - 0.26)) \
&& ($xpos[num] <= ($xpos['space'] + 0.26))) \
|| (($xpos[num] >= ($xpos['space'] - 0.01)) \
&& ($xpos[num] <= ($xpos['space'] + 0.01)) \
&& ($ypos[num] >= ($ypos['space'] - 0.26)) \
&& ($ypos[num] <= ($ypos['space'] + 0.26)))
tmp = $xpos['space']
$xpos['space'] = $xpos[num]
$xpos[num] = tmp
tmp = $ypos['space']
$ypos['space'] = $ypos[num]
$ypos[num] = tmp
w.place('relx'=>$xpos[num], 'rely'=>$ypos[num])
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/demos-en/entry1.rb
|
#
# entry (no scrollbars) widget demo (called by 'widget')
#
# toplevel widget
if defined?($entry1_demo) && $entry1_demo
$entry1_demo.destroy
$entry1_demo = nil
end
# demo toplevel widget
$entry1_demo = TkToplevel.new {|w|
title("Entry Demonstration (no scrollbars)")
iconname("entry1")
positionWindow(w)
}
base_frame = TkFrame.new($entry1_demo).pack(:fill=>:both, :expand=>true)
# label
msg = TkLabel.new(base_frame) {
font $font
wraplength '5i'
justify 'left'
text "Three different entries are displayed below. You can add characters by pointing, clicking and typing. The normal Motif editing characters are supported, along with many Emacs bindings. For example, Backspace and Control-h delete the character to the left of the insertion cursor and Delete and Control-d delete the chararacter to the right of the insertion cursor. For entries that are too large to fit in the window all at once, you can scan through the entries by dragging with mouse button2 pressed."
}
msg.pack('side'=>'top')
# frame
TkFrame.new(base_frame) {|frame|
TkButton.new(frame) {
text 'Dismiss'
command proc{
tmppath = $entry1_demo
$entry1_demo = nil
tmppath.destroy
}
}.pack('side'=>'left', 'expand'=>'yes')
TkButton.new(frame) {
text 'Show Code'
command proc{showCode 'entry1'}
}.pack('side'=>'left', 'expand'=>'yes')
}.pack('side'=>'bottom', 'fill'=>'x', 'pady'=>'2m')
#
e1 = TkEntry.new(base_frame, 'relief'=>'sunken')
e2 = TkEntry.new(base_frame, 'relief'=>'sunken')
e3 = TkEntry.new(base_frame, 'relief'=>'sunken')
[e1,e2,e3].each{|w| w.pack('side'=>'top', 'padx'=>10, 'pady'=>5, 'fill'=>'x')}
#
e1.insert(0, 'Initial value')
e2.insert('end', "This entry contains a long value, much too long ")
e2.insert('end', "to fit in the window at one time, so long in fact ")
e2.insert('end', "that you'll have to scan or scroll to see the end.")
e2.insert('end', "")
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/thread/extconf.rb
|
<reponame>arnab0073/idea
# frozen_string_literal: false
require 'mkmf'
create_makefile('thread')
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/winrm-1.8.1/lib/winrm/exceptions/exceptions.rb
|
<filename>.rvm/gems/ruby-2.3.0/gems/winrm-1.8.1/lib/winrm/exceptions/exceptions.rb
# encoding: UTF-8
#
# Copyright 2010 <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module WinRM
# WinRM base class for errors
class WinRMError < StandardError; end
# Authorization Error
class WinRMAuthorizationError < WinRMError; end
# A Fault returned in the SOAP response. The XML node is a WSManFault
class WinRMWSManFault < WinRMError
attr_reader :fault_code
attr_reader :fault_description
def initialize(fault_description, fault_code)
@fault_description = fault_description
@fault_code = fault_code
super("[WSMAN ERROR CODE: #{fault_code}]: #{fault_description}")
end
end
# A Fault returned in the SOAP response. The XML node is a MSFT_WmiError
class WinRMWMIError < WinRMError
attr_reader :error_code
attr_reader :error
def initialize(error, error_code)
@error = error
@error_code = error_code
super("[WMI ERROR CODE: #{error_code}]: #{error}")
end
end
# non-200 response without a SOAP fault
class WinRMHTTPTransportError < WinRMError
attr_reader :status_code
def initialize(msg, status_code)
@status_code = status_code
super(msg + " (#{status_code}).")
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/cgi/test_cgi_util.rb
|
# frozen_string_literal: false
require 'test/unit'
require 'cgi'
require 'stringio'
require_relative 'update_env'
class CGIUtilTest < Test::Unit::TestCase
include CGI::Util
include UpdateEnv
def setup
@environ = {}
update_env(
'REQUEST_METHOD' => 'GET',
'SCRIPT_NAME' => nil,
)
@str1="&<>\" \xE3\x82\x86\xE3\x82\x93\xE3\x82\x86\xE3\x82\x93"
@str1.force_encoding("UTF-8") if defined?(::Encoding)
end
def teardown
ENV.update(@environ)
end
def test_cgi_escape
assert_equal('%26%3C%3E%22+%E3%82%86%E3%82%93%E3%82%86%E3%82%93', CGI::escape(@str1))
assert_equal('%26%3C%3E%22+%E3%82%86%E3%82%93%E3%82%86%E3%82%93'.ascii_only?, CGI::escape(@str1).ascii_only?) if defined?(::Encoding)
end
def test_cgi_escape_with_invalid_byte_sequence
assert_nothing_raised(ArgumentError) do
assert_equal('%C0%3C%3C', CGI::escape("\xC0\<\<".force_encoding("UTF-8")))
end
end
def test_cgi_escape_preserve_encoding
assert_equal(Encoding::US_ASCII, CGI::escape("\xC0\<\<".force_encoding("US-ASCII")).encoding)
assert_equal(Encoding::ASCII_8BIT, CGI::escape("\xC0\<\<".force_encoding("ASCII-8BIT")).encoding)
assert_equal(Encoding::UTF_8, CGI::escape("\xC0\<\<".force_encoding("UTF-8")).encoding)
end
def test_cgi_unescape
assert_equal(@str1, CGI::unescape('%26%3C%3E%22+%E3%82%86%E3%82%93%E3%82%86%E3%82%93'))
assert_equal(@str1.encoding, CGI::unescape('%26%3C%3E%22+%E3%82%86%E3%82%93%E3%82%86%E3%82%93').encoding) if defined?(::Encoding)
assert_equal("\u{30E1 30E2 30EA 691C 7D22}", CGI.unescape("\u{30E1 30E2 30EA}%E6%A4%9C%E7%B4%A2"))
end
def test_cgi_unescape_preserve_encoding
assert_equal(Encoding::US_ASCII, CGI::unescape("%C0%3C%3C".force_encoding("US-ASCII")).encoding)
assert_equal(Encoding::ASCII_8BIT, CGI::unescape("%C0%3C%3C".force_encoding("ASCII-8BIT")).encoding)
assert_equal(Encoding::UTF_8, CGI::unescape("%C0%3C%3C".force_encoding("UTF-8")).encoding)
end
def test_cgi_pretty
assert_equal("<HTML>\n <BODY>\n </BODY>\n</HTML>\n",CGI::pretty("<HTML><BODY></BODY></HTML>"))
assert_equal("<HTML>\n\t<BODY>\n\t</BODY>\n</HTML>\n",CGI::pretty("<HTML><BODY></BODY></HTML>","\t"))
end
def test_cgi_escapeHTML
assert_equal("'&"><", CGI::escapeHTML("'&\"><"))
end
def test_cgi_escape_html_duplicated
orig = "Ruby".force_encoding("US-ASCII")
str = CGI::escapeHTML(orig)
assert_equal(orig, str)
assert_not_same(orig, str)
end
def assert_cgi_escape_html_preserve_encoding(str, encoding)
assert_equal(encoding, CGI::escapeHTML(str.dup.force_encoding(encoding)).encoding)
end
def test_cgi_escape_html_preserve_encoding
Encoding.list do |enc|
assert_cgi_escape_html_preserve_encoding("'&\"><", enc)
assert_cgi_escape_html_preserve_encoding("Ruby", enc)
end
end
def test_cgi_escape_html_preserve_tainted
assert_not_predicate CGI::escapeHTML("'&\"><"), :tainted?
assert_predicate CGI::escapeHTML("'&\"><".taint), :tainted?
assert_not_predicate CGI::escapeHTML("Ruby"), :tainted?
assert_predicate CGI::escapeHTML("Ruby".taint), :tainted?
end
def test_cgi_escape_html_dont_freeze
assert_not_predicate CGI::escapeHTML("'&\"><".dup), :frozen?
assert_not_predicate CGI::escapeHTML("'&\"><".freeze), :frozen?
assert_not_predicate CGI::escapeHTML("Ruby".dup), :frozen?
assert_not_predicate CGI::escapeHTML("Ruby".freeze), :frozen?
end
def test_cgi_unescapeHTML
assert_equal("'&\"><", CGI::unescapeHTML("'&"><"))
end
def test_cgi_unescapeHTML_uppercasecharacter
assert_equal("\xE3\x81\x82\xE3\x81\x84\xE3\x81\x86", CGI::unescapeHTML("あいう"))
end
def test_cgi_include_escape
assert_equal('%26%3C%3E%22+%E3%82%86%E3%82%93%E3%82%86%E3%82%93', escape(@str1))
end
def test_cgi_include_escapeHTML
assert_equal("'&"><", escapeHTML("'&\"><"))
end
def test_cgi_include_h
assert_equal("'&"><", h("'&\"><"))
end
def test_cgi_include_unescape
assert_equal(@str1, unescape('%26%3C%3E%22+%E3%82%86%E3%82%93%E3%82%86%E3%82%93'))
assert_equal(@str1.encoding, unescape('%26%3C%3E%22+%E3%82%86%E3%82%93%E3%82%86%E3%82%93').encoding) if defined?(::Encoding)
assert_equal("\u{30E1 30E2 30EA 691C 7D22}", unescape("\u{30E1 30E2 30EA}%E6%A4%9C%E7%B4%A2"))
end
def test_cgi_include_unescapeHTML
assert_equal("'&\"><", unescapeHTML("'&"><"))
end
def test_cgi_escapeElement
assert_equal("<BR><A HREF="url"></A>", escapeElement('<BR><A HREF="url"></A>', "A", "IMG"))
assert_equal("<BR><A HREF="url"></A>", escapeElement('<BR><A HREF="url"></A>', ["A", "IMG"]))
assert_equal("<BR><A HREF="url"></A>", escape_element('<BR><A HREF="url"></A>', "A", "IMG"))
assert_equal("<BR><A HREF="url"></A>", escape_element('<BR><A HREF="url"></A>', ["A", "IMG"]))
end
def test_cgi_unescapeElement
assert_equal('<BR><A HREF="url"></A>', unescapeElement(escapeHTML('<BR><A HREF="url"></A>'), "A", "IMG"))
assert_equal('<BR><A HREF="url"></A>', unescapeElement(escapeHTML('<BR><A HREF="url"></A>'), ["A", "IMG"]))
assert_equal('<BR><A HREF="url"></A>', unescape_element(escapeHTML('<BR><A HREF="url"></A>'), "A", "IMG"))
assert_equal('<BR><A HREF="url"></A>', unescape_element(escapeHTML('<BR><A HREF="url"></A>'), ["A", "IMG"]))
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/psych/test_json_tree.rb
|
# frozen_string_literal: false
require_relative 'helper'
module Psych
class TestJSONTree < TestCase
def test_string
assert_match(/"foo"/, Psych.to_json("foo"))
end
def test_symbol
assert_match(/"foo"/, Psych.to_json(:foo))
end
def test_nil
assert_match(/^null/, Psych.to_json(nil))
end
def test_int
assert_match(/^10/, Psych.to_json(10))
end
def test_float
assert_match(/^1.2/, Psych.to_json(1.2))
end
def test_hash
hash = { 'one' => 'two' }
json = Psych.to_json(hash)
assert_match(/}$/, json)
assert_match(/^\{/, json)
assert_match(/['"]one['"]/, json)
assert_match(/['"]two['"]/, json)
end
class Bar
def encode_with coder
coder.represent_seq 'omg', %w{ a b c }
end
end
def test_json_list_dump_exclude_tag
json = Psych.to_json Bar.new
refute_match('omg', json)
end
def test_list_to_json
list = %w{ one two }
json = Psych.to_json(list)
assert_match(/\]$/, json)
assert_match(/^\[/, json)
assert_match(/"one"/, json)
assert_match(/"two"/, json)
end
def test_time
time = Time.utc(2010, 10, 10)
assert_equal "{\"a\": \"2010-10-10 00:00:00.000000000 Z\"}\n",
Psych.to_json({'a' => time })
end
def test_datetime
time = Time.new(2010, 10, 10).to_datetime
assert_equal "{\"a\": \"#{time.strftime("%Y-%m-%d %H:%M:%S.%9N %:z")}\"}\n", Psych.to_json({'a' => time })
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/rdoc/test_rdoc_markup_to_table_of_contents.rb
|
# frozen_string_literal: false
require 'rdoc/test_case'
class TestRDocMarkupToTableOfContents < RDoc::Markup::FormatterTestCase
add_visitor_tests
def setup
super
@to = RDoc::Markup::ToTableOfContents.new
end
def end_accepting
assert_equal %w[hi], @to.res
end
def empty
assert_empty @to.res
end
def accept_heading
assert_equal [@RM::Heading.new(5, 'Hello')], @to.res
end
def accept_heading_1
assert_equal [@RM::Heading.new(1, 'Hello')], @to.res
end
def accept_heading_2
assert_equal [@RM::Heading.new(2, 'Hello')], @to.res
end
def accept_heading_3
assert_equal [@RM::Heading.new(3, 'Hello')], @to.res
end
def accept_heading_4
assert_equal [@RM::Heading.new(4, 'Hello')], @to.res
end
def accept_heading_b
assert_equal [@RM::Heading.new(1, '*Hello*')], @to.res
end
def accept_heading_suppressed_crossref
assert_equal [@RM::Heading.new(1, '\\Hello')], @to.res
end
alias accept_blank_line empty
alias accept_block_quote empty
alias accept_document empty
alias accept_list_end_bullet empty
alias accept_list_end_label empty
alias accept_list_end_lalpha empty
alias accept_list_end_note empty
alias accept_list_end_number empty
alias accept_list_end_ualpha empty
alias accept_list_item_end_bullet empty
alias accept_list_item_end_label empty
alias accept_list_item_end_lalpha empty
alias accept_list_item_end_note empty
alias accept_list_item_end_number empty
alias accept_list_item_end_ualpha empty
alias accept_list_item_start_bullet empty
alias accept_list_item_start_label empty
alias accept_list_item_start_lalpha empty
alias accept_list_item_start_note empty
alias accept_list_item_start_note_2 empty
alias accept_list_item_start_note_multi_description empty
alias accept_list_item_start_note_multi_label empty
alias accept_list_item_start_number empty
alias accept_list_item_start_ualpha empty
alias accept_list_start_bullet empty
alias accept_list_start_label empty
alias accept_list_start_lalpha empty
alias accept_list_start_note empty
alias accept_list_start_number empty
alias accept_list_start_ualpha empty
alias accept_paragraph empty
alias accept_paragraph_b empty
alias accept_paragraph_br empty
alias accept_paragraph_break empty
alias accept_paragraph_i empty
alias accept_paragraph_plus empty
alias accept_paragraph_star empty
alias accept_paragraph_underscore empty
alias accept_raw empty
alias accept_rule empty
alias accept_verbatim empty
alias list_nested empty
alias list_verbatim empty
alias start_accepting empty
def test_accept_document_omit_headings_below
document = doc
document.omit_headings_below = 2
@to.accept_document document
assert_equal 2, @to.omit_headings_below
end
def test_accept_heading_suppressed
@to.start_accepting
@to.omit_headings_below = 4
suppressed = head 5, 'Hello'
@to.accept_heading suppressed
assert_empty @to.res
end
def test_suppressed_eh
@to.omit_headings_below = nil
refute @to.suppressed? head(1, '')
@to.omit_headings_below = 1
refute @to.suppressed? head(1, '')
assert @to.suppressed? head(2, '')
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/rubygems/test_gem_commands_which_command.rb
|
# frozen_string_literal: false
require 'rubygems/test_case'
require 'rubygems/commands/which_command'
class TestGemCommandsWhichCommand < Gem::TestCase
def setup
super
Gem::Specification.reset
@cmd = Gem::Commands::WhichCommand.new
end
def test_execute
util_foo_bar
@cmd.handle_options %w[foo_bar]
use_ui @ui do
@cmd.execute
end
assert_equal "#{@foo_bar.full_gem_path}/lib/foo_bar.rb\n", @ui.output
assert_equal '', @ui.error
end
def test_execute_directory
@cmd.handle_options %w[directory]
use_ui @ui do
assert_raises Gem::MockGemUi::TermError do
@cmd.execute
end
end
assert_equal '', @ui.output
assert_match %r%Can.t find ruby library file or shared library directory\n%,
@ui.error
end
def test_execute_one_missing
# TODO: this test fails in isolation
util_foo_bar
@cmd.handle_options %w[foo_bar missinglib]
use_ui @ui do
assert_raises Gem::MockGemUi::TermError do
@cmd.execute
end
end
assert_equal "#{@foo_bar.full_gem_path}/lib/foo_bar.rb\n", @ui.output
assert_match %r%Can.t find ruby library file or shared library missinglib\n%,
@ui.error
end
def test_execute_missing
@cmd.handle_options %w[missinglib]
use_ui @ui do
assert_raises Gem::MockGemUi::TermError do
@cmd.execute
end
end
assert_equal '', @ui.output
assert_match %r%Can.t find ruby library file or shared library missinglib\n%,
@ui.error
end
def util_foo_bar
files = %w[lib/foo_bar.rb lib/directory/baz.rb Rakefile]
@foo_bar = util_spec 'foo_bar' do |gem|
gem.files = files
end
install_specs @foo_bar
files.each do |file|
filename = File.join(@foo_bar.full_gem_path, file)
FileUtils.mkdir_p File.dirname filename
FileUtils.touch filename
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/coverage/test_coverage.rb
|
# frozen_string_literal: false
require "test/unit"
require "coverage"
require "tmpdir"
class TestCoverage < Test::Unit::TestCase
def test_result_without_start
assert_raise(RuntimeError) {Coverage.result}
end
def test_peek_result_without_start
assert_raise(RuntimeError) {Coverage.peek_result}
end
def test_result_with_nothing
Coverage.start
result = Coverage.result
assert_kind_of(Hash, result)
result.each do |key, val|
assert_kind_of(String, key)
assert_kind_of(Array, val)
end
end
def test_coverage_snapshot
loaded_features = $".dup
Dir.mktmpdir {|tmp|
Dir.chdir(tmp) {
File.open("test.rb", "w") do |f|
f.puts <<-EOS
def coverage_test_method
:ok
end
EOS
end
Coverage.start
require tmp + '/test.rb'
cov = Coverage.peek_result[tmp + '/test.rb']
coverage_test_method
cov2 = Coverage.peek_result[tmp + '/test.rb']
assert_equal cov[1] + 1, cov2[1]
assert_equal cov2, Coverage.result[tmp + '/test.rb']
}
}
ensure
$".replace loaded_features
end
def test_restarting_coverage
loaded_features = $".dup
Dir.mktmpdir {|tmp|
Dir.chdir(tmp) {
File.open("test.rb", "w") do |f|
f.puts <<-EOS
def coverage_test_method
:ok
end
EOS
end
File.open("test2.rb", "w") do |f|
f.puts <<-EOS
def coverage_test_method2
:ok
:ok
end
EOS
end
Coverage.start
require tmp + '/test.rb'
assert_equal 3, Coverage.result[tmp + '/test.rb'].size
# Restart coverage but '/test.rb' is required before restart,
# so coverage is not recorded.
Coverage.start
coverage_test_method
assert_equal 0, Coverage.result[tmp + '/test.rb'].size
# Restart coverage and '/test2.rb' is required after restart,
# so coverage is recorded.
Coverage.start
require tmp + '/test2.rb'
assert_equal 4, Coverage.result[tmp + '/test2.rb'].size
}
}
ensure
$".replace loaded_features
end
def test_big_code
loaded_features = $".dup
Dir.mktmpdir {|tmp|
Dir.chdir(tmp) {
File.open("test.rb", "w") do |f|
f.puts "__id__\n" * 10000
f.puts "def ignore(x); end"
f.puts "ignore([1"
f.puts "])"
end
Coverage.start
require tmp + '/test.rb'
assert_equal 10003, Coverage.result[tmp + '/test.rb'].size
}
}
ensure
$".replace loaded_features
end
end
|
arnab0073/idea
|
.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/gem-wrappers-1.2.7/test/gem-wrappers_test.rb
|
<filename>.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/gem-wrappers-1.2.7/test/gem-wrappers_test.rb
require 'test_helper'
require 'tempfile'
require 'gem-wrappers'
require 'gem-wrappers/fakes'
describe GemWrappers do
subject do
GemWrappers
end
describe "fake" do
before do
@fake_installer = GemWrappers::FakeInstaller.new
@fake_envvironment = GemWrappers::FakeEnvironment.new
subject.instance_variable_set(:@installer, @fake_installer)
subject.instance_variable_set(:@environment, @fake_envvironment)
end
it "reads configured file" do
subject.environment_file.must_equal("/path/to/environment")
end
it "reads configured file" do
subject.wrappers_path.must_equal("/path/to/wrappers")
end
it "does create environment and wrapper" do
subject.install(%w{rake test})
@fake_envvironment.ensure?.must_equal(true)
@fake_installer.ensure?.must_equal(true)
@fake_installer.executables.must_equal(%w{rake test ruby gem erb irb ri rdoc testrb})
end
it "does remove wrapper" do
subject.install(%w{rake})
@fake_installer.executables.must_equal(%w{rake ruby gem erb irb ri rdoc testrb})
subject.uninstall(%w{rake})
@fake_installer.executables.must_equal(%w{ruby gem erb irb ri rdoc testrb})
end
end
describe "real" do
before do
file = Tempfile.new('wrappers')
@test_path = file.path
file.close
file.unlink
Dir.mkdir(@test_path)
subject.instance_variable_set(:@installer, nil)
subject.instance_variable_set(:@environment, nil)
@wrappers_path = File.join(@test_path, "wrappers")
@environment_path = File.join(@test_path, "environment")
@rake_wrapper = File.join(@wrappers_path, "rake")
ENV['GEMRC'] = File.join(@test_path, ".gemrc")
File.open(ENV['GEMRC'], "w") do |file|
file.write <<-GEMRC
wrappers_path: #{@wrappers_path}
wrappers_environment_file: #{@environment_path}
GEMRC
end
Gem.instance_variable_set(:@configuration, Gem::ConfigFile.new([]))
end
after do
ENV['GEMRC'] = nil
Gem.instance_variable_set(:@configuration, Gem::ConfigFile.new([]))
FileUtils.rm_rf(@test_path)
end
it "installas wrappers" do
File.exist?(@rake_wrapper).must_equal(false)
subject.install(%w{rake})
File.exist?(@rake_wrapper ).must_equal(true)
end
it "removes wrappers" do
File.exist?(@rake_wrapper ).must_equal(false)
Dir.mkdir(@wrappers_path)
File.open(@rake_wrapper, "w") do |file|
file.puts "small wrapper"
end
subject.uninstall(%w{rake})
File.exist?(@rake_wrapper ).must_equal(false)
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/test/json/test_json_generate.rb
|
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'test/unit'
require File.join(File.dirname(__FILE__), 'setup_variant')
class TC_JSONGenerate < Test::Unit::TestCase
include JSON
def setup
@hash = {
'a' => 2,
'b' => 3.141,
'c' => 'c',
'd' => [ 1, "b", 3.14 ],
'e' => { 'foo' => 'bar' },
'g' => "\"\0\037",
'h' => 1000.0,
'i' => 0.001
}
@json2 = '{"a":2,"b":3.141,"c":"c","d":[1,"b",3.14],"e":{"foo":"bar"},' +
'"g":"\\"\\u0000\\u001f","h":1000.0,"i":0.001}'
@json3 = <<'EOT'.chomp
{
"a": 2,
"b": 3.141,
"c": "c",
"d": [
1,
"b",
3.14
],
"e": {
"foo": "bar"
},
"g": "\"\u0000\u001f",
"h": 1000.0,
"i": 0.001
}
EOT
end
def test_generate
json = generate(@hash)
assert_equal(JSON.parse(@json2), JSON.parse(json))
parsed_json = parse(json)
assert_equal(@hash, parsed_json)
json = generate({1=>2})
assert_equal('{"1":2}', json)
parsed_json = parse(json)
assert_equal({"1"=>2}, parsed_json)
assert_raise(GeneratorError) { generate(666) }
assert_equal '666', generate(666, :quirks_mode => true)
end
def test_generate_pretty
json = pretty_generate(@hash)
# hashes aren't (insertion) ordered on every ruby implementation assert_equal(@json3, json)
assert_equal(JSON.parse(@json3), JSON.parse(json))
parsed_json = parse(json)
assert_equal(@hash, parsed_json)
json = pretty_generate({1=>2})
assert_equal(<<'EOT'.chomp, json)
{
"1": 2
}
EOT
parsed_json = parse(json)
assert_equal({"1"=>2}, parsed_json)
assert_raise(GeneratorError) { pretty_generate(666) }
assert_equal '666', pretty_generate(666, :quirks_mode => true)
end
def test_fast_generate
json = fast_generate(@hash)
assert_equal(JSON.parse(@json2), JSON.parse(json))
parsed_json = parse(json)
assert_equal(@hash, parsed_json)
json = fast_generate({1=>2})
assert_equal('{"1":2}', json)
parsed_json = parse(json)
assert_equal({"1"=>2}, parsed_json)
assert_raise(GeneratorError) { fast_generate(666) }
assert_equal '666', fast_generate(666, :quirks_mode => true)
end
def test_own_state
state = State.new
json = generate(@hash, state)
assert_equal(JSON.parse(@json2), JSON.parse(json))
parsed_json = parse(json)
assert_equal(@hash, parsed_json)
json = generate({1=>2}, state)
assert_equal('{"1":2}', json)
parsed_json = parse(json)
assert_equal({"1"=>2}, parsed_json)
assert_raise(GeneratorError) { generate(666, state) }
state.quirks_mode = true
assert state.quirks_mode?
assert_equal '666', generate(666, state)
end
def test_states
json = generate({1=>2}, nil)
assert_equal('{"1":2}', json)
s = JSON.state.new
assert s.check_circular?
assert s[:check_circular?]
h = { 1=>2 }
h[3] = h
assert_raises(JSON::NestingError) { generate(h) }
assert_raises(JSON::NestingError) { generate(h, s) }
s = JSON.state.new
a = [ 1, 2 ]
a << a
assert_raises(JSON::NestingError) { generate(a, s) }
assert s.check_circular?
assert s[:check_circular?]
end
def test_pretty_state
state = PRETTY_STATE_PROTOTYPE.dup
assert_equal({
:allow_nan => false,
:array_nl => "\n",
:ascii_only => false,
:quirks_mode => false,
:depth => 0,
:indent => " ",
:max_nesting => 19,
:object_nl => "\n",
:space => " ",
:space_before => "",
}.sort_by { |n,| n.to_s }, state.to_h.sort_by { |n,| n.to_s })
end
def test_safe_state
state = SAFE_STATE_PROTOTYPE.dup
assert_equal({
:allow_nan => false,
:array_nl => "",
:ascii_only => false,
:quirks_mode => false,
:depth => 0,
:indent => "",
:max_nesting => 19,
:object_nl => "",
:space => "",
:space_before => "",
}.sort_by { |n,| n.to_s }, state.to_h.sort_by { |n,| n.to_s })
end
def test_fast_state
state = FAST_STATE_PROTOTYPE.dup
assert_equal({
:allow_nan => false,
:array_nl => "",
:ascii_only => false,
:quirks_mode => false,
:depth => 0,
:indent => "",
:max_nesting => 0,
:object_nl => "",
:space => "",
:space_before => "",
}.sort_by { |n,| n.to_s }, state.to_h.sort_by { |n,| n.to_s })
end
def test_allow_nan
assert_raises(GeneratorError) { generate([JSON::NaN]) }
assert_equal '[NaN]', generate([JSON::NaN], :allow_nan => true)
assert_raises(GeneratorError) { fast_generate([JSON::NaN]) }
assert_raises(GeneratorError) { pretty_generate([JSON::NaN]) }
assert_equal "[\n NaN\n]", pretty_generate([JSON::NaN], :allow_nan => true)
assert_raises(GeneratorError) { generate([JSON::Infinity]) }
assert_equal '[Infinity]', generate([JSON::Infinity], :allow_nan => true)
assert_raises(GeneratorError) { fast_generate([JSON::Infinity]) }
assert_raises(GeneratorError) { pretty_generate([JSON::Infinity]) }
assert_equal "[\n Infinity\n]", pretty_generate([JSON::Infinity], :allow_nan => true)
assert_raises(GeneratorError) { generate([JSON::MinusInfinity]) }
assert_equal '[-Infinity]', generate([JSON::MinusInfinity], :allow_nan => true)
assert_raises(GeneratorError) { fast_generate([JSON::MinusInfinity]) }
assert_raises(GeneratorError) { pretty_generate([JSON::MinusInfinity]) }
assert_equal "[\n -Infinity\n]", pretty_generate([JSON::MinusInfinity], :allow_nan => true)
end
def test_depth
ary = []; ary << ary
assert_equal 0, JSON::SAFE_STATE_PROTOTYPE.depth
assert_raises(JSON::NestingError) { JSON.generate(ary) }
assert_equal 0, JSON::SAFE_STATE_PROTOTYPE.depth
assert_equal 0, JSON::PRETTY_STATE_PROTOTYPE.depth
assert_raises(JSON::NestingError) { JSON.pretty_generate(ary) }
assert_equal 0, JSON::PRETTY_STATE_PROTOTYPE.depth
s = JSON.state.new
assert_equal 0, s.depth
assert_raises(JSON::NestingError) { ary.to_json(s) }
assert_equal 19, s.depth
end
def test_gc
bignum_too_long_to_embed_as_string = 1234567890123456789012345
expect = bignum_too_long_to_embed_as_string.to_s
stress, GC.stress = GC.stress, true
10.times do |i|
tmp = bignum_too_long_to_embed_as_string.to_json
assert_equal expect, tmp
end
ensure
GC.stress = stress
end if GC.respond_to?(:stress=)
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/psych/lib/psych/versions.rb
|
# frozen_string_literal: false
module Psych
DEFAULT_SNAKEYAML_VERSION = '1.14'.freeze
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/blt/plot1.rb
|
<gh_stars>10-100
#!/usr/bin/env ruby
require 'tk'
require 'tkextlib/blt'
graph = Tk::BLT::Graph.new.pack
plot = Tk::BLT::PlotComponent::Element.new(graph, :linewidth=>0, :label=>'foo')
plot.data([[1.0, 3.4], [1.1, 2.8], [1.2, 3.1], [1.4, 2.9]].flatten)
Tk.mainloop
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/treectrl/outlook-newgroup.rb
|
#
# Demo: Outlook Express newsgroup messages
#
def demoOutlookNewsgroup(t)
init_pics('outlook-*')
height = t.font.metrics(:linespace)
height = 18 if height < 18
t.configure(:itemheight=>height, :selectmode=>:browse, :showlines=>false,
:showroot=>false, :showrootbutton=>false, :showbuttons=>true)
if $Version_1_1_OrLater
t.column_create(:image=>@images['outlook-clip'], :tag=>'clip')
t.column_create(:image=>@images['outlook-arrow'], :tag=>'arrow')
t.column_create(:image=>@images['outlook-watch'], :tag=>'watch')
t.column_create(:text=>'Subject', :width=>250, :tag=>'subject')
t.column_create(:text=>'From', :width=>150, :tag=>'from')
t.column_create(:text=>'Sent', :width=>150, :tag=>'sent')
t.column_create(:text=>'Size', :width=>60, :justify=>:right, :tag=>'size')
else # TreeCtrl 1.0
t.column_configure(0, :image=>@images['outlook-clip'], :tag=>'clip')
t.column_configure(1, :image=>@images['outlook-arrow'], :tag=>'arrow')
t.column_configure(2, :image=>@images['outlook-watch'], :tag=>'watch')
t.column_configure(3, :text=>'Subject', :width=>250, :tag=>'subject')
t.column_configure(4, :text=>'From', :width=>150, :tag=>'from')
t.column_configure(5, :text=>'Sent', :width=>150, :tag=>'sent')
t.column_configure(6, :text=>'Size', :width=>60, :justify=>:right,
:tag=>'size')
end
# Would be nice if I could specify a column -tag too
t.treecolumn = 3
# State for a read message
t.state_define('read')
# State for a message with unread descendants
t.state_define('unread')
t.element_create('elemImg', :image,
:image=>[
@sel_images['outlook-read-2'],
['selected', 'read', 'unread', '!open'],
@images['outlook-read-2'], ['read', 'unread', '!open'],
@sel_images['outlook-read'], ['selected', 'read'],
@images['outlook-read'], ['read'],
@sel_images['outlook-unread'], ['selected'],
@images['outlook-unread'], []
])
t.element_create('elemTxt', :text, :lines=>1,
:fill=>[@SystemHighlightText, ['selected', 'focus']],
:font=>[
t.font.dup.weight(:bold), ['read', 'unread', '!open'],
t.font.dup.weight(:bold), ['!read']
])
t.element_create('sel.e', :rect, :open=>:e, :showfocus=>true,
:fill=>[
@SystemHighlight, ['selected', 'focus'],
'gray', ['selected', '!focus']
])
t.element_create('sel.w', :rect, :open=>:w, :showfocus=>true,
:fill=>[
@SystemHighlight, ['selected', 'focus'],
'gray', ['selected', '!focus']
])
t.element_create('sel.we', :rect, :open=>:we, :showfocus=>true,
:fill=>[
@SystemHighlight, ['selected', 'focus'],
'gray', ['selected', '!focus']
])
# Image + text
s = t.style_create('s1')
t.style_elements(s, ['sel.e', 'elemImg', 'elemTxt'])
t.style_layout(s, 'elemImg', :expand=>:ns)
t.style_layout(s, 'elemTxt', :padx=>[2,6], :squeeze=>:x, :expand=>:ns)
t.style_layout(s, 'sel.e', :union=>['elemTxt'],
:iexpand=>:nes, :ipadx=>[2,0])
# Text
s = t.style_create('s2.we')
t.style_elements(s, ['sel.we', 'elemTxt'])
t.style_layout(s, 'elemTxt', :padx=>6, :squeeze=>:x, :expand=>:ns)
t.style_layout(s, 'sel.we', :detach=>true, :iexpand=>:es)
# Text
s = t.style_create('s2.w')
t.style_elements(s, ['sel.w', 'elemTxt'])
t.style_layout(s, 'elemTxt', :padx=>6, :squeeze=>:x, :expand=>:ns)
t.style_layout(s, 'sel.w', :detach=>true, :iexpand=>:es)
# Set default item style
if $Version_1_1_OrLater
t.defaultstyle = ['', '', '', 's1', 's2.we', 's2.we', 's2.w']
end
msgCnt = 100
thread = 0
@Message = Hash.new{|k, v| k[v] = Hash.new}
@Message[:count][0] = 0
items = [t.index(:root)]
(1...(msgCnt)).each{|i|
item_i = t.item_create
item_j = nil
j = nil
loop {
j = rand(i)
item_j = items[j]
break if j == 0
next if t.depth(item_j) == 5
next if @Message[:count][@Message[:thread][item_j]] == 15
break
}
t.item_lastchild(item_j, item_i)
@Message[:read][item_i] = (rand(2) == 0)
if j == 0
thread += 1
@Message[:thread][item_i] = thread
@Message[:seconds][item_i] = (Tk::Clock.seconds - rand(500000))
@Message[:seconds2][item_i] = @Message[:seconds][item_i]
@Message[:count][thread] = 1
else
@Message[:thread][item_i] = @Message[:thread][item_j]
@Message[:seconds][item_i] = (@Message[:seconds2][item_j] + rand(10000))
@Message[:seconds2][item_i] = @Message[:seconds][item_i]
@Message[:seconds2][item_j] = @Message[:seconds][item_i]
@Message[:count][@Message[:thread][item_j]] += 1
end
items << item_i
}
(1...(msgCnt)).each{|i|
item_i = items[i]
subject = "This is thread number #{@Message[:thread][item_i]}"
from = '<EMAIL>'
sent = Tk::Clock.format(@Message[:seconds][item_i], "%d/%m/%y %I:%M %p")
size = "#{1 + rand(10)}KB"
# This message has been read
t.item_state_set(item_i, 'read') if @Message[:read][item_i]
# This message has unread descendants
t.item_state_set(item_i, 'unread') if anyUnreadDescendants(t, item_i)
if t.item_numchildren(item_i) > 0
if $Version_1_1_OrLater
t.item_configure(item_i, :button=>true)
else # TreeCtrl 1.0
t.item_hasbutton(item_i, true)
end
# Collapse some messages
if $Version_1_1_OrLater
t.item_collapse(item_i) if rand(2) == 0
else # TreeCtrl 1.0
t.collapse(item_i) if rand(2) == 0
end
end
unless $Version_1_1_OrLater
t.item_style_set(item_i, 3, 's1', 4, 's2.we', 5, 's2.we', 6, 's2.w')
end
t.item_text(item_i, 3, subject, 4, from, 5, sent, 6, size)
}
# Do something when the selection changes
t.notify_bind(t, 'Selection',
proc{|w|
if w.selection_count == 1
# One item is selected
if @Message[:afterId][:id]
Tk.after_cancel(@Message[:afterId][:id])
end
@Message[:afterId][:item] = w.selection_get[0]
@Message[:afterId][:id] = Tk.after(500, proc{
messageReadDelayed(w)
})
end
}, '%T')
end
def messageReadDelayed(t)
@Message[:afterId].delete(:id)
i = @Message[:afterId][:item]
return unless t.selection_includes(i)
# This message is not read
unless @Message[:read][i]
# Read the message
t.item_state_set(i, 'read')
@Message[:read][i] = true
# Check ancestors (except root)
t.item_ancestors(i)[0..-2].each{|i2|
# This ancestor has no more unread descendants
t.item_state_set(i2, '!unread') unless anyUnreadDescendants(t, i2)
}
end
end
# Alternate implementation which does not rely on run-time states
def demoOutlookNewsgroup2(t)
init_pics('outlook-*')
height = t.font.metrics(:linespace)
height = 18 if height < 18
t.configure(:itemheight=>height, :selectmode=>:browse, :showlines=>false,
:showroot=>false, :showrootbutton=>false, :showbuttons=>true)
if $Version_1_1_OrLater
t.column_create(:image=>@images['outlook-clip'], :tag=>'clip')
t.column_create(:image=>@images['outlook-arrow'], :tag=>'arrow')
t.column_create(:image=>@images['outlook-watch'], :tag=>'watch')
t.column_create(:text=>'Subject', :width=>250, :tag=>'subject')
t.column_create(:text=>'From', :width=>150, :tag=>'from')
t.column_create(:text=>'Sent', :width=>150, :tag=>'sent')
t.column_create(:text=>'Size', :width=>60, :justify=>:right, :tag=>'size')
else # TreeCtrl 1.0
t.column_configure(0, :image=>@images['outlook-clip'], :tag=>'clip')
t.column_configure(1, :image=>@images['outlook-arrow'], :tag=>'arrow')
t.column_configure(2, :image=>@images['outlook-watch'], :tag=>'watch')
t.column_configure(3, :text=>'Subject', :width=>250, :tag=>'subject')
t.column_configure(4, :text=>'From', :width=>150, :tag=>'from')
t.column_configure(5, :text=>'Sent', :width=>150, :tag=>'sent')
t.column_configure(6, :text=>'Size', :width=>60, :justify=>:right,
:tag=>'size')
end
t.treecolumn = 3
t.element_create('image.unread', :image, :image=>@images['outlook-unread'])
t.element_create('image.read', :image, :image=>@images['outlook-read'])
t.element_create('image.read2', :image, :image=>@images['outlook-read-2'])
t.element_create('text.read', :text, :lines=>1,
:fill=>[@SystemHighlightText, ['selected', 'focus']])
t.element_create('text.unread', :text, :lines=>1,
:fill=>[@SystemHighlightText, ['selected', 'focus']],
:font=>t.font.dup.weight(:bold))
t.element_create('sel.e', :rect, :open=>:e, :showfocus=>true,
:fill=>[
@SystemHighlight, ['selected', 'focus'],
'gray', ['selected', '!focus']
])
t.element_create('sel.w', :rect, :open=>:w, :showfocus=>true,
:fill=>[
@SystemHighlight, ['selected', 'focus'],
'gray', ['selected', '!focus']
])
t.element_create('sel.we', :rect, :open=>:we, :showfocus=>true,
:fill=>[
@SystemHighlight, ['selected', 'focus'],
'gray', ['selected', '!focus']
])
# Image + text
s = t.style_create('unread')
t.style_elements(s, ['sel.e', 'image.unread', 'text.unread'])
t.style_layout(s, 'image.unread', :expand=>:ns)
t.style_layout(s, 'text.unread', :padx=>[2,6], :squeeze=>:x, :expand=>:ns)
t.style_layout(s, 'sel.e', :union=>['text.unread'],
:iexpand=>:nes, :ipadx=>[2,0])
# Image + text
s = t.style_create('read')
t.style_elements(s, ['sel.e', 'image.read', 'text.read'])
t.style_layout(s, 'image.read', :expand=>:ns)
t.style_layout(s, 'text.read', :padx=>[2,6], :squeeze=>:x, :expand=>:ns)
t.style_layout(s, 'sel.e', :union=>['text.read'],
:iexpand=>:nes, :ipadx=>[2,0])
# Image + text
s = t.style_create('read2')
t.style_elements(s, ['sel.e', 'image.read2', 'text.unread'])
t.style_layout(s, 'image.read2', :expand=>:ns)
t.style_layout(s, 'text.unread', :padx=>[2,6], :squeeze=>:x, :expand=>:ns)
t.style_layout(s, 'sel.e', :union=>['text.unread'],
:iexpand=>:nes, :ipadx=>[2,0])
# Text
s = t.style_create('unread.we')
t.style_elements(s, ['sel.we', 'text.unread'])
t.style_layout(s, 'text.unread', :padx=>6, :squeeze=>:x, :expand=>:ns)
t.style_layout(s, 'sel.we', :detach=>true, :iexpand=>:es)
# Text
s = t.style_create('read.we')
t.style_elements(s, ['sel.we', 'text.read'])
t.style_layout(s, 'text.read', :padx=>6, :squeeze=>:x, :expand=>:ns)
t.style_layout(s, 'sel.we', :detach=>true, :iexpand=>:es)
# Text
s = t.style_create('unread.w')
t.style_elements(s, ['sel.w', 'text.unread'])
t.style_layout(s, 'text.unread', :padx=>6, :squeeze=>:x, :expand=>:ns)
t.style_layout(s, 'sel.w', :detach=>true, :iexpand=>:es)
# Text
s = t.style_create('read.w')
t.style_elements(s, ['sel.w', 'text.read'])
t.style_layout(s, 'text.read', :padx=>6, :squeeze=>:x, :expand=>:ns)
t.style_layout(s, 'sel.w', :detach=>true, :iexpand=>:es)
msgCnt = 100
thread = 0
@Message = Hash.new{|k, v| k[v] = Hash.new}
@Message[:count][0] = 0
(1...(msgCnt)).each{|i|
t.item_create
j = nil
loop {
j = rand(i)
break if j == 0
next if t.depth(j) == 5
next if @Message[:count][@Message[:thread][j]] == 15
break
}
t.item_lastchild(j, i)
@Message[:read][i] = (rand(2) == 0)
if j == 0
thread += 1
@Message[:thread][i] = thread
@Message[:seconds][i] = (Tk::Clock.seconds - rand(500000))
@Message[:seconds2][i] = @Message[:seconds][i]
@Message[:count][thread] = 1
else
@Message[:thread][i] = @Message[:thread][j]
@Message[:seconds][i] = (@Message[:seconds2][j] + rand(10000))
@Message[:seconds2][i] = @Message[:seconds][i]
@Message[:seconds2][j] = @Message[:seconds][i]
@Message[:count][@Message[:thread][j]] += 1
end
}
(1...(msgCnt)).each{|i|
subject = "This is thread number #{@Message[:thread][i]}"
from = '<EMAIL>'
sent = Tk::Clock.format(@Message[:seconds][i], "%d/%m/%y %I:%M %p")
size = "#{1 + rand(10)}KB"
if @Message[:read][i]
style = 'read'
style2 = 'read2'
else
style = 'unread'
style2 = 'unread2'
end
t.item_style_set(i, 3, style, 4, "#{style2}.we", 5, "#{style2}.we",
6, "#{style2}.w")
t.item_text(i, 3, subject, 4, from, 5, sent, 6, size)
if t.item_numchildren(i) > 0
t.item_configure(item_i, :button=>true)
end
}
# Do something when the selection changes
t.notify_bind(t, 'Selection',
proc{|w|
if w.selection_count == 1
i = t.selection_get[0]
unless @Message[:read][i]
if t.item_isopen(i) || !anyUnreadDescendants(t, i)
# unread -> read
t.item_style_map(i, 'subject', 'read',
['text.unread', 'text.read'])
t.item_style_map(i, 'from', 'read.we',
['text.unread', 'text.read'])
t.item_style_map(i, 'sent', 'read.we',
['text.unread', 'text.read'])
t.item_style_map(i, 'size', 'read.w',
['text.unread', 'text.read'])
else
# unread -> read2
t.item_style_map(i, 'subject', 'read2',
['text.unread', 'text.unread'])
end
@Message[:read][i] = true
@display_styles_in_item.call(i)
end
end
}, '%T')
t.notify_bind(t, 'Expand-after',
proc{|w, i|
if @Messge[:read][i] && anyUnreadDescendants(t, i)
# read2 -> read
t.item_style_map(i, 'subject', 'read',
['text.unread', 'text.read'])
# unread -> read
t.item_style_map(i, 'from', 'read.we',
['text.unread', 'text.read'])
t.item_style_map(i, 'sent', 'read.we',
['text.unread', 'text.read'])
t.item_style_map(i, 'size', 'read.w',
['text.unread', 'text.read'])
end
}, '%T %I')
t.notify_bind(t, 'Collapse-after',
proc{|w, i|
if @Messge[:read][i] && anyUnreadDescendants(t, i)
# read -> read2
t.item_style_map(i, 'subject', 'read2',
['text.read', 'text.unread'])
# read -> unread
t.item_style_map(i, 'from', 'unread.we',
['text.read', 'text.unread'])
t.item_style_map(i, 'sent', 'unread.we',
['text.read', 'text.unread'])
t.item_style_map(i, 'size', 'unread.w',
['text.read', 'text.unread'])
end
}, '%T %I')
(1...(msgCnt)).each{|i|
if rand(2) == 0
if t.item_numchildren(i) > 0
if $Version_1_1_OrLater
t.item_collapse(i)
else # TreeCtrl 1.0
t.collapse(i)
end
end
end
}
end
def anyUnreadDescendants(t, i)
itemList = []
item = t.item_firstchild(i)
itemList.push(item) if item != ''
while item = itemList.pop
return true unless @Message[:read][item]
item2 = t.item_nextsibling(item)
itemList.push(item2) if item2 != ''
item2 = t.item_firstchild(item)
itemList.push(item2) if item2 != ''
end
false
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/cloudstack/requests/compute/associate_ip_address.rb
|
<gh_stars>1-10
module Fog
module Compute
class Cloudstack
class Real
# Acquires and associates a public IP to an account.
#
# {CloudStack API Reference}[http://cloudstack.apache.org/docs/api/apidocs-4.4/root_admin/associateIpAddress.html]
def associate_ip_address(*args)
options = {}
if args[0].is_a? Hash
options = args[0]
options.merge!('command' => 'associateIpAddress')
else
options.merge!('command' => 'associateIpAddress')
end
# add project id if we have one
@cloudstack_project_id ? options.merge!('projectid' => @cloudstack_project_id) : nil
request(options)
end
end
class Mock
def associate_ip_address(*args)
public_ip_address = {
"id" => "f2f2f2f2-f2f2-f2f2-f2f2-f2f2f2f2f2",
"ipaddress" => "192.168.200.3",
"allocated" => "2014-12-22T22:32:39+0000",
"zoneid" => "0e276270-7950-4483-bf21-3dc897dbe08a",
"zonename" => "Toronto",
"issourcenat" => false,
"projectid" => "f1f1f1f1-f1f1-f1f1-f1f1-f1f1f1f1f1",
"project" => "TestProject",
"domainid" => "f1f1f1f1-f1f1-f1f1-f1f1-f1f1f1f1f1",
"domain" => "TestDomain",
"forvirtualnetwork" => true,
"isstaticnat" => false,
"issystem" => false,
"associatednetworkid" => "f1f1f1f1-f1f1-f1f1-f1f1-f1f1f1f1f1",
"associatednetworkname" => "TestNetwork",
"networkid" => "f1f1f1f1-f1f1-f1f1-f1f1-f1f1f1f1f1",
"state" => "Allocated",
"physicalnetworkid" => "f1f1f1f1-f1f1-f1f1-f1f1-f1f1f1f1f1",
"tags" => []
}
self.data[:public_ip_addresses][public_ip_address_id]= public_ip_address
{'associateipaddressresponse' => public_ip_address}
end
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/test/scanf/test_scanfio.rb
|
<reponame>arnab0073/idea
# $Id: test_scanfio.rb 25426 2009-10-21 03:44:56Z nobu $
#
# scanf for Ruby
#
# Ad hoc tests of IO#scanf (needs to be expanded)
require "scanf"
class TestScanfIO < Test::Unit::TestCase
def test_io
fh = File.new(File.join(File.dirname(__FILE__), "data.txt"), "r")
assert_equal(0, fh.pos)
assert_equal(["this", "is"], fh.scanf("%s%s"))
assert_equal([33, "little"], fh.scanf("%da fun%s"))
ensure
fh.close
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/tool/parse.rb
|
$file = ARGV[0]
$str = ARGF.read.sub(/^__END__.*\z/m, '')
puts '# ' + '-' * 70
puts "# target program: "
puts '# ' + '-' * 70
puts $str
puts '# ' + '-' * 70
$parsed = RubyVM::InstructionSequence.compile_file($file)
puts "# disasm result: "
puts '# ' + '-' * 70
puts $parsed.disasm
puts '# ' + '-' * 70
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/fiddle/lib/fiddle/function.rb
|
<filename>.rvm/src/ruby-2.3.0/ext/fiddle/lib/fiddle/function.rb
# frozen_string_literal: false
module Fiddle
class Function
# The ABI of the Function.
attr_reader :abi
# The address of this function
attr_reader :ptr
# The name of this function
attr_reader :name
# The integer memory location of this function
def to_i
ptr.to_i
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/tk/lib/tkextlib/itk/incr_tk.rb
|
<reponame>arnab0073/idea
# frozen_string_literal: false
#
# tkextlib/itk/incr_tk.rb
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tk/menuspec'
require 'tkextlib/itcl.rb'
# call setup script
require 'tkextlib/itk.rb'
#TkPackage.require('Itk', '3.2')
TkPackage.require('Itk')
module Tk
module Itk
include Tk
extend Tk
LIBRARY = TkVarAccess.new('::itk::library')
PACKAGE_NAME = 'Itk'.freeze
def self.package_name
PACKAGE_NAME
end
def self.package_version
begin
TkPackage.require('Itk')
rescue
''
end
end
def self.usual(arg, *args)
tk_call('::itk::usual', arg, *args)
end
def self.usual_names
list(tk_call('::itk::usual'))
end
############################
class Archetype < TkWindow
TkCommandNames = [].freeze
# WidgetClassName = 'Archetype'.freeze
# WidgetClassNames[WidgetClassName] = self
def self.to_eval
'::itk::' << self::WidgetClassName
end
def __destroy_hook__
Tk::Itk::Component::ComponentID_TBL.delete(self.path)
end
#### [incr Tk] public methods
def component
simplelist(tk_send('component'))
end
def component_path(name)
window(tk_send('component', name))
end
alias component_widget component_path
def component_invoke(name, cmd, *args)
window(tk_send('component', name, cmd, *args))
end
def component_obj(*names)
names = component if names.empty?
names.collect{|name| Tk::Itk::Component.new(self.path, name) }
end
#### [incr Tk] protected methods
=begin
def itk_component_add(visibility, name, create_cmds, option_cmds=None)
args = []
visibility.each{|v| v = v.to_s; args << ( (v[0] == ?-)? v: "-#{v}" )}
args << '--' << name << create_cmd << option_cmds
tk_call('itk_component', 'add', *args)
end
def itk_component_delete(*names)
tk_call('itk_component', 'delete', *names)
end
def itk_initialize(keys={})
tk_call('itk_initialize', keys)
end
def itk_option_add(*args)
tk_call('itk_option', 'add', *args)
end
def itk_option_define(name, resource, klass, init, config=None)
tk_call('itk_option', 'define', name, resource, klass, init, config)
end
def itk_option_remove(*args)
tk_call('itk_option', 'remove', *args)
end
=end
end
############################
class Toplevel < Archetype
TkCommandNames = ['::itk::Toplevel'].freeze
WidgetClassName = 'Toplevel'.freeze
WidgetClassNames[WidgetClassName] ||= self
include Wm
include TkMenuSpec
def __strval_optkeys
super() << 'title'
end
private :__strval_optkeys
end
############################
class Widget < Archetype
TkCommandNames = ['::itk::Widget'].freeze
WidgetClassName = 'Widget'.freeze
WidgetClassNames[WidgetClassName] ||= self
end
############################
class Component < TkObject
def __cget_cmd
[self.master, 'component', self.name, 'cget']
end
private :__cget_cmd
def __config_cmd
[self.master, 'component', self.name, 'configure']
end
private :__config_cmd
ComponentID_TBL = TkCore::INTERP.create_table
(Itk_Component_ID = ['itk:component'.freeze, TkUtil.untrust('00000')]).instance_eval{
@mutex = Mutex.new
def mutex; @mutex; end
freeze
}
TkCore::INTERP.init_ip_env{
ComponentID_TBL.mutex.synchronize{ ComponentID_TBL.clear }
}
def self.id2obj(master, id)
if master.kind_of?(TkObject)
master = master.path
else
master = master.to_s
end
ComponentID_TBL.mutex.synchronize{
if ComponentID_TBL.key?(master)
(ComponentID_TBL[master].key?(id))? ComponentID_TBL[master][id]: id
else
id
end
}
end
def self.new(master, component=nil)
if master.kind_of?(TkObject)
master = master.path
else
master = master.to_s
end
if component.kind_of?(Tk::Itk::Component)
component = component.name
elsif component
component = component.to_s
else
Itk_Component_ID.mutex.synchronize{
component = Itk_Component_ID.join(TkCore::INTERP._ip_id_)
Itk_Component_ID[1].succ!
}
end
ComponentID_TBL.mutex.synchronize{
if ComponentID_TBL.key?(master)
if ComponentID_TBL[master].key?(component)
return ComponentID_TBL[master][component]
end
else
ComponentID_TBL[master] = {}
end
}
super(master, component)
end
def initialize(master, component)
@master = master
@component = component
ComponentID_TBL.mutex.synchronize{
ComponentID_TBL[@master][@component] = self
}
begin
@widget = window(tk_call(@master, 'component', @component))
@path = @widget.path
rescue
@widget = nil
@path = nil
end
end
def path
unless @path
begin
@widget = window(tk_call(@master, 'component', @component))
@path = @widget.path
rescue
fail RuntimeError, 'component is not assigned to a widget'
end
end
@path
end
def epath
path()
end
def to_eval
path()
end
def master
@master
end
def name
@component
end
def widget
unless @widget
begin
@widget = window(tk_call(@master, 'component', @component))
@path = @widget.path
rescue
fail RuntimeError, 'component is not assigned to a widget'
end
end
@widget
end
def widget_class
unless @widget
begin
@widget = window(tk_call(@master, 'component', @component))
@path = @widget.path
@widget.classname
rescue
nil
end
end
end
def method_missing(id, *args)
name = id.id2name
# try 1 : component command
begin
return tk_call(@master, 'component', @component, name, *args)
rescue
end
# try 2 : component configure
len = args.length
begin
case len
when 1
if name[-1] == ?=
return configure(name[0..-2], args[0])
else
return configure(name, args[0])
end
when 0
return cget(name)
end
rescue
end
# try 3 : widget method or widget configure
begin
unless @widget
@widget = window(tk_call(@master, 'component', @component))
@path = @widget.path
end
@widget.__send__(id, *args)
rescue
end
# unknown method
super(id, *args)
# fail RuntimeError, "unknown method '#{name}' for #{self.inspect}"
end
def tk_send(cmd, *rest)
begin
tk_call(@master, 'component', @component, cmd, *rest)
rescue
unless @path
begin
@widget = window(tk_call(@master, 'component', @component))
@path = @widget.path
rescue
fail RuntimeError, 'component is not assigned to a widget'
end
end
tk_call(@path, cmd, *rest)
end
end
def tk_send_without_enc(cmd, *rest)
begin
tk_call_without_enc(@master, 'component', @component, cmd, *rest)
rescue
unless @path
begin
@widget = window(tk_call(@master, 'component', @component))
@path = @widget.path
rescue
fail RuntimeError, 'component is not assigned to a widget'
end
end
tk_call_without_enc(@path, cmd, *rest)
end
end
def tk_send_with_enc(cmd, *rest)
begin
tk_call_with_enc(@master, 'component', @component, cmd, *rest)
rescue
unless @path
begin
@widget = window(tk_call(@master, 'component', @component))
@path = @widget.path
rescue
fail RuntimeError, 'component is not assigned to a widget'
end
end
tk_call_with_enc(@path, cmd, *rest)
end
end
#def bind(*args)
# unless @widget
# begin
# @widget = window(tk_call(@master, 'component', @component))
# @path = @widget.path
# rescue
# fail RuntimeError, 'component is not assigned to a widget'
# end
# end
# @widget.bind(*args)
#end
def bind(context, *args)
unless @widget
begin
@widget = window(tk_call(@master, 'component', @component))
@path = @widget.path
rescue
fail RuntimeError, 'component is not assigned to a widget'
end
end
# if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
if TkComm._callback_entry?(args[0]) || !block_given?
cmd = args.shift
else
cmd = Proc.new
end
@widget.bind(context, cmd, *args)
end
#def bind_append(*args)
# unless @widget
# begin
# @widget = window(tk_call(@master, 'component', @component))
# @path = @widget.path
# rescue
# fail RuntimeError, 'component is not assigned to a widget'
# end
# end
# @widget.bind_append(*args)
#end
def bind_append(context, *args)
unless @widget
begin
@widget = window(tk_call(@master, 'component', @component))
@path = @widget.path
rescue
fail RuntimeError, 'component is not assigned to a widget'
end
end
# if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
if TkComm._callback_entry?(args[0]) || !block_given?
cmd = args.shift
else
cmd = Proc.new
end
@widget.bind_append(context, cmd, *args)
end
def bind_remove(*args)
unless @widget
begin
@widget = window(tk_call(@master, 'component', @component))
@path = @widget.path
rescue
fail RuntimeError, 'component is not assigned to a widget'
end
end
@widget.bind_remove(*args)
end
def bindinfo(*args)
unless @widget
begin
@widget = window(tk_call(@master, 'component', @component))
@path = @widget.path
rescue
fail RuntimeError, 'component is not assigned to a widget'
end
end
@widget.bindinfo(*args)
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/io/nonblock/extconf.rb
|
<gh_stars>10-100
require 'mkmf'
target = "io/nonblock"
hdr = %w"fcntl.h"
if have_macro("O_NONBLOCK", hdr) and
(have_macro("F_GETFL", hdr) or have_macro("F_SETFL", hdr))
create_makefile(target)
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/knife-ec2-0.12.0/spec/unit/ec2_server_create_spec.rb
|
<filename>.rvm/gems/ruby-2.3.0/gems/knife-ec2-0.12.0/spec/unit/ec2_server_create_spec.rb
#
# Author:: <NAME> (<<EMAIL>>)
# Copyright:: Copyright (c) 2010 <NAME>
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require File.expand_path('../../spec_helper', __FILE__)
require 'net/ssh/proxy/http'
require 'net/ssh/proxy/command'
require 'net/ssh/gateway'
require 'fog'
require 'chef/knife/bootstrap'
require 'chef/knife/bootstrap_windows_winrm'
require 'chef/knife/bootstrap_windows_ssh'
describe Chef::Knife::Ec2ServerCreate do
before(:each) do
@knife_ec2_create = Chef::Knife::Ec2ServerCreate.new
@knife_ec2_create.initial_sleep_delay = 0
allow(@knife_ec2_create).to receive(:tcp_test_ssh).and_return(true)
{
:image => 'image',
:ssh_key_name => 'ssh_key_name',
:aws_access_key_id => 'aws_access_key_id',
:aws_secret_access_key => 'aws_secret_access_key'
}.each do |key, value|
Chef::Config[:knife][key] = value
end
@ec2_connection = double(Fog::Compute::AWS)
allow(@ec2_connection).to receive(:tags).and_return double('create', :create => true)
allow(@ec2_connection).to receive_message_chain(:images, :get).and_return double('ami', :root_device_type => 'not_ebs', :platform => 'linux')
allow(@ec2_connection).to receive(:addresses).and_return [double('addesses', {
:domain => 'standard',
:public_ip => '192.168.3.11',
:server_id => nil,
:allocation_id => ''})]
@ec2_servers = double()
@new_ec2_server = double()
@spot_requests = double
@new_spot_request = double
@ec2_server_attribs = { :id => 'i-39382318',
:flavor_id => 'm1.small',
:image_id => 'ami-47241231',
:placement_group => 'some_placement_group',
:availability_zone => 'us-west-1',
:key_name => 'my_ssh_key',
:groups => ['group1', 'group2'],
:security_group_ids => ['sg-00aa11bb'],
:dns_name => 'ec2-75.101.253.10.compute-1.amazonaws.com',
:public_ip_address => '172.16.58.3',
:private_dns_name => 'ip-10-251-75-20.ec2.internal',
:private_ip_address => '10.251.75.20',
:root_device_type => 'not_ebs' }
@spot_request_attribs = { :id => 'test_spot_request_id',
:price => 0.001,
:request_type => 'persistent',
:created_at => '2015-07-14 09:53:11 UTC',
:instance_count => nil,
:instance_id => 'test_spot_instance_id',
:state => 'open',
:key_name => 'ssh_key_name',
:availability_zone => nil,
:flavor_id => 'm1.small',
:image_id => 'image' }
@ec2_server_attribs.each_pair do |attrib, value|
allow(@new_ec2_server).to receive(attrib).and_return(value)
end
@spot_request_attribs.each_pair do |attrib, value|
allow(@new_spot_request).to receive(attrib).and_return(value)
end
@s3_connection = double(Fog::Storage::AWS)
@bootstrap = Chef::Knife::Bootstrap.new
allow(Chef::Knife::Bootstrap).to receive(:new).and_return(@bootstrap)
@validation_key_url = 's3://bucket/foo/bar'
@validation_key_file = '/tmp/a_good_temp_file'
@validation_key_body = "TEST VALIDATION KEY\n"
end
describe "Spot Instance creation" do
before do
allow(Fog::Compute::AWS).to receive(:new).and_return(@ec2_connection)
@knife_ec2_create.config[:spot_price] = 0.001
@knife_ec2_create.config[:spot_request_type] = 'persistent'
allow(@knife_ec2_create).to receive(:puts)
allow(@knife_ec2_create).to receive(:msg_pair)
allow(@knife_ec2_create.ui).to receive(:color).and_return('')
allow(@knife_ec2_create).to receive(:confirm)
@spot_instance_server_def = {
:image_id => "image",
:groups => nil,
:security_group_ids => nil,
:flavor_id => nil,
:key_name => "ssh_key_name",
:availability_zone => nil,
:price => 0.001,
:request_type => 'persistent',
:placement_group => nil,
:iam_instance_profile_name => nil,
:ebs_optimized => "false"
}
allow(@bootstrap).to receive(:run)
end
it "creates a new spot instance request with request type as persistent" do
expect(@ec2_connection).to receive(
:spot_requests).and_return(@spot_requests)
expect(@spot_requests).to receive(
:create).with(@spot_instance_server_def).and_return(@new_spot_request)
@knife_ec2_create.config[:yes] = true
allow(@new_spot_request).to receive(:wait_for).and_return(true)
allow(@ec2_connection).to receive(:servers).and_return(@ec2_servers)
allow(@ec2_servers).to receive(
:get).with(@new_spot_request.instance_id).and_return(@new_ec2_server)
allow(@new_ec2_server).to receive(:wait_for).and_return(true)
@knife_ec2_create.run
expect(@new_spot_request.request_type).to eq('persistent')
end
it "successfully creates a new spot instance" do
allow(@ec2_connection).to receive(
:spot_requests).and_return(@spot_requests)
allow(@spot_requests).to receive(
:create).with(@spot_instance_server_def).and_return(@new_spot_request)
@knife_ec2_create.config[:yes] = true
expect(@new_spot_request).to receive(:wait_for).and_return(true)
expect(@ec2_connection).to receive(:servers).and_return(@ec2_servers)
expect(@ec2_servers).to receive(
:get).with(@new_spot_request.instance_id).and_return(@new_ec2_server)
expect(@new_ec2_server).to receive(:wait_for).and_return(true)
@knife_ec2_create.run
end
it "does not create the spot instance request and creates a regular instance" do
@knife_ec2_create.config.delete(:spot_price)
expect(@ec2_connection).to receive(:servers).and_return(@ec2_servers)
expect(@ec2_servers).to receive(
:create).and_return(@new_ec2_server)
expect(@new_ec2_server).to receive(:wait_for).and_return(true)
@knife_ec2_create.run
end
end
describe "run" do
before do
expect(@ec2_servers).to receive(:create).and_return(@new_ec2_server)
expect(@ec2_connection).to receive(:servers).and_return(@ec2_servers)
expect(@ec2_connection).to receive(:addresses)
@eip = "192.168.3.11"
expect(Fog::Compute::AWS).to receive(:new).and_return(@ec2_connection)
allow(@knife_ec2_create).to receive(:puts)
allow(@knife_ec2_create).to receive(:print)
@knife_ec2_create.config[:image] = '12345'
expect(@bootstrap).to receive(:run)
end
it "defaults to a distro of 'chef-full' for a linux instance" do
expect(@new_ec2_server).to receive(:wait_for).and_return(true)
@knife_ec2_create.config[:distro] = @knife_ec2_create.options[:distro][:default]
expect(@knife_ec2_create).to receive(:default_bootstrap_template).and_return('chef-full')
@knife_ec2_create.run
end
it "creates an EC2 instance and bootstraps it" do
expect(@new_ec2_server).to receive(:wait_for).and_return(true)
expect(@knife_ec2_create).to receive(:ssh_override_winrm)
@knife_ec2_create.run
expect(@knife_ec2_create.server).to_not be_nil
end
it "set ssh_user value by using -x option for ssh bootstrap protocol or linux image" do
# Currently -x option set config[:winrm_user]
# default value of config[:ssh_user] is root
@knife_ec2_create.config[:winrm_user] = "ubuntu"
@knife_ec2_create.config[:ssh_user] = "root"
expect(@new_ec2_server).to receive(:wait_for).and_return(true)
@knife_ec2_create.run
expect(@knife_ec2_create.config[:ssh_user]).to eq("ubuntu")
expect(@knife_ec2_create.server).to_not be_nil
end
it "set ssh_password value by using -P option for ssh bootstrap protocol or linux image" do
# Currently -P option set config[:winrm_password]
# default value of config[:ssh_password] is nil
@knife_ec2_create.config[:winrm_password] = "<PASSWORD>"
@knife_ec2_create.config[:ssh_password] = nil
expect(@new_ec2_server).to receive(:wait_for).and_return(true)
@knife_ec2_create.run
expect(@knife_ec2_create.config[:ssh_password]).to eq("<PASSWORD>")
expect(@knife_ec2_create.server).to_not be_nil
end
it "set ssh_port value by using -p option for ssh bootstrap protocol or linux image" do
# Currently -p option set config[:winrm_port]
# default value of config[:ssh_port] is 22
@knife_ec2_create.config[:winrm_port] = "1234"
@knife_ec2_create.config[:ssh_port] = "22"
expect(@new_ec2_server).to receive(:wait_for).and_return(true)
@knife_ec2_create.run
expect(@knife_ec2_create.config[:ssh_port]).to eq("1234")
expect(@knife_ec2_create.server).to_not be_nil
end
it "set identity_file value by using -i option for ssh bootstrap protocol or linux image" do
# Currently -i option set config[:kerberos_keytab_file]
# default value of config[:identity_file] is nil
@knife_ec2_create.config[:kerberos_keytab_file] = "kerberos_keytab_file"
@knife_ec2_create.config[:identity_file] = nil
expect(@new_ec2_server).to receive(:wait_for).and_return(true)
@knife_ec2_create.run
expect(@knife_ec2_create.config[:identity_file]).to eq("kerberos_keytab_file")
expect(@knife_ec2_create.server).to_not be_nil
end
it "should never invoke windows bootstrap for linux instance" do
expect(@new_ec2_server).to receive(:wait_for).and_return(true)
expect(@knife_ec2_create).not_to receive(:bootstrap_for_windows_node)
@knife_ec2_create.run
end
it "creates an EC2 instance, assigns existing EIP and bootstraps it" do
@knife_ec2_create.config[:associate_eip] = @eip
allow(@new_ec2_server).to receive(:public_ip_address).and_return(@eip)
expect(@ec2_connection).to receive(:associate_address).with(@ec2_server_attribs[:id], @eip, nil, '')
expect(@new_ec2_server).to receive(:wait_for).at_least(:twice).and_return(true)
@knife_ec2_create.run
expect(@knife_ec2_create.server).to_not be_nil
end
it "retries if it receives Fog::Compute::AWS::NotFound" do
expect(@new_ec2_server).to receive(:wait_for).and_return(true)
expect(@knife_ec2_create).to receive(:create_tags).and_raise(Fog::Compute::AWS::NotFound)
expect(@knife_ec2_create).to receive(:create_tags).and_return(true)
expect(@knife_ec2_create).to receive(:sleep).and_return(true)
expect(@knife_ec2_create.ui).to receive(:warn).with(/retrying/)
@knife_ec2_create.run
end
it 'actually writes to the validation key tempfile' do
expect(@new_ec2_server).to receive(:wait_for).and_return(true)
Chef::Config[:knife][:validation_key_url] =
@validation_key_url
@knife_ec2_create.config[:validation_key_url] =
@validation_key_url
allow(@knife_ec2_create).to receive_message_chain(:validation_key_tmpfile, :path).and_return(@validation_key_file)
allow(Chef::Knife::S3Source).to receive(:fetch).with(@validation_key_url).and_return(@validation_key_body)
expect(File).to receive(:open).with(@validation_key_file, 'w')
@knife_ec2_create.run
end
end
describe "run for EC2 Windows instance" do
before do
expect(@ec2_servers).to receive(:create).and_return(@new_ec2_server)
expect(@ec2_connection).to receive(:servers).and_return(@ec2_servers)
expect(@ec2_connection).to receive(:addresses)
expect(Fog::Compute::AWS).to receive(:new).and_return(@ec2_connection)
allow(@knife_ec2_create).to receive(:puts)
allow(@knife_ec2_create).to receive(:print)
@knife_ec2_create.config[:identity_file] = "~/.ssh/aws-key.pem"
@knife_ec2_create.config[:image] = '12345'
allow(@knife_ec2_create).to receive(:is_image_windows?).and_return(true)
allow(@knife_ec2_create).to receive(:tcp_test_winrm).and_return(true)
end
it "bootstraps via the WinRM protocol" do
@knife_ec2_create.config[:winrm_password] = '<PASSWORD>'
@knife_ec2_create.config[:bootstrap_protocol] = 'winrm'
@bootstrap_winrm = Chef::Knife::BootstrapWindowsWinrm.new
allow(Chef::Knife::BootstrapWindowsWinrm).to receive(:new).and_return(@bootstrap_winrm)
expect(@bootstrap_winrm).to receive(:run)
expect(@knife_ec2_create).not_to receive(:ssh_override_winrm)
expect(@new_ec2_server).to receive(:wait_for).and_return(true)
@knife_ec2_create.run
end
it "set default distro to windows-chef-client-msi for windows" do
@knife_ec2_create.config[:winrm_password] = '<PASSWORD>'
@knife_ec2_create.config[:bootstrap_protocol] = 'winrm'
@bootstrap_winrm = Chef::Knife::BootstrapWindowsWinrm.new
allow(Chef::Knife::BootstrapWindowsWinrm).to receive(:new).and_return(@bootstrap_winrm)
expect(@bootstrap_winrm).to receive(:run)
expect(@new_ec2_server).to receive(:wait_for).and_return(true)
allow(@knife_ec2_create).to receive(:is_image_windows?).and_return(true)
expect(@knife_ec2_create).to receive(:default_bootstrap_template).and_return("windows-chef-client-msi")
@knife_ec2_create.run
end
it "bootstraps via the SSH protocol" do
@knife_ec2_create.config[:bootstrap_protocol] = 'ssh'
bootstrap_win_ssh = Chef::Knife::BootstrapWindowsSsh.new
allow(Chef::Knife::BootstrapWindowsSsh).to receive(:new).and_return(bootstrap_win_ssh)
expect(bootstrap_win_ssh).to receive(:run)
expect(@knife_ec2_create).to receive(:ssh_override_winrm)
expect(@new_ec2_server).to receive(:wait_for).and_return(true)
@knife_ec2_create.run
end
it "should use configured SSH port" do
@knife_ec2_create.config[:bootstrap_protocol] = 'ssh'
@knife_ec2_create.config[:ssh_port] = 422
expect(@knife_ec2_create).to receive(:tcp_test_ssh).with('ec2-75.101.253.10.compute-1.amazonaws.com', 422).and_return(true)
bootstrap_win_ssh = Chef::Knife::BootstrapWindowsSsh.new
allow(Chef::Knife::BootstrapWindowsSsh).to receive(:new).and_return(bootstrap_win_ssh)
expect(bootstrap_win_ssh).to receive(:run)
expect(@new_ec2_server).to receive(:wait_for).and_return(true)
@knife_ec2_create.run
end
it "should never invoke linux bootstrap" do
@knife_ec2_create.config[:bootstrap_protocol] = '<PASSWORD>'
allow(@knife_ec2_create).to receive(:windows_password).and_return("")
expect(@knife_ec2_create).not_to receive(:bootstrap_for_linux_node)
expect(@new_ec2_server).to receive(:wait_for).and_return(true)
allow(@knife_ec2_create).to receive(:bootstrap_for_windows_node).and_return double("bootstrap", :run => true)
@knife_ec2_create.run
end
it "waits for EC2 to generate password if not supplied" do
@knife_ec2_create.config[:bootstrap_protocol] = 'winrm'
@knife_ec2_create.config[:winrm_password] = <PASSWORD>
expect(@knife_ec2_create).to receive(:windows_password).and_return("")
allow(@new_ec2_server).to receive(:wait_for).and_return(true)
allow(@knife_ec2_create).to receive(:check_windows_password_available).and_return(true)
bootstrap_winrm = Chef::Knife::BootstrapWindowsWinrm.new
allow(Chef::Knife::BootstrapWindowsWinrm).to receive(:new).and_return(bootstrap_winrm)
expect(bootstrap_winrm).to receive(:run)
@knife_ec2_create.run
end
end
describe "when setting tags" do
before do
expect(Fog::Compute::AWS).to receive(:new).and_return(@ec2_connection)
allow(@knife_ec2_create).to receive(:bootstrap_for_linux_node).and_return double("bootstrap", :run => true)
allow(@ec2_connection).to receive(:servers).and_return(@ec2_servers)
expect(@ec2_connection).to receive(:addresses)
allow(@new_ec2_server).to receive(:wait_for).and_return(true)
allow(@ec2_servers).to receive(:create).and_return(@new_ec2_server)
allow(@knife_ec2_create).to receive(:puts)
allow(@knife_ec2_create).to receive(:print)
end
it "sets the Name tag to the instance id by default" do
expect(@ec2_connection.tags).to receive(:create).with(:key => "Name",
:value => @new_ec2_server.id,
:resource_id => @new_ec2_server.id)
@knife_ec2_create.run
end
it "sets the Name tag to the chef_node_name when given" do
@knife_ec2_create.config[:chef_node_name] = "wombat"
expect(@ec2_connection.tags).to receive(:create).with(:key => "Name",
:value => "wombat",
:resource_id => @new_ec2_server.id)
@knife_ec2_create.run
end
it "sets the Name tag to the specified name when given --tags Name=NAME" do
@knife_ec2_create.config[:tags] = ["Name=bobcat"]
expect(@ec2_connection.tags).to receive(:create).with(:key => "Name",
:value => "bobcat",
:resource_id => @new_ec2_server.id)
@knife_ec2_create.run
end
it "sets arbitrary tags" do
@knife_ec2_create.config[:tags] = ["foo=bar"]
expect(@ec2_connection.tags).to receive(:create).with(:key => "foo",
:value => "bar",
:resource_id => @new_ec2_server.id)
@knife_ec2_create.run
end
end
# This shared examples group can be used to house specifications that
# are common to both the Linux and Windows bootstraping process. This
# would remove a lot of testing duplication that is currently present.
shared_examples "generic bootstrap configurations" do
context "data bag secret" do
before(:each) do
Chef::Config[:knife][:secret] = "sys-knife-secret"
end
it "uses the the knife configuration when no explicit value is provided" do
expect(bootstrap.config[:secret]).to eql("sys-knife-secret")
end
it "prefers using a provided value instead of the knife confiuration" do
subject.config[:secret] = "cli-provided-secret"
expect(bootstrap.config[:secret]).to eql("cli-provided-secret")
end
end
context "data bag secret file" do
before(:each) do
Chef::Config[:knife][:secret_file] = "sys-knife-secret-file"
end
it "uses the the knife configuration when no explicit value is provided" do
expect(bootstrap.config[:secret_file]).to eql("sys-knife-secret-file")
end
it "prefers using a provided value instead of the knife confiuration" do
subject.config[:secret_file] = "cli-provided-secret-file"
expect(bootstrap.config[:secret_file]).to eql("cli-provided-secret-file")
end
end
context 'S3-based secret' do
before(:each) do
Chef::Config[:knife][:s3_secret] =
's3://test.bucket/folder/encrypted_data_bag_secret'
@secret_content = "TEST DATA BAG SECRET\n"
allow(@knife_ec2_create).to receive(:s3_secret).and_return(@secret_content)
end
it 'sets the secret to the expected test string' do
expect(bootstrap.config[:secret]).to eql(@secret_content)
end
end
end
context "when deprecated aws_ssh_key_id option is used in knife config and no ssh-key is supplied on the CLI" do
before do
Chef::Config[:knife][:aws_ssh_key_id] = "mykey"
Chef::Config[:knife].delete(:ssh_key_name)
@aws_key = Chef::Config[:knife][:aws_ssh_key_id]
allow(@knife_ec2_create).to receive(:ami).and_return(false)
end
it "gives warning message and creates the attribute with the required name" do
expect(@knife_ec2_create.ui).to receive(:warn).with("Use of aws_ssh_key_id option in knife.rb config is deprecated, use ssh_key_name option instead.")
@knife_ec2_create.validate!
expect(Chef::Config[:knife][:ssh_key_name]).to eq(@aws_key)
end
end
context "when deprecated aws_ssh_key_id option is used in knife config but ssh-key is also supplied on the CLI" do
before do
Chef::Config[:knife][:aws_ssh_key_id] = "mykey"
@aws_key = Chef::Config[:knife][:aws_ssh_key_id]
allow(@knife_ec2_create).to receive(:ami).and_return(false)
end
it "gives warning message and gives preference to CLI value over knife config's value" do
expect(@knife_ec2_create.ui).to receive(:warn).with("Use of aws_ssh_key_id option in knife.rb config is deprecated, use ssh_key_name option instead.")
@knife_ec2_create.validate!
expect(Chef::Config[:knife][:ssh_key_name]).to_not eq(@aws_key)
end
end
context "when ssh_key_name option is used in knife config instead of deprecated aws_ssh_key_id option" do
before do
Chef::Config[:knife][:ssh_key_name] = "mykey"
allow(@knife_ec2_create).to receive(:ami).and_return(false)
end
it "does nothing" do
@knife_ec2_create.validate!
end
end
context "when ssh_key_name option is used in knife config also it is passed on the CLI" do
before do
allow(Fog::Compute::AWS).to receive(:new).and_return(@ec2_connection)
Chef::Config[:knife][:ssh_key_name] = "mykey"
@knife_ec2_create.config[:ssh_key_name] = "ssh_key_name"
end
it "ssh-key passed over CLI gets preference over knife config value" do
server_def = @knife_ec2_create.create_server_def
expect(server_def[:key_name]).to eq(@knife_ec2_create.config[:ssh_key_name])
end
end
describe "when configuring the bootstrap process" do
before do
@knife_ec2_create.config[:ssh_user] = "ubuntu"
@knife_ec2_create.config[:identity_file] = "~/.ssh/aws-key.pem"
@knife_ec2_create.config[:ssh_port] = 22
@knife_ec2_create.config[:ssh_gateway] = 'bastion.host.com'
@knife_ec2_create.config[:chef_node_name] = "blarf"
@knife_ec2_create.config[:template_file] = '~/.chef/templates/my-bootstrap.sh.erb'
@knife_ec2_create.config[:distro] = 'ubuntu-10.04-magic-sparkles'
@knife_ec2_create.config[:run_list] = ['role[base]']
@knife_ec2_create.config[:json_attributes] = "{'my_attributes':{'foo':'bar'}"
@bootstrap = @knife_ec2_create.bootstrap_for_linux_node(@new_ec2_server, @new_ec2_server.dns_name)
end
include_examples "generic bootstrap configurations" do
subject { @knife_ec2_create }
let(:bootstrap) { @knife_ec2_create.bootstrap_for_linux_node(@new_ec2_server, @new_ec2_server.dns_name) }
end
it "should set the bootstrap 'name argument' to the hostname of the EC2 server" do
expect(@bootstrap.name_args).to eq(['ec2-75.101.253.10.compute-1.amazonaws.com'])
end
it "should set the bootstrap 'first_boot_attributes' correctly" do
expect(@bootstrap.config[:first_boot_attributes]).to eq("{'my_attributes':{'foo':'bar'}")
end
it "configures sets the bootstrap's run_list" do
expect(@bootstrap.config[:run_list]).to eq(['role[base]'])
end
it "configures the bootstrap to use the correct ssh_user login" do
expect(@bootstrap.config[:ssh_user]).to eq('ubuntu')
end
it "configures the bootstrap to use the correct ssh_gateway host" do
expect(@bootstrap.config[:ssh_gateway]).to eq('bastion.host.com')
end
it "configures the bootstrap to use the correct ssh identity file" do
expect(@bootstrap.config[:identity_file]).to eq("~/.ssh/aws-key.pem")
end
it "configures the bootstrap to use the correct ssh_port number" do
expect(@bootstrap.config[:ssh_port]).to eq(22)
end
it "configures the bootstrap to use the configured node name if provided" do
expect(@bootstrap.config[:chef_node_name]).to eq('blarf')
end
it "configures the bootstrap to use the EC2 server id if no explicit node name is set" do
@knife_ec2_create.config[:chef_node_name] = nil
bootstrap = @knife_ec2_create.bootstrap_for_linux_node(@new_ec2_server, @new_ec2_server.dns_name)
expect(bootstrap.config[:chef_node_name]).to eq(@new_ec2_server.id)
end
it "configures the bootstrap to use prerelease versions of chef if specified" do
expect(@bootstrap.config[:prerelease]).to be_falsey
@knife_ec2_create.config[:prerelease] = true
bootstrap = @knife_ec2_create.bootstrap_for_linux_node(@new_ec2_server, @new_ec2_server.dns_name)
expect(bootstrap.config[:prerelease]).to eq(true)
end
it "configures the bootstrap to use the desired distro-specific bootstrap script" do
expect(@bootstrap.config[:distro]).to eq('ubuntu-10.04-magic-sparkles')
end
it "configures the bootstrap to use sudo" do
expect(@bootstrap.config[:use_sudo]).to eq(true)
end
it "configured the bootstrap to use the desired template" do
expect(@bootstrap.config[:template_file]).to eq('~/.chef/templates/my-bootstrap.sh.erb')
end
it "configured the bootstrap to set an ec2 hint (via Chef::Config)" do
expect(Chef::Config[:knife][:hints]["ec2"]).not_to be_nil
end
end
describe "when configuring the ssh bootstrap process for windows" do
before do
allow(@knife_ec2_create).to receive(:fetch_server_fqdn).and_return("SERVERNAME")
@knife_ec2_create.config[:ssh_user] = "administrator"
@knife_ec2_create.config[:ssh_password] = "password"
@knife_ec2_create.config[:ssh_port] = 22
@knife_ec2_create.config[:forward_agent] = true
@knife_ec2_create.config[:bootstrap_protocol] = 'ssh'
@knife_ec2_create.config[:image] = '12345'
allow(@knife_ec2_create).to receive(:is_image_windows?).and_return(true)
@bootstrap = @knife_ec2_create.bootstrap_for_windows_node(@new_ec2_server, @new_ec2_server.dns_name)
end
it "sets the bootstrap 'forward_agent' correctly" do
expect(@bootstrap.config[:forward_agent]).to eq(true)
end
end
describe "when configuring the winrm bootstrap process for windows" do
before do
allow(@knife_ec2_create).to receive(:fetch_server_fqdn).and_return("SERVERNAME")
@knife_ec2_create.config[:winrm_user] = "Administrator"
@knife_ec2_create.config[:winrm_password] = "password"
@knife_ec2_create.config[:winrm_port] = 12345
@knife_ec2_create.config[:winrm_transport] = 'ssl'
@knife_ec2_create.config[:kerberos_realm] = "realm"
@knife_ec2_create.config[:bootstrap_protocol] = 'winrm'
@knife_ec2_create.config[:kerberos_service] = "service"
@knife_ec2_create.config[:chef_node_name] = "blarf"
@knife_ec2_create.config[:template_file] = '~/.chef/templates/my-bootstrap.sh.erb'
@knife_ec2_create.config[:distro] = 'ubuntu-10.04-magic-sparkles'
@knife_ec2_create.config[:run_list] = ['role[base]']
@knife_ec2_create.config[:json_attributes] = "{'my_attributes':{'foo':'bar'}"
@knife_ec2_create.config[:winrm_ssl_verify_mode] = 'basic'
@knife_ec2_create.config[:msi_url] = 'https://opscode-omnibus-packages.s3.amazonaws.com/windows/2008r2/x86_64/chef-client-12.3.0-1.msi'
@knife_ec2_create.config[:install_as_service] = true
@knife_ec2_create.config[:session_timeout] = "90"
@bootstrap = @knife_ec2_create.bootstrap_for_windows_node(@new_ec2_server, @new_ec2_server.dns_name)
end
include_examples "generic bootstrap configurations" do
subject { @knife_ec2_create }
let(:bootstrap) { @knife_ec2_create.bootstrap_for_linux_node(@new_ec2_server, @new_ec2_server.dns_name) }
end
it "should set the winrm username correctly" do
expect(@bootstrap.config[:winrm_user]).to eq(@knife_ec2_create.config[:winrm_user])
end
it "should set the winrm password correctly" do
expect(@bootstrap.config[:winrm_password]).to eq(@knife_ec2_create.config[:winrm_password])
end
it "should set the winrm port correctly" do
expect(@bootstrap.config[:winrm_port]).to eq(@knife_ec2_create.config[:winrm_port])
end
it "should set the winrm transport layer correctly" do
expect(@bootstrap.config[:winrm_transport]).to eq(@knife_ec2_create.config[:winrm_transport])
end
it "should set the kerberos realm correctly" do
expect(@bootstrap.config[:kerberos_realm]).to eq(@knife_ec2_create.config[:kerberos_realm])
end
it "should set the kerberos service correctly" do
expect(@bootstrap.config[:kerberos_service]).to eq(@knife_ec2_create.config[:kerberos_service])
end
it "should set the bootstrap 'name argument' to the Windows/AD hostname of the EC2 server" do
expect(@bootstrap.name_args).to eq(["SERVERNAME"])
end
it "should set the bootstrap 'name argument' to the hostname of the EC2 server when AD/Kerberos is not used" do
@knife_ec2_create.config[:kerberos_realm] = nil
@bootstrap = @knife_ec2_create.bootstrap_for_windows_node(@new_ec2_server, @new_ec2_server.dns_name)
expect(@bootstrap.name_args).to eq(['ec2-75.101.253.10.compute-1.amazonaws.com'])
end
it "should set the bootstrap 'first_boot_attributes' correctly" do
expect(@bootstrap.config[:first_boot_attributes]).to eq("{'my_attributes':{'foo':'bar'}")
end
it "should set the bootstrap 'winrm_ssl_verify_mode' correctly" do
expect(@bootstrap.config[:winrm_ssl_verify_mode]).to eq("basic")
end
it "should set the bootstrap 'msi_url' correctly" do
expect(@bootstrap.config[:msi_url]).to eq('https://opscode-omnibus-packages.s3.amazonaws.com/windows/2008r2/x86_64/chef-client-12.3.0-1.msi')
end
it "should set the bootstrap 'install_as_service' correctly" do
expect(@bootstrap.config[:install_as_service]).to eq(@knife_ec2_create.config[:install_as_service])
end
it "should set the bootstrap 'session_timeout' correctly" do
expect(@bootstrap.config[:session_timeout]).to eq(@knife_ec2_create.config[:session_timeout])
end
it "configures sets the bootstrap's run_list" do
expect(@bootstrap.config[:run_list]).to eq(['role[base]'])
end
it "configures auth_timeout for bootstrap to default to 25 minutes" do
expect(@knife_ec2_create.options[:auth_timeout][:default]).to eq(25)
end
it "configures auth_timeout for bootstrap according to plugin auth_timeout config" do
@knife_ec2_create.config[:auth_timeout] = 5
bootstrap = @knife_ec2_create.bootstrap_for_windows_node(@new_ec2_server, @new_ec2_server.dns_name)
expect(bootstrap.config[:auth_timeout]).to eq(5)
end
end
describe "when validating the command-line parameters" do
before do
allow(Fog::Compute::AWS).to receive(:new).and_return(@ec2_connection)
allow(@knife_ec2_create.ui).to receive(:error)
allow(@knife_ec2_create.ui).to receive(:msg)
end
describe "when reading aws_credential_file" do
before do
Chef::Config[:knife].delete(:aws_access_key_id)
Chef::Config[:knife].delete(:aws_secret_access_key)
Chef::Config[:knife][:aws_credential_file] = '/apple/pear'
@access_key_id = 'access_key_id'
@secret_key = 'secret_key'
end
it "reads UNIX Line endings" do
allow(File).to receive(:read).
and_return("AWSAccessKeyId=#{@access_key_id}\nAWSSecretKey=#{@secret_key}")
@knife_ec2_create.validate!
expect(Chef::Config[:knife][:aws_access_key_id]).to eq(@access_key_id)
expect(Chef::Config[:knife][:aws_secret_access_key]).to eq(@secret_key)
end
it "reads DOS Line endings" do
allow(File).to receive(:read).
and_return("AWSAccessKeyId=#{@access_key_id}\r\nAWSSecretKey=#{@secret_key}")
@knife_ec2_create.validate!
expect(Chef::Config[:knife][:aws_access_key_id]).to eq(@access_key_id)
expect(Chef::Config[:knife][:aws_secret_access_key]).to eq(@secret_key)
end
it "reads UNIX Line endings for new format" do
allow(File).to receive(:read).
and_return("[default]\naws_access_key_id=#{@access_key_id}\naws_secret_access_key=#{@secret_key}")
@knife_ec2_create.validate!
expect(Chef::Config[:knife][:aws_access_key_id]).to eq(@access_key_id)
expect(Chef::Config[:knife][:aws_secret_access_key]).to eq(@secret_key)
end
it "reads DOS Line endings for new format" do
allow(File).to receive(:read).
and_return("[default]\naws_access_key_id=#{@access_key_id}\r\naws_secret_access_key=#{@secret_key}")
@knife_ec2_create.validate!
expect(Chef::Config[:knife][:aws_access_key_id]).to eq(@access_key_id)
expect(Chef::Config[:knife][:aws_secret_access_key]).to eq(@secret_key)
end
it "loads the correct profile" do
Chef::Config[:knife][:aws_profile] = 'other'
allow(File).to receive(:read).
and_return("[default]\naws_access_key_id=TESTKEY\r\naws_secret_access_key=TESTSECRET\n\n[other]\naws_access_key_id=#{@access_key_id}\r\naws_secret_access_key=#{@secret_key}")
@knife_ec2_create.validate!
expect(Chef::Config[:knife][:aws_access_key_id]).to eq(@access_key_id)
expect(Chef::Config[:knife][:aws_secret_access_key]).to eq(@secret_key)
end
end
it 'understands that file:// validation key URIs are just paths' do
Chef::Config[:knife][:validation_key_url] = 'file:///foo/bar'
expect(@knife_ec2_create.validation_key_path).to eq('/foo/bar')
end
it 'returns a path to a tmp file when presented with a URI for the ' \
'validation key' do
Chef::Config[:knife][:validation_key_url] = @validation_key_url
allow(@knife_ec2_create).to receive_message_chain(:validation_key_tmpfile, :path).and_return(@validation_key_file)
expect(@knife_ec2_create.validation_key_path).to eq(@validation_key_file)
end
it "disallows security group names when using a VPC" do
@knife_ec2_create.config[:subnet_id] = 'subnet-1a2b3c4d'
@knife_ec2_create.config[:security_group_ids] = 'sg-aabbccdd'
@knife_ec2_create.config[:security_groups] = 'groupname'
expect { @knife_ec2_create.validate! }.to raise_error SystemExit
end
it "disallows private ips when not using a VPC" do
@knife_ec2_create.config[:private_ip_address] = '10.0.0.10'
expect { @knife_ec2_create.validate! }.to raise_error SystemExit
end
it "disallows specifying credentials file and aws keys" do
Chef::Config[:knife][:aws_credential_file] = '/apple/pear'
allow(File).to receive(:read).and_return("AWSAccessKeyId=b\nAWSSecretKey=a")
expect { @knife_ec2_create.validate! }.to raise_error SystemExit
end
it "disallows associate public ip option when not using a VPC" do
@knife_ec2_create.config[:associate_public_ip] = true
@knife_ec2_create.config[:subnet_id] = nil
expect { @knife_ec2_create.validate! }.to raise_error SystemExit
end
it "disallows ebs provisioned iops option when not using ebs volume type" do
@knife_ec2_create.config[:ebs_provisioned_iops] = "123"
@knife_ec2_create.config[:ebs_volume_type] = nil
expect { @knife_ec2_create.validate! }.to raise_error SystemExit
end
it "disallows ebs provisioned iops option when not using ebs volume type 'io1'" do
@knife_ec2_create.config[:ebs_provisioned_iops] = "123"
@knife_ec2_create.config[:ebs_volume_type] = "standard"
expect { @knife_ec2_create.validate! }.to raise_error SystemExit
end
it "disallows ebs volume type if its other than 'io1' or 'gp2' or 'standard'" do
@knife_ec2_create.config[:ebs_provisioned_iops] = "123"
@knife_ec2_create.config[:ebs_volume_type] = 'invalid'
expect { @knife_ec2_create.validate! }.to raise_error SystemExit
end
it "disallows 'io1' ebs volume type when not using ebs provisioned iops" do
@knife_ec2_create.config[:ebs_provisioned_iops] = nil
@knife_ec2_create.config[:ebs_volume_type] = 'io1'
expect { @knife_ec2_create.validate! }.to raise_error SystemExit
end
context "when ebs_encrypted option specified" do
it "not raise any validation error if valid ebs_size specified" do
@knife_ec2_create.config[:ebs_size] = "8"
@knife_ec2_create.config[:flavor] = "m3.medium"
@knife_ec2_create.config[:ebs_encrypted] = true
expect(@knife_ec2_create.ui).to_not receive(:error).with(" --ebs-encrypted option requires valid --ebs-size to be specified.")
@knife_ec2_create.validate!
end
it "raise error on missing ebs_size" do
@knife_ec2_create.config[:ebs_size] = nil
@knife_ec2_create.config[:flavor] = "m3.medium"
@knife_ec2_create.config[:ebs_encrypted] = true
expect(@knife_ec2_create.ui).to receive(:error).with(" --ebs-encrypted option requires valid --ebs-size to be specified.")
expect { @knife_ec2_create.validate! }.to raise_error SystemExit
end
it "raise error if invalid ebs_size specified for 'standard' VolumeType" do
@knife_ec2_create.config[:ebs_size] = "1055"
@knife_ec2_create.config[:ebs_volume_type] = 'standard'
@knife_ec2_create.config[:flavor] = "m3.medium"
@knife_ec2_create.config[:ebs_encrypted] = true
expect(@knife_ec2_create.ui).to receive(:error).with(" --ebs-size should be in between 1-1024 for 'standard' ebs volume type.")
expect { @knife_ec2_create.validate! }.to raise_error SystemExit
end
it "raise error on invalid ebs_size specified for 'gp2' VolumeType" do
@knife_ec2_create.config[:ebs_size] = "16500"
@knife_ec2_create.config[:ebs_volume_type] = 'gp2'
@knife_ec2_create.config[:flavor] = "m3.medium"
@knife_ec2_create.config[:ebs_encrypted] = true
expect(@knife_ec2_create.ui).to receive(:error).with(" --ebs-size should be in between 1-16384 for 'gp2' ebs volume type.")
expect { @knife_ec2_create.validate! }.to raise_error SystemExit
end
it "raise error on invalid ebs_size specified for 'io1' VolumeType" do
@knife_ec2_create.config[:ebs_size] = "3"
@knife_ec2_create.config[:ebs_provisioned_iops] = "200"
@knife_ec2_create.config[:ebs_volume_type] = 'io1'
@knife_ec2_create.config[:flavor] = "m3.medium"
@knife_ec2_create.config[:ebs_encrypted] = true
expect(@knife_ec2_create.ui).to receive(:error).with(" --ebs-size should be in between 4-16384 for 'io1' ebs volume type.")
expect { @knife_ec2_create.validate! }.to raise_error SystemExit
end
end
end
describe "when creating the connection" do
describe "when use_iam_profile is true" do
before do
Chef::Config[:knife].delete(:aws_access_key_id)
Chef::Config[:knife].delete(:aws_secret_access_key)
end
it "creates a connection without access keys" do
@knife_ec2_create.config[:use_iam_profile] = true
expect(Fog::Compute::AWS).to receive(:new).with(hash_including(:use_iam_profile => true)).and_return(@ec2_connection)
@knife_ec2_create.connection
end
end
describe "when aws_session_token is present" do
it "creates a connection using the session token" do
@knife_ec2_create.config[:aws_session_token] = 'session-<PASSWORD>'
expect(Fog::Compute::AWS).to receive(:new).with(hash_including(:aws_session_token => 'session-token')).and_return(@ec2_connection)
@knife_ec2_create.connection
end
end
end
describe "when creating the server definition" do
before do
allow(Fog::Compute::AWS).to receive(:new).and_return(@ec2_connection)
end
it "sets the specified placement_group" do
@knife_ec2_create.config[:placement_group] = ['some_placement_group']
server_def = @knife_ec2_create.create_server_def
expect(server_def[:placement_group]).to eq(['some_placement_group'])
end
it "sets the specified security group names" do
@knife_ec2_create.config[:security_groups] = ['groupname']
server_def = @knife_ec2_create.create_server_def
expect(server_def[:groups]).to eq(['groupname'])
end
it "sets the specified security group ids" do
@knife_ec2_create.config[:security_group_ids] = ['sg-aabbccdd']
server_def = @knife_ec2_create.create_server_def
expect(server_def[:security_group_ids]).to eq(['sg-aabbccdd'])
end
it "sets the image id from CLI arguments over knife config" do
@knife_ec2_create.config[:image] = "ami-aaa"
Chef::Config[:knife][:image] = "ami-zzz"
server_def = @knife_ec2_create.create_server_def
expect(server_def[:image_id]).to eq("ami-aaa")
end
it "sets the flavor id from CLI arguments over knife config" do
@knife_ec2_create.config[:flavor] = "massive"
Chef::Config[:knife][:flavor] = "bitty"
server_def = @knife_ec2_create.create_server_def
expect(server_def[:flavor_id]).to eq("massive")
end
it "sets the availability zone from CLI arguments over knife config" do
@knife_ec2_create.config[:availability_zone] = "dis-one"
Chef::Config[:knife][:availability_zone] = "dat-one"
server_def = @knife_ec2_create.create_server_def
expect(server_def[:availability_zone]).to eq("dis-one")
end
it "adds the specified ephemeral device mappings" do
@knife_ec2_create.config[:ephemeral] = [ "/dev/sdb", "/dev/sdc", "/dev/sdd", "/dev/sde" ]
server_def = @knife_ec2_create.create_server_def
expect(server_def[:block_device_mapping]).to eq([{ "VirtualName" => "ephemeral0", "DeviceName" => "/dev/sdb" },
{ "VirtualName" => "ephemeral1", "DeviceName" => "/dev/sdc" },
{ "VirtualName" => "ephemeral2", "DeviceName" => "/dev/sdd" },
{ "VirtualName" => "ephemeral3", "DeviceName" => "/dev/sde" }])
end
it "sets the specified private ip address" do
@knife_ec2_create.config[:subnet_id] = 'subnet-1a2b3c4d'
@knife_ec2_create.config[:private_ip_address] = '10.0.0.10'
server_def = @knife_ec2_create.create_server_def
expect(server_def[:subnet_id]).to eq('subnet-1a2b3c4d')
expect(server_def[:private_ip_address]).to eq('10.0.0.10')
end
it "sets the IAM server role when one is specified" do
@knife_ec2_create.config[:iam_instance_profile] = ['iam-role']
server_def = @knife_ec2_create.create_server_def
expect(server_def[:iam_instance_profile_name]).to eq(['iam-role'])
end
it "doesn't set an IAM server role by default" do
server_def = @knife_ec2_create.create_server_def
expect(server_def[:iam_instance_profile_name]).to eq(nil)
end
it "doesn't use IAM profile by default" do
server_def = @knife_ec2_create.create_server_def
expect(server_def[:use_iam_profile]).to eq(nil)
end
it 'Set Tenancy Dedicated when both VPC mode and Flag is True' do
@knife_ec2_create.config[:dedicated_instance] = true
allow(@knife_ec2_create).to receive_messages(:vpc_mode? => true)
server_def = @knife_ec2_create.create_server_def
expect(server_def[:tenancy]).to eq("dedicated")
end
it 'Tenancy should be default with no vpc mode even is specified' do
@knife_ec2_create.config[:dedicated_instance] = true
server_def = @knife_ec2_create.create_server_def
expect(server_def[:tenancy]).to eq(nil)
end
it 'Tenancy should be default with vpc but not requested' do
allow(@knife_ec2_create).to receive_messages(:vpc_mode? => true)
server_def = @knife_ec2_create.create_server_def
expect(server_def[:tenancy]).to eq(nil)
end
it "sets associate_public_ip to true if specified and in vpc_mode" do
@knife_ec2_create.config[:subnet_id] = 'subnet-1a2b3c4d'
@knife_ec2_create.config[:associate_public_ip] = true
server_def = @knife_ec2_create.create_server_def
expect(server_def[:subnet_id]).to eq('subnet-1a2b3c4d')
expect(server_def[:associate_public_ip]).to eq(true)
end
it "sets the spot price" do
@knife_ec2_create.config[:spot_price] = '1.99'
server_def = @knife_ec2_create.create_server_def
expect(server_def[:price]).to eq('1.99')
end
it "sets the spot instance request type as persistent" do
@knife_ec2_create.config[:spot_request_type] = 'persistent'
server_def = @knife_ec2_create.create_server_def
expect(server_def[:request_type]).to eq('persistent')
end
it "sets the spot instance request type as one-time" do
@knife_ec2_create.config[:spot_request_type] = 'one-time'
server_def = @knife_ec2_create.create_server_def
expect(server_def[:request_type]).to eq('one-time')
end
context "when using ebs volume type and ebs provisioned iops rate options" do
before do
allow(@knife_ec2_create).to receive_message_chain(:ami, :root_device_type).and_return("ebs")
allow(@knife_ec2_create).to receive_message_chain(:ami, :block_device_mapping).and_return([{"iops" => 123}])
allow(@knife_ec2_create).to receive(:msg)
allow(@knife_ec2_create).to receive(:puts)
end
it "sets the specified 'standard' ebs volume type" do
@knife_ec2_create.config[:ebs_volume_type] = 'standard'
server_def = @knife_ec2_create.create_server_def
expect(server_def[:block_device_mapping].first['Ebs.VolumeType']).to eq('standard')
end
it "sets the specified 'io1' ebs volume type" do
@knife_ec2_create.config[:ebs_volume_type] = 'io1'
server_def = @knife_ec2_create.create_server_def
expect(server_def[:block_device_mapping].first['Ebs.VolumeType']).to eq('io1')
end
it "sets the specified 'gp2' ebs volume type" do
@knife_ec2_create.config[:ebs_volume_type] = 'gp2'
server_def = @knife_ec2_create.create_server_def
expect(server_def[:block_device_mapping].first['Ebs.VolumeType']).to eq('gp2')
end
it "sets the specified ebs provisioned iops rate" do
@knife_ec2_create.config[:ebs_provisioned_iops] = '1234'
@knife_ec2_create.config[:ebs_volume_type] = 'io1'
server_def = @knife_ec2_create.create_server_def
expect(server_def[:block_device_mapping].first['Ebs.Iops']).to eq('1234')
end
it "disallows non integer ebs provisioned iops rate" do
@knife_ec2_create.config[:ebs_provisioned_iops] = "123abcd"
expect { @knife_ec2_create.create_server_def }.to raise_error SystemExit
end
it "sets the iops rate from ami" do
@knife_ec2_create.config[:ebs_volume_type] = 'io1'
server_def = @knife_ec2_create.create_server_def
expect(server_def[:block_device_mapping].first['Ebs.Iops']).to eq('123')
end
end
end
describe "wait_for_sshd" do
let(:gateway) { 'test.gateway.com' }
let(:hostname) { 'test.host.com' }
it "should wait for tunnelled ssh if a ssh gateway is provided" do
allow(@knife_ec2_create).to receive(:get_ssh_gateway_for).and_return(gateway)
expect(@knife_ec2_create).to receive(:wait_for_tunnelled_sshd).with(gateway, hostname)
@knife_ec2_create.wait_for_sshd(hostname)
end
it "should wait for direct ssh if a ssh gateway is not provided" do
allow(@knife_ec2_create).to receive(:get_ssh_gateway_for).and_return(nil)
@knife_ec2_create.config[:ssh_port] = 22
expect(@knife_ec2_create).to receive(:wait_for_direct_sshd).with(hostname, 22)
@knife_ec2_create.wait_for_sshd(hostname)
end
end
describe "get_ssh_gateway_for" do
let(:gateway) { 'test.gateway.com' }
let(:hostname) { 'test.host.com' }
it "should give precedence to the ssh gateway specified in the knife configuration" do
allow(Net::SSH::Config).to receive(:for).and_return(:proxy => Net::SSH::Proxy::Command.new("ssh some.other.gateway.com nc %h %p"))
@knife_ec2_create.config[:ssh_gateway] = gateway
expect(@knife_ec2_create.get_ssh_gateway_for(hostname)).to eq(gateway)
end
it "should return the ssh gateway specified in the ssh configuration even if the config option is not set" do
# This should already be false, but test this explicitly for regression
@knife_ec2_create.config[:ssh_gateway] = false
allow(Net::SSH::Config).to receive(:for).and_return(:proxy => Net::SSH::Proxy::Command.new("ssh #{gateway} nc %h %p"))
expect(@knife_ec2_create.get_ssh_gateway_for(hostname)).to eq(gateway)
end
it "should return nil if the ssh gateway cannot be parsed from the ssh proxy command" do
allow(Net::SSH::Config).to receive(:for).and_return(:proxy => Net::SSH::Proxy::Command.new("cannot parse host"))
expect(@knife_ec2_create.get_ssh_gateway_for(hostname)).to be_nil
end
it "should return nil if the ssh proxy is not a proxy command" do
allow(Net::SSH::Config).to receive(:for).and_return(:proxy => Net::SSH::Proxy::HTTP.new("httphost.com"))
expect(@knife_ec2_create.get_ssh_gateway_for(hostname)).to be_nil
end
it "returns nil if the ssh config has no proxy" do
allow(Net::SSH::Config).to receive(:for).and_return(:user => "darius")
expect(@knife_ec2_create.get_ssh_gateway_for(hostname)).to be_nil
end
end
describe "ssh_connect_host" do
before(:each) do
allow(@new_ec2_server).to receive_messages(
:dns_name => 'public_name',
:private_ip_address => 'private_ip',
:custom => 'custom',
:public_ip_address => '192.168.3.11'
)
allow(@knife_ec2_create).to receive_messages(:server => @new_ec2_server)
end
describe "by default" do
it 'should use public dns name' do
expect(@knife_ec2_create.ssh_connect_host).to eq('public_name')
end
end
describe "when dns name not exist" do
it 'should use public_ip_address ' do
allow(@new_ec2_server).to receive(:dns_name).and_return(nil)
expect(@knife_ec2_create.ssh_connect_host).to eq('192.168.3.11')
end
end
describe "with vpc_mode?" do
it 'should use private ip' do
allow(@knife_ec2_create).to receive_messages(:vpc_mode? => true)
expect(@knife_ec2_create.ssh_connect_host).to eq('private_ip')
end
end
describe "with custom server attribute" do
it 'should use custom server attribute' do
@knife_ec2_create.config[:server_connect_attribute] = 'custom'
expect(@knife_ec2_create.ssh_connect_host).to eq('custom')
end
end
end
describe "tunnel_test_ssh" do
let(:gateway_host) { 'test.gateway.com' }
let(:gateway) { double('gateway') }
let(:hostname) { 'test.host.com' }
let(:local_port) { 23 }
before(:each) do
allow(@knife_ec2_create).to receive(:configure_ssh_gateway).and_return(gateway)
end
it "should test ssh through a gateway" do
@knife_ec2_create.config[:ssh_port] = 22
expect(gateway).to receive(:open).with(hostname, 22).and_yield(local_port)
expect(@knife_ec2_create).to receive(:tcp_test_ssh).with('localhost', local_port).and_return(true)
expect(@knife_ec2_create.tunnel_test_ssh(gateway_host, hostname)).to eq(true)
end
end
describe "configure_ssh_gateway" do
let(:gateway_host) { 'test.gateway.com' }
let(:gateway_user) { 'gateway_user' }
it "configures a ssh gateway with no user and the default port when the SSH Config is empty" do
allow(Net::SSH::Config).to receive(:for).and_return({})
expect(Net::SSH::Gateway).to receive(:new).with(gateway_host, nil, :port => 22)
@knife_ec2_create.configure_ssh_gateway(gateway_host)
end
it "configures a ssh gateway with the user specified in the SSH Config" do
allow(Net::SSH::Config).to receive(:for).and_return({ :user => gateway_user })
expect(Net::SSH::Gateway).to receive(:new).with(gateway_host, gateway_user, :port => 22)
@knife_ec2_create.configure_ssh_gateway(gateway_host)
end
it "configures a ssh gateway with the user specified in the ssh gateway string" do
allow(Net::SSH::Config).to receive(:for).and_return({ :user => gateway_user })
expect(Net::SSH::Gateway).to receive(:new).with(gateway_host, 'override_user', :port => 22)
@knife_ec2_create.configure_ssh_gateway("override_user@#{gateway_host}")
end
it "configures a ssh gateway with the port specified in the ssh gateway string" do
allow(Net::SSH::Config).to receive(:for).and_return({})
expect(Net::SSH::Gateway).to receive(:new).with(gateway_host, nil, :port => '24')
@knife_ec2_create.configure_ssh_gateway("#{gateway_host}:24")
end
it "configures a ssh gateway with the keys specified in the SSH Config" do
allow(Net::SSH::Config).to receive(:for).and_return({ :keys => ['configuredkey'] })
expect(Net::SSH::Gateway).to receive(:new).with(gateway_host, nil, :port => 22, :keys => ['configuredkey'])
@knife_ec2_create.configure_ssh_gateway(gateway_host)
end
it "configures the ssh gateway with the key specified on the knife config / command line" do
@knife_ec2_create.config[:ssh_gateway_identity] = "/home/fireman/.ssh/gateway.pem"
#Net::SSH::Config.stub(:for).and_return({ :keys => ['configuredkey'] })
expect(Net::SSH::Gateway).to receive(:new).with(gateway_host, nil, :port => 22, :keys => ['/home/fireman/.ssh/gateway.pem'])
@knife_ec2_create.configure_ssh_gateway(gateway_host)
end
it "prefers the knife config over the ssh config for the gateway keys" do
@knife_ec2_create.config[:ssh_gateway_identity] = "/home/fireman/.ssh/gateway.pem"
allow(Net::SSH::Config).to receive(:for).and_return({ :keys => ['not_this_key_dude'] })
expect(Net::SSH::Gateway).to receive(:new).with(gateway_host, nil, :port => 22, :keys => ['/home/fireman/.ssh/gateway.pem'])
@knife_ec2_create.configure_ssh_gateway(gateway_host)
end
end
describe "tcp_test_ssh" do
# Normally we would only get the header after we send a client header, e.g. 'SSH-2.0-client'
it "should return true if we get an ssh header" do
@knife_ec2_create = Chef::Knife::Ec2ServerCreate.new
allow(TCPSocket).to receive(:new).and_return(StringIO.new("SSH-2.0-OpenSSH_6.1p1 Debian-4"))
allow(IO).to receive(:select).and_return(true)
expect(@knife_ec2_create).to receive(:tcp_test_ssh).and_yield.and_return(true)
@knife_ec2_create.tcp_test_ssh("blackhole.ninja", 22) {nil}
end
it "should return false if we do not get an ssh header" do
@knife_ec2_create = Chef::Knife::Ec2ServerCreate.new
allow(TCPSocket).to receive(:new).and_return(StringIO.new(""))
allow(IO).to receive(:select).and_return(true)
expect(@knife_ec2_create.tcp_test_ssh("blackhole.ninja", 22)).to be_falsey
end
it "should return false if the socket isn't ready" do
@knife_ec2_create = Chef::Knife::Ec2ServerCreate.new
allow(TCPSocket).to receive(:new)
allow(IO).to receive(:select).and_return(false)
expect(@knife_ec2_create.tcp_test_ssh("blackhole.ninja", 22)).to be_falsey
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/openstack/models/orchestration/resource.rb
|
require 'fog/core/model'
module Fog
module Orchestration
class OpenStack
class Resource < Fog::Model
include Reflectable
identity :id
%w{resource_name description links logical_resource_id resource_status
updated_time required_by resource_status_reason resource_type}.each do |a|
attribute a.to_sym
end
def events(options={})
@events ||= service.events.all(self, options)
end
def metadata
@metadata ||= service.show_resource_metadata(stack, self.resource_name).body['metadata']
end
def template
@template ||= service.templates.get(self)
end
end
end
end
end
|
arnab0073/idea
|
.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/rvm-1.11.3.9/lib/rvm/environment/cleanup.rb
|
<filename>.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/rvm-1.11.3.9/lib/rvm/environment/cleanup.rb
module RVM
class Environment
# Batch define common operations.
%w(all archives repos sources logs).each do |cleanup_type|
define_method(:"cleanup_#{cleanup_type}") do
rvm(:cleanup, cleanup_type).successful?
end
end
# Returns the ruby-like interface defined by CleanupWrapper
def cleanup
@cleanup_wrapper ||= CleanupWrapper.new(self)
end
# Implements a Ruby-like interface to cleanup, making it nicer to deal with.
class CleanupWrapper
def initialize(parent)
@parent = parent
end
# Cleans up archives, repos, sources and logs
def all
@parent.cleanup_all
end
alias everything all
# Cleans up everything in the archives folder
def archives
@parent.cleanup_archives
end
# Cleans up everything in the repos path
def repos
@parent.cleanup_repos
end
alias repositories repos
# Cleans up everything in the source folder
def sources
@parent.cleanup_sources
end
alias src sources
# Cleans up all of the logs
def logs
@parent.cleanup_logs
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/tktable/spreadsheet.rb
|
#!/usr/bin/env ruby
##
## spreadsheet.rb
##
## This demos shows how you can simulate a 3D table
## and has other basic features to begin a basic spreadsheet
##
## ( based on 'spreadsheet.tcl' included source archive of tktable extension )
##
require 'tk'
require 'tkextlib/tktable'
rows = 10
cols = 10
cur_var = TkVariable.new
table_list = Hash.new{|hash, key| hash[key] = TkVariable.new_hash}
page = TkVariable.new('AA')
color = Hash.new('pink')
color['AA'] = 'orange'
color['BB'] = 'blue'
color['CC'] = 'green'
def colorize(num)
num = Integer(num)
return 'colored' if (num > 0 && num % 2 == 1)
end
def fill_table(tbl_list, page, r=10, c=10)
ary = tbl_list[page]
(0...r).each{|i|
(0...c).each{|j|
if i!=0 && j!=0
ary[i,j] = "#{page} #{i},#{j}"
elsif i!=0
ary[i,j] = i.to_s
else
ary[i,j] = (64+j).chr
end
}
}
end
def changepage(tbl_list, tbl, ent, col, var, elem, op)
if elem != ''
page = var[elem]
else
page = var.value
end
if tbl[:variable] != tbl_list[page].id
tbl.selection_clear_all
tbl.variable(tbl_list[page])
ent.textvariable(tbl_list[page].ref('active'))
tbl.activate('origin')
tbl.tag_configure('colored', :bg=>col[page])
tbl.see('active')
end
end
lbl = TkLabel.new(:text=>"TkTable v1 Spreadsheet Example")
current = TkLabel.new(:textvariable=>cur_var, :width=>5)
entry = TkEntry.new(:textvariable=>table_list[page.value].ref('active'))
lpage = TkLabel.new(:text=>'PAGE:', :width=>6, :anchor=>:e)
optmenu = TkOptionMenubutton.new(page, *(%w(AA BB CC DD)))
fill_table(table_list, page.value)
fill_table(table_list, 'BB', Integer(rows/2), Integer(cols/2))
table = Tk::TkTable.new(:rows=>rows, :cols=>cols, :width=>5, :height=>5,
:variable=>table_list[page.value],
:titlerows=>1, :titlecols=>1,
:coltagcommand=>proc{|n| colorize(n)},
:flashmode=>true, :selectmode=>:extended,
:colstretch=>:unset, :rowstretch=>:unset,
:browsecommand=>proc{|e| cur_var.value = e.new_index})
page.trace(:w, proc{|var, elem, op|
changepage(table_list, table, entry, color, var, elem, op)
})
table.tag_configure('colored', :bg=>color[page.value])
table.tag_configure('title', :fg=>'red', :relief=>:groove)
table.tag_configure('blue', :bg=>'blue')
table.tag_configure('green', :bg=>'green')
table.tag_cell('green', [6,3], [5,7], [4,9])
table.tag_cell('blue', [8,8])
table.tag_row('blue', 7)
table.tag_col('blue', 6, 8)
table.set_width([0, 3], [2, 7])
sx = table.xscrollbar(TkScrollbar.new)
sy = table.yscrollbar(TkScrollbar.new)
btn = TkButton.new(:text=>'Exit', :command=>proc{exit})
Tk.grid(lbl, '-', '-', '-', '-', :sticky=>:ew)
Tk.grid(current, entry, lpage, optmenu, '-', :sticky=>:ew)
Tk.grid(table, '-', '-', '-', sy, :sticky=>:ns)
Tk.grid(sx, '-', '-', '-', :sticky=>:ew)
Tk.grid(btn, '-', '-', '-', '-', :sticky=>:ew)
Tk.root.grid_columnconfig(1, :weight=>1)
Tk.root.grid_rowconfig(2, :weight=>1)
table.grid_configure(:sticky=>:news)
entry.bind('Return', proc{
r = table.row_index(:active)
c = table.col_index(:active)
rmax = table[:rows]
cmax = table[:cols]
c += 1
if c == cmax
c = table[:titlecols]
r += 1
if r == rmax
r = table[:titlerows]
end
end
table.activate([r, c])
table.see('active')
})
menu = TkMenu.new
m_file = TkMenu.new(menu)
Tk.root.menu(menu)
menu.add(:cascade, :label=>'File', :underline=>0, :menu=>m_file)
m_file.add(:command, :label=>'Fill Array',
:command=>proc{ fill_table(table_list, page.value) })
m_file.add(:command, :label=>'Quit', :command=>proc{exit})
puts "Table is #{table.path} with array #{(table['variable'])}"
Tk.mainloop
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/mixlib-log-1.6.0/mixlib-log.gemspec
|
<filename>.rvm/gems/ruby-2.3.0/gems/mixlib-log-1.6.0/mixlib-log.gemspec
$:.unshift File.expand_path('../lib', __FILE__)
require 'mixlib/log/version'
Gem::Specification.new do |gem|
gem.name = "mixlib-log"
gem.version = Mixlib::Log::VERSION
gem.platform = Gem::Platform::RUBY
gem.summary = "A gem that provides a simple mixin for log functionality"
gem.email = "<EMAIL>"
gem.homepage = "http://www.opscode.com"
gem.authors = ["Opscode, Inc."]
gem.has_rdoc = true
gem.extra_rdoc_files = ["README.rdoc", "LICENSE", 'NOTICE']
gem.files = Dir['lib/**/*'] + Dir['spec/**/*'] + ["Rakefile", ".gemtest", "mixlib-log.gemspec"]
gem.add_development_dependency 'rake'
gem.add_development_dependency 'rspec', '~> 2.10'
gem.add_development_dependency 'cucumber'
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/remote-tk.rb
|
#
# remote-tk.rb - supports to control remote Tk interpreters
# by <NAME> <<EMAIL>>
if defined? MultiTkIp
fail RuntimeError, "'remote-tk' library must be required before requiring 'multi-tk'"
end
class MultiTkIp; end
class RemoteTkIp < MultiTkIp; end
class MultiTkIp
@@IP_TABLE = TkUtil.untrust({}) unless defined?(@@IP_TABLE)
@@TK_TABLE_LIST = TkUtil.untrust([]) unless defined?(@@TK_TABLE_LIST)
def self._IP_TABLE; @@IP_TABLE; end
def self._TK_TABLE_LIST; @@TK_TABLE_LIST; end
@flag = true
def self._DEFAULT_MASTER
# work only once
if @flag
@flag = nil
@@DEFAULT_MASTER
else
nil
end
end
end
class RemoteTkIp
@@IP_TABLE = MultiTkIp._IP_TABLE unless defined?(@@IP_TABLE)
@@TK_TABLE_LIST = MultiTkIp._TK_TABLE_LIST unless defined?(@@TK_TABLE_LIST)
end
class << MultiTkIp
undef _IP_TABLE
undef _TK_TABLE_LIST
end
require 'multi-tk'
class RemoteTkIp
if defined?(@@DEFAULT_MASTER)
MultiTkIp._DEFAULT_MASTER
else
@@DEFAULT_MASTER = MultiTkIp._DEFAULT_MASTER
end
end
###############################
class << RemoteTkIp
undef new_master, new_slave, new_safe_slave
undef new_trusted_slave, new_safeTk
def new(*args, &b)
ip = __new(*args)
ip.eval_proc(&b) if b
ip
end
end
class RemoteTkIp
def initialize(remote_ip, displayof=nil, timeout=5)
if $SAFE >= 4
fail SecurityError, "cannot access another interpreter at level #{$SAFE}"
end
@interp = MultiTkIp.__getip
if @interp.safe?
fail SecurityError, "safe-IP cannot create RemoteTkIp"
end
@interp.allow_ruby_exit = false
@appname = @interp._invoke('tk', 'appname')
@remote = remote_ip.to_s.dup.freeze
if displayof.kind_of?(TkWindow)
@displayof = displayof.path.dup.freeze
else
@displayof = nil
end
if self.deleted?
fail RuntimeError, "no Tk application named \"#{@remote}\""
end
@tk_windows = {}
@tk_table_list = []
@slave_ip_tbl = {}
@slave_ip_top = {}
@force_default_encoding ||= TkUtil.untrust([false])
@encoding ||= TkUtil.untrust([nil])
def @encoding.to_s; self.join(nil); end
TkUtil.untrust(@tk_windows) unless @tk_windows.tainted?
TkUtil.untrust(@tk_table_list) unless @tk_table_list.tainted?
TkUtil.untrust(@slave_ip_tbl) unless @slave_ip_tbl.tainted?
TkUtil.untrust(@slave_ip_top) unless @slave_ip_top.tainted?
@system = Object.new
@threadgroup = ThreadGroup.new
@safe_level = [$SAFE]
@wait_on_mainloop = [true, 0]
@cmd_queue = Queue.new
=begin
@cmd_receiver, @receiver_watchdog = _create_receiver_and_watchdog()
@threadgroup.add @cmd_receiver
@threadgroup.add @receiver_watchdog
@threadgroup.enclose
=end
@@DEFAULT_MASTER.assign_receiver_and_watchdog(self)
@@IP_TABLE[@threadgroup] = self
@@TK_TABLE_LIST.size.times{
(tbl = {}).tainted? || TkUtil.untrust(tbl)
@tk_table_list << tbl
}
@ret_val = TkVariable.new
if timeout > 0 && ! _available_check(timeout)
fail RuntimeError, "cannot create connection"
end
@ip_id = _create_connection
class << self
undef :instance_eval
end
self.freeze # defend against modification
end
def manipulable?
return true if (Thread.current.group == ThreadGroup::Default)
MultiTkIp.__getip == @interp && ! @interp.safe?
end
def self.manipulable?
true
end
def _is_master_of?(tcltkip_obj)
tcltkip_obj == @interp
end
protected :_is_master_of?
def _ip_id_
@ip_id
end
def _available_check(timeout = 5)
raise SecurityError, "no permission to manipulate" unless self.manipulable?
return nil if timeout < 1
@ret_val.value = ''
@interp._invoke('send', '-async', @remote,
'send', '-async', Tk.appname,
"set #{@ret_val.id} ready")
Tk.update
if @ret_val != 'ready'
(1..(timeout*5)).each{
sleep 0.2
Tk.update
break if @ret_val == 'ready'
}
end
@ret_val.value == 'ready'
end
private :_available_check
def _create_connection
raise SecurityError, "no permission to manipulate" unless self.manipulable?
ip_id = '_' + @interp._invoke('send', @remote, <<-'EOS') + '_'
if {[catch {set _rubytk_control_ip_id_} ret] != 0} {
set _rubytk_control_ip_id_ 0
} else {
set _rubytk_control_ip_id_ [expr $ret + 1]
}
return $_rubytk_control_ip_id_
EOS
@interp._invoke('send', @remote, <<-EOS)
proc rb_out#{ip_id} args {
send #{@appname} rb_out \$args
}
EOS
ip_id
end
private :_create_connection
def _appsend(enc_mode, async, *cmds)
raise SecurityError, "no permission to manipulate" unless self.manipulable?
p ['_appsend', [@remote, @displayof], enc_mode, async, cmds] if $DEBUG
if $SAFE >= 4
fail SecurityError, "cannot send commands at level 4"
elsif $SAFE >= 1 && cmds.find{|obj| obj.tainted?}
fail SecurityError, "cannot send tainted commands at level #{$SAFE}"
end
cmds = @interp._merge_tklist(*TkUtil::_conv_args([], enc_mode, *cmds))
if @displayof
if async
@interp.__invoke('send', '-async', '-displayof', @displayof,
'--', @remote, *cmds)
else
@interp.__invoke('send', '-displayof', @displayof,
'--', @remote, *cmds)
end
else
if async
@interp.__invoke('send', '-async', '--', @remote, *cmds)
else
@interp.__invoke('send', '--', @remote, *cmds)
end
end
end
private :_appsend
def ready?(timeout=5)
if timeout < 0
fail ArgumentError, "timeout must be positive number"
end
_available_check(timeout)
end
def is_rubytk?
return false if _appsend(false, false, 'info', 'command', 'ruby') == ""
[ _appsend(false, false, 'ruby', 'RUBY_VERSION'),
_appsend(false, false, 'set', 'tk_patchLevel') ]
end
def appsend(async, *args)
raise SecurityError, "no permission to manipulate" unless self.manipulable?
if async != true && async != false && async != nil
args.unshift(async)
async = false
end
if @displayof
Tk.appsend_displayof(@remote, @displayof, async, *args)
else
Tk.appsend(@remote, async, *args)
end
end
def rb_appsend(async, *args)
raise SecurityError, "no permission to manipulate" unless self.manipulable?
if async != true && async != false && async != nil
args.unshift(async)
async = false
end
if @displayof
Tk.rb_appsend_displayof(@remote, @displayof, async, *args)
else
Tk.rb_appsend(@remote, async, *args)
end
end
def create_slave(name, safe=false)
if safe
safe_opt = ''
else
safe_opt = '-safe'
end
_appsend(false, false, "interp create #{safe_opt} -- #{name}")
end
def make_safe
fail RuntimeError, 'cannot change safe mode of the remote interpreter'
end
def safe?
_appsend(false, false, 'interp issafe')
end
def safe_base?
false
end
def allow_ruby_exit?
false
end
def allow_ruby_exit= (mode)
fail RuntimeError, 'cannot change mode of the remote interpreter'
end
def delete
_appsend(false, true, 'exit')
end
def deleted?
raise SecurityError, "no permission to manipulate" unless self.manipulable?
if @displayof
lst = @interp._invoke_without_enc('winfo', 'interps',
'-displayof', @displayof)
else
lst = @interp._invoke_without_enc('winfo', 'interps')
end
# unless @interp._split_tklist(lst).index(@remote)
unless @interp._split_tklist(lst).index(_toUTF8(@remote))
true
else
false
end
end
def has_mainwindow?
raise SecurityError, "no permission to manipulate" unless self.manipulable?
begin
inf = @interp._invoke_without_enc('info', 'command', '.')
rescue Exception
return nil
end
if !inf.kind_of?(String) || inf != '.'
false
else
true
end
end
def invalid_namespace?
false
end
def restart
fail RuntimeError, 'cannot restart the remote interpreter'
end
def __eval(str)
_appsend(false, false, str)
end
def _eval(str)
_appsend(nil, false, str)
end
def _eval_without_enc(str)
_appsend(false, false, str)
end
def _eval_with_enc(str)
_appsend(true, false, str)
end
def _invoke(*args)
_appsend(nil, false, *args)
end
def __invoke(*args)
_appsend(false, false, *args)
end
def _invoke(*args)
_appsend(nil, false, *args)
end
def _invoke_without_enc(*args)
_appsend(false, false, *args)
end
def _invoke_with_enc(*args)
_appsend(true, false, *args)
end
def _toUTF8(str, encoding=nil)
raise SecurityError, "no permission to manipulate" unless self.manipulable?
@interp._toUTF8(str, encoding)
end
def _fromUTF8(str, encoding=nil)
raise SecurityError, "no permission to manipulate" unless self.manipulable?
@interp._fromUTF8(str, encoding)
end
def _thread_vwait(var_name)
_appsend(false, 'thread_vwait', varname)
end
def _thread_tkwait(mode, target)
_appsend(false, 'thread_tkwait', mode, target)
end
def _return_value
raise SecurityError, "no permission to manipulate" unless self.manipulable?
@interp._return_value
end
def _get_variable(var_name, flag)
# ignore flag
_appsend(false, 'set', TkComm::_get_eval_string(var_name))
end
def _get_variable2(var_name, index_name, flag)
# ignore flag
_appsend(false, 'set', "#{TkComm::_get_eval_string(var_name)}(#{TkComm::_get_eval_string(index_name)})")
end
def _set_variable(var_name, value, flag)
# ignore flag
_appsend(false, 'set', TkComm::_get_eval_string(var_name), TkComm::_get_eval_string(value))
end
def _set_variable2(var_name, index_name, value, flag)
# ignore flag
_appsend(false, 'set', "#{TkComm::_get_eval_string(var_name)}(#{TkComm::_get_eval_string(index_name)})", TkComm::_get_eval_string(value))
end
def _unset_variable(var_name, flag)
# ignore flag
_appsend(false, 'unset', TkComm::_get_eval_string(var_name))
end
def _unset_variable2(var_name, index_name, flag)
# ignore flag
_appsend(false, 'unset', "#{var_name}(#{index_name})")
end
def _get_global_var(var_name)
_appsend(false, 'set', TkComm::_get_eval_string(var_name))
end
def _get_global_var2(var_name, index_name)
_appsend(false, 'set', "#{TkComm::_get_eval_string(var_name)}(#{TkComm::_get_eval_string(index_name)})")
end
def _set_global_var(var_name, value)
_appsend(false, 'set', TkComm::_get_eval_string(var_name), TkComm::_get_eval_string(value))
end
def _set_global_var2(var_name, index_name, value)
_appsend(false, 'set', "#{TkComm::_get_eval_string(var_name)}(#{TkComm::_get_eval_string(index_name)})", TkComm::_get_eval_string(value))
end
def _unset_global_var(var_name)
_appsend(false, 'unset', TkComm::_get_eval_string(var_name))
end
def _unset_global_var2(var_name, index_name)
_appsend(false, 'unset', "#{var_name}(#{index_name})")
end
def _split_tklist(str)
raise SecurityError, "no permission to manipulate" unless self.manipulable?
@interp._split_tklist(str)
end
def _merge_tklist(*args)
raise SecurityError, "no permission to manipulate" unless self.manipulable?
@interp._merge_tklist(*args)
end
def _conv_listelement(str)
raise SecurityError, "no permission to manipulate" unless self.manipulable?
@interp._conv_listelement(str)
end
def _create_console
fail RuntimeError, 'not support "_create_console" on the remote interpreter'
end
def mainloop
fail RuntimeError, 'not support "mainloop" on the remote interpreter'
end
def mainloop_watchdog
fail RuntimeError, 'not support "mainloop_watchdog" on the remote interpreter'
end
def do_one_event(flag = nil)
fail RuntimeError, 'not support "do_one_event" on the remote interpreter'
end
def mainloop_abort_on_exception
fail RuntimeError, 'not support "mainloop_abort_on_exception" on the remote interpreter'
end
def mainloop_abort_on_exception=(mode)
fail RuntimeError, 'not support "mainloop_abort_on_exception=" on the remote interpreter'
end
def set_eventloop_tick(*args)
fail RuntimeError, 'not support "set_eventloop_tick" on the remote interpreter'
end
def get_eventloop_tick
fail RuntimeError, 'not support "get_eventloop_tick" on the remote interpreter'
end
def set_no_event_wait(*args)
fail RuntimeError, 'not support "set_no_event_wait" on the remote interpreter'
end
def get_no_event_wait
fail RuntimeError, 'not support "get_no_event_wait" on the remote interpreter'
end
def set_eventloop_weight(*args)
fail RuntimeError, 'not support "set_eventloop_weight" on the remote interpreter'
end
def get_eventloop_weight
fail RuntimeError, 'not support "get_eventloop_weight" on the remote interpreter'
end
end
class << RemoteTkIp
def mainloop(*args)
fail RuntimeError, 'not support "mainloop" on the remote interpreter'
end
def mainloop_watchdog(*args)
fail RuntimeError, 'not support "mainloop_watchdog" on the remote interpreter'
end
def do_one_event(flag = nil)
fail RuntimeError, 'not support "do_one_event" on the remote interpreter'
end
def mainloop_abort_on_exception
fail RuntimeError, 'not support "mainloop_abort_on_exception" on the remote interpreter'
end
def mainloop_abort_on_exception=(mode)
fail RuntimeError, 'not support "mainloop_abort_on_exception=" on the remote interpreter'
end
def set_eventloop_tick(*args)
fail RuntimeError, 'not support "set_eventloop_tick" on the remote interpreter'
end
def get_eventloop_tick
fail RuntimeError, 'not support "get_eventloop_tick" on the remote interpreter'
end
def set_no_event_wait(*args)
fail RuntimeError, 'not support "set_no_event_wait" on the remote interpreter'
end
def get_no_event_wait
fail RuntimeError, 'not support "get_no_event_wait" on the remote interpreter'
end
def set_eventloop_weight(*args)
fail RuntimeError, 'not support "set_eventloop_weight" on the remote interpreter'
end
def get_eventloop_weight
fail RuntimeError, 'not support "get_eventloop_weight" on the remote interpreter'
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/openstack/models/orchestration/templates.rb
|
require 'fog/openstack/models/orchestration/template'
module Fog
module Orchestration
class OpenStack
class Templates < Fog::Collection
model Fog::Orchestration::OpenStack::Template
def get(obj)
data = if obj.is_a?(Stack)
service.get_stack_template(obj).body
else
service.show_resource_template(obj.resource_name).body
end
if data.has_key?('AWSTemplateFormatVersion')
data['content'] = data.to_json
data['format'] = 'CFN'
data['template_version'] = data.delete('AWSTemplateFormatVersion')
data['description'] = data.delete('Description')
data['parameter'] = data.delete('Parameters')
data['resources'] = data.delete('Resources')
else
data['content'] = data.to_yaml
data['format'] = 'HOT'
data['template_version'] = data.delete('heat_template_version')
end
new(data)
rescue Fog::Compute::OpenStack::NotFound
nil
end
def validate(options={})
data = service.validate_template(options).body
temp = new
temp.parameters = data['Parameters']
temp.description = data['Description']
temp
end
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/bwidget/entry.rb
|
#
# tkextlib/bwidget/entry.rb
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tk/entry'
require 'tkextlib/bwidget.rb'
module Tk
module BWidget
class Entry < Tk::Entry
end
end
end
class Tk::BWidget::Entry
include Scrollable
TkCommandNames = ['Entry'.freeze].freeze
WidgetClassName = 'Entry'.freeze
WidgetClassNames[WidgetClassName] ||= self
def __strval_optkeys
super() << 'helptext' << 'insertbackground'
end
private :__strval_optkeys
def __boolval_optkeys
super() << 'dragenabled' << 'dropenabled' << 'editable'
end
private :__boolval_optkeys
def __tkvariable_optkeys
super() << 'helpvar'
end
private :__tkvariable_optkeys
def invoke
tk_send_without_enc('invoke')
self
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/lib/xmlrpc/utils.rb
|
<gh_stars>0
# frozen_string_literal: false
#
# Copyright (C) 2001, 2002, 2003 by <NAME> (<EMAIL>)
#
# $Id: utils.rb 53141 2015-12-16 05:07:31Z naruse $
#
module XMLRPC # :nodoc:
# This module enables a user-class to be marshalled
# by XML-RPC for Ruby into a Hash, with one additional
# key/value pair <code>___class___ => ClassName</code>
#
module Marshallable
end
# Defines ParserWriterChooseMixin, which makes it possible to choose a
# different XMLWriter and/or XMLParser then the default one.
#
# The Mixin is used in client.rb (class XMLRPC::Client)
# and server.rb (class XMLRPC::BasicServer)
module ParserWriterChooseMixin
# Sets the XMLWriter to use for generating XML output.
#
# Should be an instance of a class from module XMLRPC::XMLWriter.
#
# If this method is not called, then XMLRPC::Config::DEFAULT_WRITER is used.
def set_writer(writer)
@create = Create.new(writer)
self
end
# Sets the XMLParser to use for parsing XML documents.
#
# Should be an instance of a class from module XMLRPC::XMLParser.
#
# If this method is not called, then XMLRPC::Config::DEFAULT_PARSER is used.
def set_parser(parser)
@parser = parser
self
end
private
def create
# if set_writer was not already called then call it now
if @create.nil? then
set_writer(Config::DEFAULT_WRITER.new)
end
@create
end
def parser
# if set_parser was not already called then call it now
if @parser.nil? then
set_parser(Config::DEFAULT_PARSER.new)
end
@parser
end
end # module ParserWriterChooseMixin
module Service
# Base class for XMLRPC::Service::Interface definitions, used
# by XMLRPC::BasicServer#add_handler
class BasicInterface
attr_reader :prefix, :methods
def initialize(prefix)
@prefix = prefix
@methods = []
end
def add_method(sig, help=nil, meth_name=nil)
mname = nil
sig = [sig] if sig.kind_of? String
sig = sig.collect do |s|
name, si = parse_sig(s)
raise "Wrong signatures!" if mname != nil and name != mname
mname = name
si
end
@methods << [mname, meth_name || mname, sig, help]
end
private
def parse_sig(sig)
# sig is a String
if sig =~ /^\s*(\w+)\s+([^(]+)(\(([^)]*)\))?\s*$/
params = [$1]
name = $2.strip
$4.split(",").each {|i| params << i.strip} if $4 != nil
return name, params
else
raise "Syntax error in signature"
end
end
end # class BasicInterface
#
# Class which wraps a XMLRPC::Service::Interface definition, used
# by XMLRPC::BasicServer#add_handler
#
class Interface < BasicInterface
def initialize(prefix, &p)
raise "No interface specified" if p.nil?
super(prefix)
instance_eval(&p)
end
def get_methods(obj, delim=".")
prefix = @prefix + delim
@methods.collect { |name, meth, sig, help|
[prefix + name.to_s, obj.method(meth).to_proc, sig, help]
}
end
private
def meth(*a)
add_method(*a)
end
end # class Interface
class PublicInstanceMethodsInterface < BasicInterface
def initialize(prefix)
super(prefix)
end
def get_methods(obj, delim=".")
prefix = @prefix + delim
obj.class.public_instance_methods(false).collect { |name|
[prefix + name.to_s, obj.method(name).to_proc, nil, nil]
}
end
end
end # module Service
#
# Short-form to create a XMLRPC::Service::Interface
#
def self.interface(prefix, &p)
Service::Interface.new(prefix, &p)
end
# Short-cut for creating a XMLRPC::Service::PublicInstanceMethodsInterface
def self.iPIMethods(prefix)
Service::PublicInstanceMethodsInterface.new(prefix)
end
module ParseContentType
def parse_content_type(str)
a, *b = str.split(";")
return a.strip.downcase, *b
end
end
end # module XMLRPC
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/rdoc/test_rdoc_parser_rd.rb
|
<gh_stars>10-100
# frozen_string_literal: false
require 'rdoc/test_case'
class TestRDocParserRd < RDoc::TestCase
def setup
super
@RP = RDoc::Parser
@tempfile = Tempfile.new self.class.name
filename = @tempfile.path
@top_level = @store.add_file filename
@fn = filename
@options = RDoc::Options.new
@stats = RDoc::Stats.new @store, 0
end
def teardown
super
@tempfile.close!
end
def test_file
assert_kind_of RDoc::Parser::Text, util_parser('')
end
def test_class_can_parse
temp_dir do
FileUtils.touch 'foo.rd'
assert_equal @RP::RD, @RP.can_parse('foo.rd')
FileUtils.touch 'foo.rd.ja'
assert_equal @RP::RD, @RP.can_parse('foo.rd.ja')
end
end
def test_scan
parser = util_parser 'it ((*really*)) works'
expected = doc(para('it <em>really</em> works'))
expected.file = @top_level
parser.scan
assert_equal expected, @top_level.comment.parse
end
def util_parser content
RDoc::Parser::RD.new @top_level, @fn, content, @options, @stats
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/iwidgets/toolbar.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/iwidgets/toolbar.rb
#
# tkextlib/iwidgets/toolbar.rb
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tkextlib/iwidgets.rb'
module Tk
module Iwidgets
class Toolbar < Tk::Itk::Widget
end
end
end
class Tk::Iwidgets::Toolbar
TkCommandNames = ['::iwidgets::toolbar'.freeze].freeze
WidgetClassName = 'Toolbar'.freeze
WidgetClassNames[WidgetClassName] ||= self
def __tkvariable_optkeys
super() << 'helpvariable'
end
private :__tkvariable_optkeys
####################################
include TkItemConfigMethod
def __item_cget_cmd(id)
[self.path, 'itemcget', self.index(id)]
end
private :__item_cget_cmd
def __item_config_cmd(id)
[self.path, 'itemconfigure', self.index(id)]
end
private :__item_config_cmd
def __item_strval_optkeys(id)
super(id) << 'helpstr' << 'balloonstr'
end
private :__item_strval_optkeys
def tagid(tagOrId)
if tagOrId.kind_of?(Tk::Itk::Component)
tagOrId.name
else
#_get_eval_string(tagOrId)
tagOrId
end
end
####################################
def __strval_optkeys
super() << 'balloonbackground' << 'balloonforeground'
end
private :__strval_optkeys
def __tkvariable_optkeys
super() << 'helpvariable'
end
private :__tkvariable_optkeys
def __font_optkeys
super() << 'balloonfont'
end
private :__font_optkeys
def add(type, tag=nil, keys={})
if tag.kind_of?(Hash)
keys = tag
tag = nil
end
if tag
tag = Tk::Itk::Component.new(self, tagid(tag))
else
tag = Tk::Itk::Component.new(self)
end
window(tk_call(@path, 'add', type, tagid(tag), *hash_kv(keys)))
tag
end
def delete(idx1, idx2=nil)
if idx2
tk_call(@path, 'delete', index(idx1), index(idx2))
else
tk_call(@path, 'delete', index(idx1))
end
self
end
def index(idx)
number(tk_call(@path, 'index', tagid(idx)))
end
def insert(idx, type, tag=nil, keys={})
if tag.kind_of?(Hash)
keys = tag
tag = nil
end
if tag
tag = Tk::Itk::Component.new(self, tagid(tag))
else
tag = Tk::Itk::Component.new(self)
end
window(tk_call(@path, 'insert', index(idx), type,
tagid(tag), *hash_kv(keys)))
tag
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/lib/ohai/plugins/java.rb
|
<filename>.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/lib/ohai/plugins/java.rb
#
# Author:: <NAME> (<<EMAIL>>)
# Copyright:: Copyright (c) 2009 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
provides "languages/java"
require_plugin "languages"
java = Mash.new
status, stdout, stderr = nil
if RUBY_PLATFORM.downcase.include?("darwin")
if system("/usr/libexec/java_home 2>&1 >/dev/null")
status, stdout, stderr = run_command(:no_status_check => true, :command => "java -version")
end
else
status, stdout, stderr = run_command(:no_status_check => true, :command => "java -version")
end
if status == 0
stderr.split("\n").each do |line|
case line
when /java version \"([0-9\.\_]+)\"/
java[:version] = $1
when /^(.+Runtime Environment.*) \((build )?(.+)\)$/
java[:runtime] = { "name" => $1, "build" => $3 }
when /^(.+ (Client|Server) VM) \(build (.+)\)$/
java[:hotspot] = { "name" => $1, "build" => $3 }
end
end
languages[:java] = java if java[:version]
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/blt/cutbuffer.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/blt/cutbuffer.rb
#
# tkextlib/blt/cutbuffer.rb
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tkextlib/blt.rb'
module Tk::BLT
module CutBuffer
TkCommandNames = ['::blt::cutbuffer'.freeze].freeze
def self.get(num = 0)
Tk.tk_call('::blt::cutbuffer', 'get', num)
end
def self.rotate(count = 1)
Tk.tk_call('::blt::cutbuffer', 'rotate', count)
end
def self.set(val, num = 0)
Tk.tk_call('::blt::cutbuffer', 'set', val, num)
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/lib/ohai/plugins/openbsd/memory.rb
|
#
# Author:: <NAME> <<EMAIL>>
# Copyright:: Copyright (c) 2009 <NAME>
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
provides "memory"
memory Mash.new
memory[:swap] = Mash.new
# $ vmstat -s
# 4096 bytes per page
# 514011 pages managed
# 224519 pages free
# 209339 pages active
# 4647 pages inactive
# 0 pages being paged out
# 5 pages wired
# 0 pages zeroed
# 4 pages reserved for pagedaemon
# 6 pages reserved for kernel
# 262205 swap pages
# 0 swap pages in use
# 0 total anon's in system
# 0 free anon's
# 1192991609 page faults
# 1369579301 traps
# 814549706 interrupts
# 771702498 cpu context switches
# 208810590 fpu context switches
# 492361360 software interrupts
# 1161998825 syscalls
# 0 pagein operations
# 0 swap ins
# 0 swap outs
# 768352 forks
# 16 forks where vmspace is shared
# 1763 kernel map entries
# 0 number of times the pagedaemon woke up
# 0 revolutions of the clock hand
# 0 pages freed by pagedaemon
# 0 pages scanned by pagedaemon
# 0 pages reactivated by pagedaemon
# 0 busy pages found by pagedaemon
# 1096393776 total name lookups
# cache hits (37% pos + 2% neg) system 1% per-directory
# deletions 0%, falsehits 6%, toolong 26%
# 0 select collisions
popen4("vmstat -s") do |pid, stdin, stdout, stderr|
stdin.close
stdout.each do |line|
case line
when /(\d+) bytes per page/
memory[:page_size] = $1
when /(\d+) pages managed/
memory[:page_count] = $1
memory[:total] = memory[:page_size].to_i * memory[:page_count].to_i
when /(\d+) pages free/
memory[:free] = memory[:page_size].to_i * $1.to_i
when /(\d+) pages active/
memory[:active] = memory[:page_size].to_i * $1.to_i
when /(\d+) pages inactive/
memory[:inactive] = memory[:page_size].to_i * $1.to_i
when /(\d+) pages wired/
memory[:wired] = memory[:page_size].to_i * $1.to_i
end
end
end
popen4("swapctl -l") do |pid, stdin, stdout, stderr|
stdin.close
stdout.each do |line|
# Device 1024-blocks Used Avail Capacity Priority
# swap_device 1048824 0 1048824 0% 0
if line =~ /^([\d\w\/]+)\s+(\d+)\s+(\d+)\s+(\d+)\s+([\d\%]+)/
mdev = $1
memory[:swap][mdev] = Mash.new
memory[:swap][mdev][:total] = $2
memory[:swap][mdev][:used] = $3
memory[:swap][mdev][:free] = $4
memory[:swap][mdev][:percent_free] = $5
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/demos-en/arrow.rb
|
<gh_stars>1-10
# arrow.rb
#
# This demonstration script creates a canvas widget that displays a
# large line with an arrowhead whose shape can be edited interactively.
#
# arrowhead widget demo (called by 'widget')
#
# arrowSetup --
# This method regenerates all the text and graphics in the canvas
# window. It's called when the canvas is initially created, and also
# whenever any of the parameters of the arrow head are changed
# interactively.
#
# Arguments:
# c - Name of the canvas widget.
def arrowSetup(c)
v = $demo_arrowInfo
# Remember the current box, if there is one.
tags = c.gettags('current')
if tags != []
cur = tags.find{|t| t.kind_of?(String) && t =~ /^box[1-3]$/ }
else
cur = nil
end
# Create the arrow and outline.
c.delete('all')
TkcLine.new(c, v.x1, v.y, v.x2, v.y,
{ 'width'=>10 * v.width,
'arrowshape'=>[10*v.a, 10*v.b, 10*v.c],
'arrow'=>'last'
}.update(v.bigLineStyle) )
xtip = v.x2 - 10*v.b
deltaY = 10*v.c + 5*v.width
TkcLine.new(c, v.x2, v.y, xtip, v.y + deltaY,
v.x2 - 10*v.a, v.y, xtip, v.y - deltaY, v.x2, v.y,
'width'=>2, 'capstyle'=>'round', 'joinstyle'=>'round')
# Create the boxes for reshaping the line and arrowhead.
TkcRectangle.new(c, v.x2-10*v.a-5, v.y-5, v.x2-10*v.a+5, v.y+5,
{'tags'=>['box1', $arrowTag_box]}.update(v.boxStyle) )
TkcRectangle.new(c, xtip-5, v.y-deltaY-5, xtip+5, v.y-deltaY+5,
{'tags'=>['box2', $arrowTag_box]}.update(v.boxStyle) )
TkcRectangle.new(c, v.x1-5, v.y-5*v.width-5, v.x1+5, v.y-5*v.width+5,
{'tags'=>['box3', $arrowTag_box]}.update(v.boxStyle) )
c.itemconfigure cur, v.activeStyle if cur
# Create three arrows in actual size with the same parameters
TkcLine.new(c, v.x2+50, 0, v.x2+50, 1000, 'width'=>2)
tmp = v.x2+100
TkcLine.new(c, tmp, v.y-125, tmp, v.y-75, 'width'=>v.width,
'arrow'=>'both', 'arrowshape'=>[v.a, v.b, v.c])
TkcLine.new(c, tmp-25, v.y, tmp+25, v.y, 'width'=>v.width,
'arrow'=>'both', 'arrowshape'=>[v.a, v.b, v.c])
TkcLine.new(c, tmp-25, v.y+75, tmp+25, v.y+125, 'width'=>v.width,
'arrow'=>'both', 'arrowshape'=>[v.a, v.b, v.c])
# Create a bunch of other arrows and text items showing the
# current dimensions.
tmp = v.x2+10
TkcLine.new(c, tmp, v.y-5*v.width, tmp, v.y-deltaY,
'arrow'=>'both', 'arrowshape'=>v.smallTips)
TkcText.new(c, v.x2+15, v.y-deltaY+5*v.c, 'text'=>v.c, 'anchor'=>'w')
tmp = v.x1-10
TkcLine.new(c, tmp, v.y-5*v.width, tmp, v.y+5*v.width,
'arrow'=>'both', 'arrowshape'=>v.smallTips)
TkcText.new(c, v.x1-15, v.y, 'text'=>v.width, 'anchor'=>'e')
tmp = v.y+5*v.width+10*v.c+10
TkcLine.new(c, v.x2-10*v.a, tmp, v.x2, tmp,
'arrow'=>'both', 'arrowshape'=>v.smallTips)
TkcText.new(c, v.x2-5*v.a, tmp+5, 'text'=>v.a, 'anchor'=>'n')
tmp = tmp+25
TkcLine.new(c, v.x2-10*v.b, tmp, v.x2, tmp,
'arrow'=>'both', 'arrowshape'=>v.smallTips)
TkcText.new(c, v.x2-5*v.b, tmp+5, 'text'=>v.b, 'anchor'=>'n')
if $tk_version =~ /^4.*/
TkcText.new(c, v.x1, 310, 'text'=>"'width'=>#{v.width}", 'anchor'=>'w',
'font'=>'-*-Helvetica-Medium-R-Normal--*-180-*-*-*-*-*-*')
TkcText.new(c, v.x1, 330,
'text'=>"'arrowshape'=>[#{v.a}, #{v.b}, #{v.c}]",'anchor'=>'w',
'font'=>'-*-Helvetica-Medium-R-Normal--*-180-*-*-*-*-*-*')
else
TkcText.new(c, v.x1, 310, 'text'=>"'width'=>#{v.width}", 'anchor'=>'w',
'font'=>'Helvetica 18')
TkcText.new(c, v.x1, 330,
'text'=>"'arrowshape'=>[#{v.a}, #{v.b}, #{v.c}]",
'anchor'=>'w', 'font'=>'Helvetica 18')
end
v.count += 1
end
# toplevel widget
if defined?($arrow_demo) && $arrow_demo
$arrow_demo.destroy
$arrow_demo = nil
end
# demo toplevel widget
$arrow_demo = TkToplevel.new {|w|
title("Arrowhead Editor Demonstration")
iconname("arrow")
positionWindow(w)
}
base_frame = TkFrame.new($arrow_demo).pack(:fill=>:both, :expand=>true)
# label
TkLabel.new(base_frame, 'font'=>$font, 'wraplength'=>'5i', 'justify'=>'left',
'text'=>"This widget allows you to experiment with different widths and arrowhead shapes for lines in canvases. To change the line width or the shape of the arrowhead, drag any of the three boxes attached to the oversized arrow. The arrows on the right give examples at normal scale. The text at the bottom shows the configuration options as you'd enter them for a canvas line item."){
pack('side'=>'top')
}
# frame
$arrow_buttons = TkFrame.new(base_frame) {|frame|
TkButton.new(frame) {
text 'Dismiss'
command proc{
tmppath = $arrow_demo
$arrow_demo = nil
tmppath.destroy
}
}.pack('side'=>'left', 'expand'=>'yes')
TkButton.new(frame) {
text 'Show Code'
command proc{showCode 'arrow'}
}.pack('side'=>'left', 'expand'=>'yes')
}
$arrow_buttons.pack('side'=>'bottom', 'fill'=>'x', 'pady'=>'2m')
# canvas
$arrow_canvas = TkCanvas.new(base_frame, 'width'=>500, 'height'=>350,
'relief'=>'sunken', 'borderwidth'=>2)
$arrow_canvas.pack('expand'=>'yes', 'fill'=>'both')
#
unless Struct.const_defined?("ArrowInfo")
$demo_arrowInfo = Struct.new("ArrowInfo", :a, :b, :c, :width, :motionProc,
:x1, :x2, :y, :smallTips, :count,
:bigLineStyle, :boxStyle, :activeStyle).new
end
$demo_arrowInfo.a = 8
$demo_arrowInfo.b = 10
$demo_arrowInfo.c = 3
$demo_arrowInfo.width = 2
$demo_arrowInfo.motionProc = proc{}
$demo_arrowInfo.x1 = 40
$demo_arrowInfo.x2 = 350
$demo_arrowInfo.y = 150
$demo_arrowInfo.smallTips = [5, 5, 2]
$demo_arrowInfo.count = 0
if TkWinfo.depth($arrow_canvas) > 1
$demo_arrowInfo.bigLineStyle = {'fill'=>'SkyBlue1'}
$demo_arrowInfo.boxStyle = {'fill'=>'', 'outline'=>'black', 'width'=>1}
$demo_arrowInfo.activeStyle = {'fill'=>'red', 'outline'=>'black', 'width'=>1}
else
$demo_arrowInfo.bigLineStyle = {'fill'=>'black',
'stipple'=>'@'+[$demo_dir,'..','images','grey.25'].join(File::Separator)}
$demo_arrowInfo.boxStyle = {'fill'=>'', 'outline'=>'black', 'width'=>1}
$demo_arrowInfo.activeStyle = {'fill'=>'black','outline'=>'black','width'=>1}
end
$arrowTag_box = TkcTag.new($arrow_canvas)
arrowSetup $arrow_canvas
$arrowTag_box.bind('Enter', proc{$arrow_canvas.itemconfigure('current', $demo_arrowInfo.activeStyle)})
$arrowTag_box.bind('Leave', proc{$arrow_canvas.itemconfigure('current', $demo_arrowInfo.boxStyle)})
$arrowTag_box.bind('B1-Enter', proc{})
$arrowTag_box.bind('B1-Leave', proc{})
$arrow_canvas.itembind('box1', '1',
proc{$demo_arrowInfo.motionProc \
= proc{|x,y| arrowMove1 $arrow_canvas, x, y}})
$arrow_canvas.itembind('box2', '1',
proc{$demo_arrowInfo.motionProc \
= proc{|x,y| arrowMove2 $arrow_canvas, x, y}})
$arrow_canvas.itembind('box3', '1',
proc{$demo_arrowInfo.motionProc \
= proc{|x,y| arrowMove3 $arrow_canvas, x, y}})
$arrowTag_box.bind('B1-Motion',
proc{|x,y| $demo_arrowInfo.motionProc.call(x,y)}, "%x %y")
$arrow_canvas.bind('Any-ButtonRelease-1', proc{arrowSetup $arrow_canvas})
# arrowMove1 --
# This method is called for each mouse motion event on box1 (the
# one at the vertex of the arrow). It updates the controlling parameters
# for the line and arrowhead.
#
# Arguments:
# c - The name of the canvas window.
# x, y - The coordinates of the mouse.
def arrowMove1(c,x,y)
v = $demo_arrowInfo
newA = (v.x2+5-c.canvasx(x).round)/10
newA = 0 if newA < 0
newA = 25 if newA > 25
if newA != v.a
c.move('box1', 10*(v.a-newA), 0)
v.a = newA
end
end
# arrowMove2 --
# This method is called for each mouse motion event on box2 (the
# one at the trailing tip of the arrowhead). It updates the controlling
# parameters for the line and arrowhead.
#
# Arguments:
# c - The name of the canvas window.
# x, y - The coordinates of the mouse.
def arrowMove2(c,x,y)
v = $demo_arrowInfo
newB = (v.x2+5-c.canvasx(x).round)/10
newB = 0 if newB < 0
newB = 25 if newB > 25
newC = (v.y+5-c.canvasy(y).round-5*v.width)/10
newC = 0 if newC < 0
newC = 20 if newC > 20
if newB != v.b || newC != v.c
c.move('box2', 10*(v.b-newB), 10*(v.c-newC))
v.b = newB
v.c = newC
end
end
# arrowMove3 --
# This method is called for each mouse motion event on box3 (the
# one that controls the thickness of the line). It updates the
# controlling parameters for the line and arrowhead.
#
# Arguments:
# c - The name of the canvas window.
# x, y - The coordinates of the mouse.
def arrowMove3(c,x,y)
v = $demo_arrowInfo
newWidth = (v.y+2-c.canvasy(y).round)/5
newWidth = 0 if newWidth < 0
newWidth = 20 if newWidth > 20
if newWidth != v.width
c.move('box3', 0, 5*(v.width-newWidth))
v.width = newWidth
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/optparse/test_placearg.rb
|
<reponame>arnab0073/idea
# frozen_string_literal: false
require_relative 'test_optparse'
class TestOptionParser::PlaceArg < TestOptionParser
def setup
super
@opt.def_option("-x [VAL]") {|x| @flag = x}
@opt.def_option("--option [VAL]") {|x| @flag = x}
@opt.def_option("-T [level]", /^[0-4]$/, Integer) {|x| @topt = x}
@topt = nil
@opt.def_option("-n") {}
@opt.def_option("--regexp [REGEXP]", Regexp) {|x| @reopt = x}
@reopt = nil
end
def test_short
assert_equal(%w"", no_error {@opt.parse!(%w"-x -n")})
assert_equal(nil, @flag)
@flag = false
assert_equal(%w"", no_error {@opt.parse!(%w"-x foo")})
assert_equal("foo", @flag)
assert_equal(%w"", no_error {@opt.parse!(%w"-xbar")})
assert_equal("bar", @flag)
assert_equal(%w"", no_error {@opt.parse!(%w"-x=")})
assert_equal("=", @flag)
end
def test_abbrev
assert_equal(%w"", no_error {@opt.parse!(%w"-o -n")})
assert_equal(nil, @flag)
@flag = false
assert_equal(%w"", no_error {@opt.parse!(%w"-o foo")})
assert_equal("foo", @flag)
assert_equal(%w"", no_error {@opt.parse!(%w"-obar")})
assert_equal("bar", @flag)
assert_equal(%w"", no_error {@opt.parse!(%w"-o=")})
assert_equal("=", @flag)
end
def test_long
assert_equal(%w"", no_error {@opt.parse!(%w"--opt -n")})
assert_equal(nil, @flag)
assert_equal(%w"foo", no_error {@opt.parse!(%w"--opt= foo")})
assert_equal("", @flag)
assert_equal(%w"", no_error {@opt.parse!(%w"--opt=foo")})
assert_equal("foo", @flag)
assert_equal(%w"", no_error {@opt.parse!(%w"--opt bar")})
assert_equal("bar", @flag)
end
def test_conv
assert_equal(%w"te.rb", no_error('[ruby-dev:38333]') {@opt.parse!(%w"-T te.rb")})
assert_nil(@topt)
assert_equal(%w"te.rb", no_error('[ruby-dev:38333]') {@opt.parse!(%w"-T1 te.rb")})
assert_equal(1, @topt)
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/psych/test_hash.rb
|
<filename>.rvm/src/ruby-2.3.0/test/psych/test_hash.rb
# frozen_string_literal: false
require_relative 'helper'
module Psych
class TestHash < TestCase
class X < Hash
end
class HashWithCustomInit < Hash
attr_reader :obj
def initialize(obj)
@obj = obj
end
end
class HashWithCustomInitNoIvar < Hash
def initialize(obj)
# *shrug*
end
end
def setup
super
@hash = { :a => 'b' }
end
def test_referenced_hash_with_ivar
a = [1,2,3,4,5]
t1 = [HashWithCustomInit.new(a)]
t1 << t1.first
assert_cycle t1
end
def test_custom_initialized
a = [1,2,3,4,5]
t1 = HashWithCustomInit.new(a)
t2 = Psych.load(Psych.dump(t1))
assert_equal t1, t2
assert_cycle t1
end
def test_custom_initialize_no_ivar
t1 = HashWithCustomInitNoIvar.new(nil)
t2 = Psych.load(Psych.dump(t1))
assert_equal t1, t2
assert_cycle t1
end
def test_hash_subclass_with_ivars
x = X.new
x[:a] = 'b'
x.instance_variable_set :@foo, 'bar'
dup = Psych.load Psych.dump x
assert_cycle x
assert_equal 'bar', dup.instance_variable_get(:@foo)
assert_equal X, dup.class
end
def test_load_with_class_syck_compatibility
hash = Psych.load "--- !ruby/object:Hash\n:user_id: 7\n:username: Lucas\n"
assert_equal({ user_id: 7, username: 'Lucas'}, hash)
end
def test_empty_subclass
assert_match "!ruby/hash:#{X}", Psych.dump(X.new)
x = Psych.load Psych.dump X.new
assert_equal X, x.class
end
def test_map
x = Psych.load "--- !map:#{X} { }\n"
assert_equal X, x.class
end
def test_self_referential
@hash['self'] = @hash
assert_cycle(@hash)
end
def test_cycles
assert_cycle(@hash)
end
def test_ref_append
hash = Psych.load(<<-eoyml)
---
foo: &foo
hello: world
bar:
<<: *foo
eoyml
assert_equal({"foo"=>{"hello"=>"world"}, "bar"=>{"hello"=>"world"}}, hash)
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/rest-client-1.6.9/spec/base.rb
|
<reponame>arnab0073/idea
def is_ruby_19?
RUBY_VERSION > '1.9'
end
require 'rubygems'
begin
require "ruby-debug"
rescue LoadError
# NOP, ignore
end
require File.dirname(__FILE__) + '/../lib/restclient'
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/lib/ohai/plugins/solaris2/cpu.rb
|
<filename>.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/lib/ohai/plugins/solaris2/cpu.rb
#$ psrinfo -v
#Status of virtual processor 0 as of: 01/11/2009 23:31:55
# on-line since 05/29/2008 15:05:28.
# The i386 processor operates at 2660 MHz,
# and has an i387 compatible floating point processor.
#Status of virtual processor 1 as of: 01/11/2009 23:31:55
# on-line since 05/29/2008 15:05:30.
# The i386 processor operates at 2660 MHz,
# and has an i387 compatible floating point processor.
#Status of virtual processor 2 as of: 01/11/2009 23:31:55
# on-line since 05/29/2008 15:05:30.
# The i386 processor operates at 2660 MHz,
# and has an i387 compatible floating point processor.
#Status of virtual processor 3 as of: 01/11/2009 23:31:55
# on-line since 05/29/2008 15:05:30.
# The i386 processor operates at 2660 MHz,
# and has an i387 compatible floating point processor.
#Status of virtual processor 4 as of: 01/11/2009 23:31:55
# on-line since 05/29/2008 15:05:30.
# The i386 processor operates at 2660 MHz,
# and has an i387 compatible floating point processor.
#Status of virtual processor 5 as of: 01/11/2009 23:31:55
# on-line since 05/29/2008 15:05:30.
# The i386 processor operates at 2660 MHz,
# and has an i387 compatible floating point processor.
#Status of virtual processor 6 as of: 01/11/2009 23:31:55
# on-line since 05/29/2008 15:05:30.
# The i386 processor operates at 2660 MHz,
# and has an i387 compatible floating point processor.
#Status of virtual processor 7 as of: 01/11/2009 23:31:55
# on-line since 05/29/2008 15:05:30.
# The i386 processor operates at 2660 MHz,
# and has an i387 compatible floating point processor.
|
arnab0073/idea
|
.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/rvm-1.11.3.9/lib/rvm/environment.rb
|
require 'forwardable'
module RVM
# Implements the actual wrapper around the api. For more information
# about this design, see the RVM module.
class Environment
extend Forwardable
%w(configuration utility alias list gemset rubies cleanup sets env tools info wrapper).each do |key|
require File.join("rvm", "environment", key)
end
# The default config has rvm_silence_logging so that log doesn't print anything to stdout.
merge_config! :rvm_silence_logging => 1,
:rvm_promptless => 1,
:rvm_ruby_api => 1
attr_reader :environment_name, :shell_wrapper
# Creates a new environment with the given name and optionally
# a set of extra environment variables to be set on load.
def initialize(environment_name = "default", options = {})
merge_config! options
@environment_name = environment_name
@shell_wrapper = Shell.default_wrapper.new
@shell_wrapper.setup do |s|
source_rvm_environment
use_rvm_environment
end
end
def inspect
"#<#{self.class.name} environment_name=#{@environment_name.inspect}>"
end
# Returns the expanded name, using the same method as used by the rvm command line.
#
# Suppose that you are in the 1.9.2 patchlevel Environment.
#
# env.expanded_name # => "ruby-1.9.2-p0"
#
def expanded_name
@expanded_name ||= tools_identifier.to_s
end
# Actually define methods to interact with the shell wrapper.
def_delegators :@shell_wrapper, :run, :run_silently, :run_command_without_output,
:run_command, :[], :escape_argument
protected
# Automatically load rvm config from the multiple sources.
def source_rvm_environment
rvm_path = config_value_for(:rvm_path, self.class.default_rvm_path, false)
actual_config = defined_config.merge('rvm_path' => rvm_path)
config = []
actual_config.each_pair do |k, v|
config << "#{k}=#{escape_argument(v.to_s)}"
end
run_silently "export #{config.join(" ")}"
run_silently :source, File.join(rvm_path, "scripts", "rvm")
end
def use_rvm_environment
rvm :use, @environment_name, :silent => true
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tk/grid.rb
|
#
# tk/grid.rb : control grid geometry manager
#
require 'tk'
module TkGrid
include Tk
extend Tk
TkCommandNames = ['grid'.freeze].freeze
def anchor(master, anchor=None)
# master = master.epath if master.kind_of?(TkObject)
master = _epath(master)
tk_call_without_enc('grid', 'anchor', master, anchor)
end
def bbox(master, *args)
# master = master.epath if master.kind_of?(TkObject)
master = _epath(master)
args.unshift(master)
list(tk_call_without_enc('grid', 'bbox', *args))
end
=begin
def configure(win, *args)
if args[-1].kind_of?(Hash)
opts = args.pop
else
opts = {}
end
params = []
params.push(_epath(win))
args.each{|win|
case win
when '-', 'x', '^' # RELATIVE PLACEMENT
params.push(win)
else
params.push(_epath(win))
end
}
opts.each{|k, v|
params.push("-#{k}")
params.push((v.kind_of?(TkObject))? v.epath: v)
}
if Tk::TCL_MAJOR_VERSION < 8 ||
(Tk::TCL_MAJOR_VERSION == 8 && Tk::TCL_MINOR_VERSION <= 3)
if params[0] == '-' || params[0] == 'x' || params[0] == '^'
tk_call_without_enc('grid', *params)
else
tk_call_without_enc('grid', 'configure', *params)
end
else
tk_call_without_enc('grid', 'configure', *params)
end
end
=end
def configure(*args)
if args[-1].kind_of?(Hash)
opts = args.pop
else
opts = {}
end
fail ArgumentError, 'no widget is given' if args.empty?
params = []
args.flatten(1).each{|win|
case win
when '-', ?- # RELATIVE PLACEMENT (increase columnspan)
params.push('-')
when /^-+$/ # RELATIVE PLACEMENT (increase columnspan)
params.concat(win.to_s.split(//))
when '^', ?^ # RELATIVE PLACEMENT (increase rowspan)
params.push('^')
when /^\^+$/ # RELATIVE PLACEMENT (increase rowspan)
params.concat(win.to_s.split(//))
when 'x', :x, ?x, nil, '' # RELATIVE PLACEMENT (empty column)
params.push('x')
when /^x+$/ # RELATIVE PLACEMENT (empty column)
params.concat(win.to_s.split(//))
else
params.push(_epath(win))
end
}
opts.each{|k, v|
params.push("-#{k}")
params.push(_epath(v)) # have to use 'epath' (hash_kv() is unavailable)
}
if Tk::TCL_MAJOR_VERSION < 8 ||
(Tk::TCL_MAJOR_VERSION == 8 && Tk::TCL_MINOR_VERSION <= 3)
if params[0] == '-' || params[0] == 'x' || params[0] == '^'
tk_call_without_enc('grid', *params)
else
tk_call_without_enc('grid', 'configure', *params)
end
else
tk_call_without_enc('grid', 'configure', *params)
end
end
alias grid configure
def columnconfigure(master, index, args)
# master = master.epath if master.kind_of?(TkObject)
master = _epath(master)
tk_call_without_enc("grid", 'columnconfigure',
master, index, *hash_kv(args))
end
def rowconfigure(master, index, args)
# master = master.epath if master.kind_of?(TkObject)
master = _epath(master)
tk_call_without_enc("grid", 'rowconfigure', master, index, *hash_kv(args))
end
def columnconfiginfo(master, index, slot=nil)
# master = master.epath if master.kind_of?(TkObject)
master = _epath(master)
if slot
case slot
when 'uniform', :uniform
tk_call_without_enc('grid', 'columnconfigure',
master, index, "-#{slot}")
else
num_or_str(tk_call_without_enc('grid', 'columnconfigure',
master, index, "-#{slot}"))
end
else
#ilist = list(tk_call_without_enc('grid','columnconfigure',master,index))
ilist = simplelist(tk_call_without_enc('grid', 'columnconfigure',
master, index))
info = {}
while key = ilist.shift
case key
when 'uniform'
info[key[1..-1]] = ilist.shift
else
info[key[1..-1]] = tk_tcl2ruby(ilist.shift)
end
end
info
end
end
def rowconfiginfo(master, index, slot=nil)
# master = master.epath if master.kind_of?(TkObject)
master = _epath(master)
if slot
case slot
when 'uniform', :uniform
tk_call_without_enc('grid', 'rowconfigure',
master, index, "-#{slot}")
else
num_or_str(tk_call_without_enc('grid', 'rowconfigure',
master, index, "-#{slot}"))
end
else
#ilist = list(tk_call_without_enc('grid', 'rowconfigure', master, index))
ilist = simplelist(tk_call_without_enc('grid', 'rowconfigure',
master, index))
info = {}
while key = ilist.shift
case key
when 'uniform'
info[key[1..-1]] = ilist.shift
else
info[key[1..-1]] = tk_tcl2ruby(ilist.shift)
end
end
info
end
end
def column(master, index, keys=nil)
if keys.kind_of?(Hash)
columnconfigure(master, index, keys)
else
columnconfiginfo(master, index, keys)
end
end
def row(master, index, keys=nil)
if keys.kind_of?(Hash)
rowconfigure(master, index, keys)
else
rowconfiginfo(master, index, keys)
end
end
def add(widget, *args)
configure(widget, *args)
end
def forget(*args)
return '' if args.size == 0
wins = args.collect{|win|
# (win.kind_of?(TkObject))? win.epath: win
_epath(win)
}
tk_call_without_enc('grid', 'forget', *wins)
end
def info(slave)
# slave = slave.epath if slave.kind_of?(TkObject)
slave = _epath(slave)
#ilist = list(tk_call_without_enc('grid', 'info', slave))
ilist = simplelist(tk_call_without_enc('grid', 'info', slave))
info = {}
while key = ilist.shift
#info[key[1..-1]] = ilist.shift
info[key[1..-1]] = tk_tcl2ruby(ilist.shift)
end
return info
end
def location(master, x, y)
# master = master.epath if master.kind_of?(TkObject)
master = _epath(master)
list(tk_call_without_enc('grid', 'location', master, x, y))
end
def propagate(master, mode=None)
# master = master.epath if master.kind_of?(TkObject)
master = _epath(master)
if mode == None
bool(tk_call_without_enc('grid', 'propagate', master))
else
tk_call_without_enc('grid', 'propagate', master, mode)
end
end
def remove(*args)
return '' if args.size == 0
wins = args.collect{|win|
# (win.kind_of?(TkObject))? win.epath: win
_epath(win)
}
tk_call_without_enc('grid', 'remove', *wins)
end
def size(master)
# master = master.epath if master.kind_of?(TkObject)
master = _epath(master)
list(tk_call_without_enc('grid', 'size', master))
end
def slaves(master, keys=nil)
# master = master.epath if master.kind_of?(TkObject)
master = _epath(master)
list(tk_call_without_enc('grid', 'slaves', master, *hash_kv(args)))
end
module_function :anchor, :bbox, :add, :forget, :propagate, :info
module_function :remove, :size, :slaves, :location
module_function :grid, :configure, :columnconfigure, :rowconfigure
module_function :column, :row, :columnconfiginfo, :rowconfiginfo
end
=begin
def TkGrid(win, *args)
if args[-1].kind_of?(Hash)
opts = args.pop
else
opts = {}
end
params = []
params.push((win.kind_of?(TkObject))? win.epath: win)
args.each{|win|
case win
when '-', 'x', '^' # RELATIVE PLACEMENT
params.push(win)
else
params.push((win.kind_of?(TkObject))? win.epath: win)
end
}
opts.each{|k, v|
params.push("-#{k}")
params.push((v.kind_of?(TkObject))? v.epath: v)
}
tk_call_without_enc("grid", *params)
end
=end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.