repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/lib/memory_status.rb
|
<filename>.rvm/src/ruby-2.3.0/test/lib/memory_status.rb<gh_stars>1-10
# frozen_string_literal: false
module Memory
keys = []
vals = []
case
when File.exist?(procfile = "/proc/self/status") && (pat = /^Vm(\w+):\s+(\d+)/) =~ File.binread(procfile)
PROC_FILE = procfile
VM_PAT = pat
def self.read_status
IO.foreach(PROC_FILE, encoding: Encoding::ASCII_8BIT) do |l|
yield($1.downcase.intern, $2.to_i * 1024) if VM_PAT =~ l
end
end
read_status {|k, v| keys << k; vals << v}
when /mswin|mingw/ =~ RUBY_PLATFORM
require 'fiddle/import'
require 'fiddle/types'
module Win32
extend Fiddle::Importer
dlload "kernel32.dll", "psapi.dll"
include Fiddle::Win32Types
typealias "SIZE_T", "size_t"
PROCESS_MEMORY_COUNTERS = struct [
"DWORD cb",
"DWORD PageFaultCount",
"SIZE_T PeakWorkingSetSize",
"SIZE_T WorkingSetSize",
"SIZE_T QuotaPeakPagedPoolUsage",
"SIZE_T QuotaPagedPoolUsage",
"SIZE_T QuotaPeakNonPagedPoolUsage",
"SIZE_T QuotaNonPagedPoolUsage",
"SIZE_T PagefileUsage",
"SIZE_T PeakPagefileUsage",
]
typealias "PPROCESS_MEMORY_COUNTERS", "PROCESS_MEMORY_COUNTERS*"
extern "HANDLE GetCurrentProcess()", :stdcall
extern "BOOL GetProcessMemoryInfo(HANDLE, PPROCESS_MEMORY_COUNTERS, DWORD)", :stdcall
module_function
def memory_info
size = PROCESS_MEMORY_COUNTERS.size
data = PROCESS_MEMORY_COUNTERS.malloc
data.cb = size
data if GetProcessMemoryInfo(GetCurrentProcess(), data, size)
end
end
keys << :peak << :size
def self.read_status
if info = Win32.memory_info
yield :peak, info.PeakPagefileUsage
yield :size, info.PagefileUsage
end
end
else
PAT = /^\s*(\d+)\s+(\d+)$/
require_relative 'find_executable'
if PSCMD = EnvUtil.find_executable("ps", "-ovsz=", "-orss=", "-p", $$.to_s) {|out| PAT =~ out}
PSCMD.pop
end
raise MiniTest::Skip, "ps command not found" unless PSCMD
keys << :size << :rss
def self.read_status
if PAT =~ IO.popen(PSCMD + [$$.to_s], "r", err: [:child, :out], &:read)
yield :size, $1.to_i*1024
yield :rss, $2.to_i*1024
end
end
end
Status = Struct.new(*keys)
class Status
def _update
Memory.read_status do |key, val|
self[key] = val
end
end
end
class Status
Header = members.map {|k| k.to_s.upcase.rjust(6)}.join('')
Format = "%6d"
def initialize
_update
end
def to_s
status = each_pair.map {|n,v|
"#{n}:#{v}"
}
"{#{status.join(",")}}"
end
def self.parse(str)
status = allocate
str.scan(/(?:\A\{|\G,)(#{members.join('|')}):(\d+)(?=,|\}\z)/) do
status[$1] = $2.to_i
end
status
end
end
# On some platforms (e.g. Solaris), libc malloc does not return
# freed memory to OS because of efficiency, and linking with extra
# malloc library is needed to detect memory leaks.
#
case RUBY_PLATFORM
when /solaris2\.(?:9|[1-9][0-9])/i # Solaris 9, 10, 11,...
bits = [nil].pack('p').size == 8 ? 64 : 32
if ENV['LD_PRELOAD'].to_s.empty? &&
ENV["LD_PRELOAD_#{bits}"].to_s.empty? &&
(ENV['UMEM_OPTIONS'].to_s.empty? ||
ENV['UMEM_OPTIONS'] == 'backend=mmap') then
envs = {
'LD_PRELOAD' => 'libumem.so',
'UMEM_OPTIONS' => 'backend=mmap'
}
args = [
envs,
"--disable=gems",
"-v", "-",
]
_, err, status = EnvUtil.invoke_ruby(args, "exit(0)", true, true)
if status.exitstatus == 0 && err.to_s.empty? then
NO_MEMORY_LEAK_ENVS = envs
end
end
end #case RUBY_PLATFORM
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/mixlib-config-2.2.1/lib/mixlib/config.rb
|
<gh_stars>0
#
# Author:: <NAME> (<<EMAIL>>)
# Author:: <NAME> (<<EMAIL>>)
# Author:: <NAME> (<<EMAIL>>)
# Copyright:: Copyright (c) 2008 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.
#
require 'mixlib/config/version'
require 'mixlib/config/configurable'
require 'mixlib/config/unknown_config_option_error'
require 'mixlib/config/reopened_config_context_with_configurable_error'
require 'mixlib/config/reopened_configurable_with_config_context_error'
module Mixlib
module Config
def self.extended(base)
class << base; attr_accessor :configuration; end
class << base; attr_accessor :configurables; end
class << base; attr_accessor :config_contexts; end
class << base; attr_accessor :config_parent; end
base.configuration = Hash.new
base.configurables = Hash.new
base.config_contexts = Hash.new
end
# Loads a given ruby file, and runs instance_eval against it in the context of the current
# object.
#
# Raises an IOError if the file cannot be found, or is not readable.
#
# === Parameters
# filename<String>:: A filename to read from
def from_file(filename)
self.instance_eval(IO.read(filename), filename, 1)
end
# Pass Mixlib::Config.configure() a block, and it will yield itself
#
# === Parameters
# block<Block>:: A block that is called with self.configuration as the argument.
def configure(&block)
block.call(self.configuration)
end
# Get the value of a config option
#
# === Parameters
# config_option<Symbol>:: The config option to return
#
# === Returns
# value:: The value of the config option
#
# === Raises
# <UnknownConfigOptionError>:: If the config option does not exist and strict mode is on.
def [](config_option)
internal_get(config_option.to_sym)
end
# Set the value of a config option
#
# === Parameters
# config_option<Symbol>:: The config option to set (within the [])
# value:: The value for the config option
#
# === Returns
# value:: The new value of the config option
#
# === Raises
# <UnknownConfigOptionError>:: If the config option does not exist and strict mode is on.
def []=(config_option, value)
internal_set(config_option.to_sym, value)
end
# Check if Mixlib::Config has a config option.
#
# === Parameters
# key<Symbol>:: The config option to check for
#
# === Returns
# <True>:: If the config option exists
# <False>:: If the config option does not exist
def has_key?(key)
self.configuration.has_key?(key.to_sym)
end
# Resets a config option to its default.
#
# === Parameters
# symbol<Symbol>:: Name of the config option
def delete(symbol)
self.configuration.delete(symbol)
end
# Resets all config options to their defaults.
def reset
self.configuration = Hash.new
self.config_contexts.values.each { |config_context| config_context.reset }
end
# Makes a copy of any non-default values.
#
# This returns a shallow copy of the hash; while the hash itself is
# duplicated a la dup, modifying data inside arrays and hashes may modify
# the original Config object.
#
# === Returns
#
# Hash of values the user has set.
#
# === Examples
#
# For example, this config class:
#
# class MyConfig < Mixlib::Config
# default :will_be_set, 1
# default :will_be_set_to_default, 1
# default :will_not_be_set, 1
# configurable(:computed_value) { |x| x*2 }
# config_context :group do
# default :will_not_be_set, 1
# end
# config_context :group_never_set
# end
#
# MyConfig.x = 2
# MyConfig.will_be_set = 2
# MyConfig.will_be_set_to_default = 1
# MyConfig.computed_value = 2
# MyConfig.group.x = 3
#
# produces this:
#
# MyConfig.save == {
# :x => 2,
# :will_be_set => 2,
# :will_be_set_to_default => 1,
# :computed_value => 4,
# :group => {
# :x => 3
# }
# }
#
def save(include_defaults = false)
result = self.configuration.dup
if include_defaults
(self.configurables.keys - result.keys).each do |missing_default|
# Ask any configurables to save themselves into the result array
if self.configurables[missing_default].has_default
result[missing_default] = self.configurables[missing_default].default
end
end
end
self.config_contexts.each_pair do |key, context|
context_result = context.save(include_defaults)
result[key] = context_result if context_result.size != 0 || include_defaults
end
result
end
# Restore non-default values from the given hash.
#
# This method is the equivalent of +reset+ followed by +merge!(hash)+.
#
# === Parameters
# hash<Hash>: a hash in the same format as output by save.
#
# === Returns
# self
def restore(hash)
reset
merge!(hash)
end
# Merge an incoming hash with our config options
#
# === Parameters
# hash<Hash>: a hash in the same format as output by save.
#
# === Returns
# self
def merge!(hash)
hash.each do |key, value|
if self.config_contexts.has_key?(key)
# Grab the config context and let internal_get cache it if so desired
self.config_contexts[key].restore(value)
else
self.configuration[key] = value
end
end
self
end
# Return the set of config hash keys.
# This *only* returns hash keys which have been set by the user. In future
# versions this will likely be removed in favor of something more explicit.
# For now though, we want this to match has_key?
#
# === Returns
# result of Hash#keys
def keys
self.configuration.keys
end
# Creates a shallow copy of the internal hash
# NOTE: remove this in 3.0 in favor of save. This is completely useless
# with default values and configuration_context.
#
# === Returns
# result of Hash#dup
def hash_dup
save
end
# metaprogramming to ensure that the slot for method_symbol
# gets set to value after any other logic is run
#
# === Parameters
# method_symbol<Symbol>:: Name of the method (variable setter)
# blk<Block>:: logic block to run in setting slot method_symbol to value
# value<Object>:: Value to be set in config hash
#
def config_attr_writer(method_symbol, &block)
configurable(method_symbol).writes_value(&block)
end
# metaprogramming to set the default value for the given config option
#
# === Parameters
# symbol<Symbol>:: Name of the config option
# default_value<Object>:: Default value (can be unspecified)
# block<Block>:: Logic block that calculates default value
def default(symbol, default_value = nil, &block)
configurable(symbol).defaults_to(default_value, &block)
end
# metaprogramming to set information about a config option. This may be
# used in one of two ways:
#
# 1. Block-based:
# configurable(:attr) do
# defaults_to 4
# writes_value { |value| 10 }
# end
#
# 2. Chain-based:
# configurable(:attr).defaults_to(4).writes_value { |value| 10 }
#
# Currently supported configuration:
#
# defaults_to(value): value returned when configurable has no explicit value
# defaults_to BLOCK: block is run when the configurable has no explicit value
# writes_value BLOCK: block that is run to filter a value when it is being set
#
# === Parameters
# symbol<Symbol>:: Name of the config option
# default_value<Object>:: Default value [optional]
# block<Block>:: Logic block that calculates default value [optional]
#
# === Returns
# The value of the config option.
def configurable(symbol, &block)
unless configurables[symbol]
if config_contexts.has_key?(symbol)
raise ReopenedConfigContextWithConfigurableError, "Cannot redefine config_context #{symbol} as a configurable value"
end
configurables[symbol] = Configurable.new(symbol)
define_attr_accessor_methods(symbol)
end
if block
block.call(configurables[symbol])
end
configurables[symbol]
end
# Allows you to create a new config context where you can define new
# options with default values.
#
# This method allows you to open up the configurable more than once.
#
# For example:
#
# config_context :server_info do
# configurable(:url).defaults_to("http://localhost")
# end
#
# === Parameters
# symbol<Symbol>: the name of the context
# block<Block>: a block that will be run in the context of this new config
# class.
def config_context(symbol, &block)
if configurables.has_key?(symbol)
raise ReopenedConfigurableWithConfigContextError, "Cannot redefine config value #{symbol} with a config context"
end
if config_contexts.has_key?(symbol)
context = config_contexts[symbol]
else
context = Class.new
context.extend(::Mixlib::Config)
context.config_parent = self
config_contexts[symbol] = context
define_attr_accessor_methods(symbol)
end
if block
context.instance_eval(&block)
end
context
end
NOT_PASSED = Object.new
# Gets or sets strict mode. When strict mode is on, only values which
# were specified with configurable(), default() or writes_with() may be
# retrieved or set. Getting or setting anything else will cause
# Mixlib::Config::UnknownConfigOptionError to be thrown.
#
# If this is set to :warn, unknown values may be get or set, but a warning
# will be printed with Chef::Log.warn if this occurs.
#
# === Parameters
# value<String>:: pass this value to set strict mode [optional]
#
# === Returns
# Current value of config_strict_mode
#
# === Raises
# <ArgumentError>:: if value is set to something other than true, false, or :warn
#
def config_strict_mode(value = NOT_PASSED)
if value == NOT_PASSED
if @config_strict_mode.nil?
if config_parent
config_parent.config_strict_mode
else
false
end
else
@config_strict_mode
end
else
self.config_strict_mode = value
end
end
# Sets strict mode. When strict mode is on, only values which
# were specified with configurable(), default() or writes_with() may be
# retrieved or set. All other values
#
# If this is set to :warn, unknown values may be get or set, but a warning
# will be printed with Chef::Log.warn if this occurs.
#
# === Parameters
# value<String>:: pass this value to set strict mode [optional]
#
# === Raises
# <ArgumentError>:: if value is set to something other than true, false, or :warn
#
def config_strict_mode=(value)
if ![ true, false, :warn, nil ].include?(value)
raise ArgumentError, "config_strict_mode must be true, false, nil or :warn"
end
@config_strict_mode = value
end
# Allows for simple lookups and setting of config options via method calls
# on Mixlib::Config. If there any arguments to the method, they are used to set
# the value of the config option. Otherwise, it's a simple get operation.
#
# === Parameters
# method_symbol<Symbol>:: The method called. Must match a config option.
# *args:: Any arguments passed to the method
#
# === Returns
# value:: The value of the config option.
#
# === Raises
# <UnknownConfigOptionError>:: If the config option does not exist and strict mode is on.
def method_missing(method_symbol, *args)
method_symbol = $1.to_sym if method_symbol.to_s =~ /(.+)=$/
internal_get_or_set(method_symbol, *args)
end
private
# Internal dispatch setter for config values.
#
# === Parameters
# symbol<Symbol>:: Name of the method (variable setter)
# value<Object>:: Value to be set in config hash
#
def internal_set(symbol,value)
if configurables.has_key?(symbol)
configurables[symbol].set(self.configuration, value)
elsif config_contexts.has_key?(symbol)
config_contexts[symbol].restore(value)
else
if config_strict_mode == :warn
Chef::Log.warn("Setting unsupported config value #{symbol}.")
elsif config_strict_mode
raise UnknownConfigOptionError, "Cannot set unsupported config value #{symbol}."
end
configuration[symbol] = value
end
end
def internal_get(symbol)
if configurables.has_key?(symbol)
configurables[symbol].get(self.configuration)
elsif config_contexts.has_key?(symbol)
config_contexts[symbol]
else
if config_strict_mode == :warn
Chef::Log.warn("Reading unsupported config value #{symbol}.")
elsif config_strict_mode
raise UnknownConfigOptionError, "Reading unsupported config value #{symbol}."
end
configuration[symbol]
end
end
def internal_get_or_set(symbol,*args)
num_args = args.length
# Setting
if num_args > 0
internal_set(symbol, num_args == 1 ? args[0] : args)
end
# Returning
internal_get(symbol)
end
def define_attr_accessor_methods(symbol)
# When Ruby 1.8.7 is no longer supported, this stuff can be done with define_singleton_method!
meta = class << self; self; end
# Setter
meta.send :define_method, "#{symbol.to_s}=".to_sym do |value|
internal_set(symbol, value)
end
# Getter
meta.send :define_method, symbol do |*args|
internal_get_or_set(symbol, *args)
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/benchmark/bm_vm1_ivar.rb
|
@a = 1
i = 0
while i<30_000_000 # while loop 1
i+= 1
j = @a
k = @a
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/tktable/buttons.rb
|
#!/usr/bin/env ruby
##
## buttons.rb
##
## demonstrates the simulation of a button array
##
## ( based on 'buttons.tcl' included source archive of tktable extension )
##
require 'tk'
require 'tkextlib/tktable'
# create the table
tab = TkVariable.new_hash
rows = 20
cols = 20
table = Tk::TkTable.new(:rows=>rows + 1, :cols=>cols + 1,
:variable=>tab, :titlerows=>1, :titlecols=>1,
:roworigin=>-1, :colorigin=>-1,
:colwidth=>4, :width=>8, :height=>8,
:cursor=>'top_left_arrow', :borderwidth=>2,
:flashmode=>false, :state=>:disabled)
sx = table.xscrollbar(TkScrollbar.new)
sy = table.yscrollbar(TkScrollbar.new)
Tk.grid(table, sy, :sticky=>:news)
Tk.grid(sx, :sticky=>:ew)
Tk.root.grid_columnconfig(0, :weight=>1)
Tk.root.grid_rowconfig(0, :weight=>1)
# set up tags for the various states of the buttons
table.tag_configure('OFF', :bg=>'red', :relief=>:raised)
table.tag_configure('ON', :bg=>'green', :relief=>:sunken)
table.tag_configure('sel', :bg=>'gray75', :relief=>:flat)
# clean up if mouse leaves the widget
table.bind('Leave', proc{|w| w.selection_clear_all}, '%W')
# highlight the cell under the mouse
table.bind('Motion', proc{|w, x, y|
Tk.callback_break if w.selection_include?(TkComm._at(x,y))
w.selection_clear_all
w.selection_set(TkComm._at(x,y))
Tk.callback_break
## "break" prevents the call to tkTableCheckBorder
}, '%W %x %y')
# mousebutton 1 toggles the value of the cell
# use of "selection includes" would work here
table.bind('1', proc{|w, x, y|
#rc = w.curselection[0]
rc = w.index(TkComm._at(x,y))
if tab[rc] == 'ON'
tab[rc] = 'OFF'
w.tag_cell('OFF', rc)
else
tab[rc] = 'ON'
w.tag_cell('ON', rc)
end}, '%W %x %y')
# inititialize the array, titles, and celltags
0.step(rows){|i|
tab[i,-1] = i
0.step(cols){|j|
if i == 0
tab[-1,j] = j
end
tab[i,j] = "OFF"
table.tag_cell('OFF', "#{i},#{j}")
}
}
Tk.mainloop
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/sample/from.rb
|
#! /usr/local/bin/ruby
require "time"
require "kconv"
class String
def kjust(len)
res = ''
rlen = 0
self.each_char do |char|
delta = char.bytesize > 1 ? 2 : 1
break if rlen + delta > len
rlen += delta
res += char
end
res += ' ' * (len - rlen) if rlen < len
res
end
end
def fromout(date, from, subj)
return 0 if !date
y, m, d = Time.parse(date).to_a.reverse[4, 3] if date
y ||= 0; m ||= 0; d ||= 0
from ||= "<EMAIL>"
from.delete!("\r\n")
from = from.kconv(Encoding.default_external).kjust(28)
subj ||= "(nil)"
subj.delete!("\r\n")
subj = subj.kconv(Encoding.default_external).kjust(40)
printf "%02d/%02d/%02d [%s] %s\n", y%100, m, d, from, subj
return 1
end
def get_mailfile(user)
file = user
unless user
file = ENV['MAIL']
user = ENV['USER'] || ENV['USERNAME'] || ENV['LOGNAME']
end
if file == nil or !File.exist?(file)
[ENV['SPOOLDIR'], '/usr/spool', '/var/spool', '/usr', '/var'].each do |m|
path = "#{m}/mail/#{user}"
if File.exist?(path)
file = path
break
end
end
end
file
end
def from_main
if ARGV[0] == '-w'
wait = true
ARGV.shift
end
file = get_mailfile(ARGV[0])
outcount = 0
if File.exist?(file)
atime = File.atime(file)
mtime = File.mtime(file)
open(file, "r") do |f|
until f.eof?
header = {}
f.each_line do |line|
next if /^From / =~ line # skip From-line
break if /^$/ =~ line # end of header
if /^(?<attr>\S+?):\s*(?<value>.*)/ =~ line
attr.capitalize!
header[attr] = value
elsif attr
header[attr] += "\n" + line.lstrip
end
end
f.each_line do |line|
break if /^From / =~ line
end
outcount += fromout(header['Date'], header['From'], header['Subject'])
end
end
File.utime(atime, mtime, file)
end
if outcount == 0
print "You have no mail.\n"
sleep 2 if wait
elsif wait
system "stty cbreak -echo"
$stdin.getc
system "stty cooked echo"
end
end
if __FILE__ == $0
from_main
end
__END__
=begin
= from.rb
== USAGE
ruby from.rb [-w] [username_or_filename]
=end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/openstack/models/orchestration/events.rb
|
require 'fog/openstack/models/orchestration/event'
module Fog
module Orchestration
class OpenStack
class Events < Fog::Collection
model Fog::Orchestration::OpenStack::Event
def all(obj, options={})
data = if obj.is_a?(Stack)
service.list_stack_events(obj, options).body['events']
else
service.list_resource_events(obj.stack, obj, options).body['events']
end
load data
end
def get(stack, resource, event_id)
data = service.show_event_details(stack, resource, event_id).body['event']
new(data)
rescue Fog::Compute::OpenStack::NotFound
nil
end
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/tcllib/plotchart.rb
|
#
# tkextlib/tcllib/plotchart.rb
# by <NAME> (<EMAIL>)
#
# * Part of tcllib extension
# * Simple plotting and charting package
#
# (The following is the original description of the library.)
#
# Plotchart is a Tcl-only package that focuses on the easy creation of
# xy-plots, barcharts and other common types of graphical presentations.
# The emphasis is on ease of use, rather than flexibility. The procedures
# that create a plot use the entire canvas window, making the layout of the
# plot completely automatic.
#
# This results in the creation of an xy-plot in, say, ten lines of code:
# --------------------------------------------------------------------
# package require Plotchart
#
# canvas .c -background white -width 400 -height 200
# pack .c -fill both
#
# #
# # Create the plot with its x- and y-axes
# #
# set s [::Plotchart::createXYPlot .c {0.0 100.0 10.0} {0.0 100.0 20.0}]
#
# foreach {x y} {0.0 32.0 10.0 50.0 25.0 60.0 78.0 11.0 } {
# $s plot series1 $x $y
# }
#
# $s title "Data series"
# --------------------------------------------------------------------
#
# A drawback of the package might be that it does not do any data management.
# So if the canvas that holds the plot is to be resized, the whole plot must
# be redrawn. The advantage, though, is that it offers a number of plot and
# chart types:
#
# * XY-plots like the one shown above with any number of data series.
# * Stripcharts, a kind of XY-plots where the horizontal axis is adjusted
# automatically. The result is a kind of sliding window on the data
# series.
# * Polar plots, where the coordinates are polar instead of cartesian.
# * Isometric plots, where the scale of the coordinates in the two
# directions is always the same, i.e. a circle in world coordinates
# appears as a circle on the screen.
# You can zoom in and out, as well as pan with these plots (Note: this
# works best if no axes are drawn, the zooming and panning routines do
# not distinguish the axes), using the mouse buttons with the control
# key and the arrow keys with the control key.
# * Piecharts, with automatic scaling to indicate the proportions.
# * Barcharts, with either vertical or horizontal bars, stacked bars or
# bars side by side.
# * Timecharts, where bars indicate a time period and milestones or other
# important moments in time are represented by triangles.
# * 3D plots (both for displaying surfaces and 3D bars)
#
require 'tk'
require 'tkextlib/tcllib.rb'
# TkPackage.require('Plotchart', '0.9')
# TkPackage.require('Plotchart', '1.1')
# TkPackage.require('Plotchart', '1.6.3')
TkPackage.require('Plotchart')
module Tk
module Tcllib
module Plotchart
PACKAGE_NAME = 'Plotchart'.freeze
def self.package_name
PACKAGE_NAME
end
def self.package_version
begin
TkPackage.require('Plotchart')
rescue
''
end
end
end
end
end
module Tk::Tcllib::Plotchart
extend TkCore
############################
def self.view_port(w, *args) # args := pxmin, pymin, pxmax, pymax
tk_call_without_enc('::Plotchart::viewPort', w.path, *(args.flatten))
end
def self.world_coordinates(w, *args) # args := xmin, ymin, xmax, ymax
tk_call_without_enc('::Plotchart::worldCoordinates',
w.path, *(args.flatten))
end
def self.world_3D_coordinates(w, *args)
# args := xmin, ymin, zmin, xmax, ymax, zmax
tk_call_without_enc('::Plotchart::world3DCoordinates',
w.path, *(args.flatten))
end
def self.coords_to_pixel(w, x, y)
list(tk_call_without_enc('::Plotchart::coordsToPixel', w.path, x, y))
end
def self.coords_3D_to_pixel(w, x, y, z)
list(tk_call_without_enc('::Plotchart::coords3DToPixel', w.path, x, y, z))
end
def self.plotconfig(*args)
case args.length
when 0, 1, 2
# 0: (no args) --> list of chat types
# 1: charttype --> list of components
# 2: charttype, component --> list of properties
simplelist(tk_call('::Plotchart::plotconfig', *args))
when 3
# 3: charttype, component, property --> current value
tk_call('::Plotchart::plotconfig', *args)
else
# 4: charttype, component, property, value : set new value
# 5+: Error on Tcl/Tk
tk_call('::Plotchart::plotconfig', *args)
nil
end
end
def self.plotpack(w, dir, *plots)
tk_call_without_enc('::Plotchart::plotpack', w.path, dir, *plots)
w
end
def self.polar_coordinates(w, radmax)
tk_call_without_enc('::Plotchart::polarCoordinates', w.path, radmax)
end
def self.polar_to_pixel(w, rad, phi)
list(tk_call_without_enc('::Plotchart::polarToPixel', w.path, rad, phi))
end
def self.pixel_to_coords(w, x, y)
list(tk_call_without_enc('::Plotchart::coordsToPixel', w.path, x, y))
end
def self.determine_scale(*args) # (xmin, xmax, inverted=false)
tk_call_without_enc('::Plotchart::determineScale', *args)
end
def self.set_zoom_pan(w)
tk_call_without_enc('::Plotchart::setZoomPan', w.path)
end
############################
module ChartMethod
include TkCore
def title(str)
tk_call_without_enc(@chart, 'title', _get_eval_enc_str(str))
self
end
def save_plot(filename)
tk_call_without_enc(@chart, 'saveplot', filename)
self
end
def xtext(str)
tk_call_without_enc(@chart, 'xtext', _get_eval_enc_str(str))
self
end
def ytext(str)
tk_call_without_enc(@chart, 'ytext', _get_eval_enc_str(str))
self
end
def xconfig(key, value=None)
if key.kind_of?(Hash)
tk_call_without_enc(@chart, 'xconfig', *hash_kv(key, true))
else
tk_call(@chart, 'xconfig', "-#{key}",value)
end
self
end
def yconfig(key, value=None)
if key.kind_of?(Hash)
tk_call_without_enc(@chart, 'yconfig', *hash_kv(key, true))
else
tk_call(@chart, 'yconfig', "-#{key}", value)
end
self
end
def background(part, color_or_image, dir)
tk_call_without_enc(@chart, 'background',
part, color_or_image, dir)
self
end
def xticklines(color=None)
tk_call(@chart, 'xticklines', color)
self
end
def yticklines(color=None)
tk_call(@chart, 'yticklines', color)
self
end
def legendconfig(key, value=None)
if key.kind_of?(Hash)
tk_call_without_enc(@chart, 'legendconfig', *hash_kv(key, true))
else
tk_call(@chart, 'legendconfig', "-#{key}", value)
end
self
end
def legend(series, text)
tk_call_without_enc(@chart, 'legend',
_get_eval_enc_str(series), _get_eval_enc_str(text))
self
end
def balloon(*args) # args => (x, y, text, dir) or ([x, y], text, dir)
if args[0].kind_of?(Array)
# args => ([x, y], text, dir)
x, y = args.shift
else
# args => (x, y, text, dir)
x = args.shift
y = args.shift
end
text, dir = args
tk_call_without_enc(@chart, 'balloon', x, y,
_get_eval_enc_str(text), dir)
self
end
def balloonconfig(key, value=None)
if key.kind_of?(Hash)
tk_call_without_enc(@chart, 'balloonconfig', *hash_kv(key, true))
else
tk_call(@chart, 'balloonconfig', "-#{key}", value)
end
end
def plaintext(*args) # args => (x, y, text, dir) or ([x, y], text, dir)
if args[0].kind_of?(Array)
# args => ([x, y], text, dir)
x, y = args.shift
else
# args => (x, y, text, dir)
x = args.shift
y = args.shift
end
text, dir = args
tk_call_without_enc(@chart, 'plaintext', x, y,
_get_eval_enc_str(text), dir)
self
end
############################
def view_port(*args) # args := pxmin, pymin, pxmax, pymax
tk_call_without_enc('::Plotchart::viewPort', @path, *(args.flatten))
self
end
def world_coordinates(*args) # args := xmin, ymin, xmax, ymax
tk_call_without_enc('::Plotchart::worldCoordinates',
@path, *(args.flatten))
self
end
def world_3D_coordinates(*args)
# args := xmin, ymin, zmin, xmax, ymax, zmax
tk_call_without_enc('::Plotchart::world3DCoordinates',
@path, *(args.flatten))
self
end
def coords_to_pixel(x, y)
list(tk_call_without_enc('::Plotchart::coordsToPixel', @path, x, y))
end
def coords_3D_to_pixel(x, y, z)
list(tk_call_without_enc('::Plotchart::coords3DToPixel', @path, x, y, z))
end
def plotpack(dir, *plots)
tk_call_without_enc('::Plotchart::plotpack', @path, dir, *plots)
self
end
def polar_coordinates(radmax)
tk_call_without_enc('::Plotchart::polarCoordinates', @path, radmax)
self
end
def polar_to_pixel(rad, phi)
list(tk_call_without_enc('::Plotchart::polarToPixel', @path, rad, phi))
end
def pixel_to_coords(x, y)
list(tk_call_without_enc('::Plotchart::coordsToPixel', @path, x, y))
end
def determine_scale(xmax, ymax)
tk_call_without_enc('::Plotchart::determineScale', @path, xmax, ymax)
self
end
def set_zoom_pan()
tk_call_without_enc('::Plotchart::setZoomPan', @path)
self
end
end
############################
class XYPlot < Tk::Canvas
include ChartMethod
TkCommandNames = [
'canvas'.freeze,
'::Plotchart::createXYPlot'.freeze
].freeze
def initialize(*args) # args := ([parent,] xaxis, yaxis [, keys])
# xaxis := Array of [minimum, maximum, stepsize]
# yaxis := Array of [minimum, maximum, stepsize]
if args[0].kind_of?(Array)
@xaxis = args.shift
@yaxis = args.shift
super(*args) # create canvas widget
else
parent = args.shift
@xaxis = args.shift
@yaxis = args.shift
if parent.kind_of?(Tk::Canvas)
@path = parent.path
else
super(parent, *args) # create canvas widget
end
end
@chart = _create_chart
end
def _create_chart
p self.class::TkCommandNames[1] if $DEBUG
tk_call_without_enc(self.class::TkCommandNames[1], @path,
array2tk_list(@xaxis), array2tk_list(@yaxis))
end
private :_create_chart
def __destroy_hook__
Tk::Tcllib::Plotchart::PlotSeries::SeriesID_TBL.mutex.synchronize{
Tk::Tcllib::Plotchart::PlotSeries::SeriesID_TBL.delete(@path)
}
end
def plot(series, x, y)
tk_call_without_enc(@chart, 'plot', _get_eval_enc_str(series), x, y)
self
end
def contourlines(xcrd, ycrd, vals, clss=None)
xcrd = array2tk_list(xcrd) if xcrd.kind_of?(Array)
ycrd = array2tk_list(ycrd) if ycrd.kind_of?(Array)
vals = array2tk_list(vals) if vals.kind_of?(Array)
clss = array2tk_list(clss) if clss.kind_of?(Array)
tk_call(@chart, 'contourlines', xcrd, ycrd, vals, clss)
self
end
def contourfill(xcrd, ycrd, vals, clss=None)
xcrd = array2tk_list(xcrd) if xcrd.kind_of?(Array)
ycrd = array2tk_list(ycrd) if ycrd.kind_of?(Array)
vals = array2tk_list(vals) if vals.kind_of?(Array)
clss = array2tk_list(clss) if clss.kind_of?(Array)
tk_call(@chart, 'contourfill', xcrd, ycrd, vals, clss)
self
end
def contourbox(xcrd, ycrd, vals, clss=None)
xcrd = array2tk_list(xcrd) if xcrd.kind_of?(Array)
ycrd = array2tk_list(ycrd) if ycrd.kind_of?(Array)
vals = array2tk_list(vals) if vals.kind_of?(Array)
clss = array2tk_list(clss) if clss.kind_of?(Array)
tk_call(@chart, 'contourbox', xcrd, ycrd, vals, clss)
self
end
def color_map(colors)
colors = array2tk_list(colors) if colors.kind_of?(Array)
tk_call_without_enc(@chart, 'colorMap', colors)
self
end
def grid_cells(xcrd, ycrd)
xcrd = array2tk_list(xcrd) if xcrd.kind_of?(Array)
ycrd = array2tk_list(ycrd) if ycrd.kind_of?(Array)
tk_call_without_enc(@chart, 'grid', xcrd, ycrd)
self
end
def dataconfig(series, key, value=None)
if key.kind_of?(Hash)
tk_call_without_enc(@chart, 'dataconfig', series, *hash_kv(key, true))
else
tk_call(@chart, 'dataconfig', series, "-#{key}", value)
end
end
def rescale(xscale, yscale) # xscale|yscale => [newmin, newmax, newstep]
tk_call_without_enc(@chart, 'rescale', xscale, yscale)
self
end
def trend(series, xcrd, ycrd)
tk_call_without_enc(@chart, 'trend',
_get_eval_enc_str(series), xcrd, ycrd)
self
end
def rchart(series, xcrd, ycrd)
tk_call_without_enc(@chart, 'rchart',
_get_eval_enc_str(series), xcrd, ycrd)
self
end
def interval(series, xcrd, ymin, ymax, ycenter=None)
tk_call(@chart, 'interval', series, xcrd, ymin, ymax, ycenter)
self
end
def box_and_whiskers(series, xcrd, ycrd)
tk_call_without_enc(@chart, 'box-and-whiskers',
_get_eval_enc_str(series), xcrd, ycrd)
self
end
alias box_whiskers box_and_whiskers
def vectorconfig(series, key, value=None)
if key.kind_of?(Hash)
tk_call_without_enc(@chart, 'vectorconfig',
_get_eval_enc_str(series), *hash_kv(key, true))
else
tk_call(@chart, 'vectorconfig', series, "-#{key}", value)
end
self
end
def vector(series, xcrd, ycrd, ucmp, vcmp)
tk_call_without_enc(@chart, 'vector', _get_eval_enc_str(series),
xcrd, ycrd, ucmp, vcmp)
self
end
def dotconfig(series, key, value=None)
if key.kind_of?(Hash)
tk_call_without_enc(@chart, 'dotconfig',
_get_eval_enc_str(series), *hash_kv(key, true))
else
tk_call(@chart, 'dotconfig', series, "-#{key}", value)
end
self
end
def dot(series, xcrd, ycrd, value)
tk_call_without_enc(@chart, 'dot', _get_eval_enc_str(series),
xcrd, ycrd, value)
self
end
end
############################
class Stripchart < XYPlot
TkCommandNames = [
'canvas'.freeze,
'::Plotchart::createStripchart'.freeze
].freeze
end
############################
class TXPlot < XYPlot
TkCommandNames = [
'canvas'.freeze,
'::Plotchart::createTXPlot'.freeze
].freeze
end
############################
class XLogYPlot < XYPlot
TkCommandNames = [
'canvas'.freeze,
'::Plotchart::createXLogYPlot'.freeze
].freeze
end
############################
class Histogram < XYPlot
TkCommandNames = [
'canvas'.freeze,
'::Plotchart::createHistgram'.freeze
].freeze
end
############################
class PolarPlot < Tk::Canvas
include ChartMethod
TkCommandNames = [
'canvas'.freeze,
'::Plotchart::createPolarplot'.freeze
].freeze
def initialize(*args) # args := ([parent,] radius_data [, keys])
# radius_data := Array of [maximum_radius, stepsize]
if args[0].kind_of?(Array)
@radius_data = args.shift
super(*args) # create canvas widget
else
parent = args.shift
@radius_data = args.shift
if parent.kind_of?(Tk::Canvas)
@path = parent.path
else
super(parent, *args) # create canvas widget
end
end
@chart = _create_chart
end
def _create_chart
p self.class::TkCommandNames[1] if $DEBUG
tk_call_without_enc(self.class::TkCommandNames[1], @path,
array2tk_list(@radius_data))
end
private :_create_chart
def __destroy_hook__
Tk::Tcllib::Plotchart::PlotSeries::SeriesID_TBL.mutex.synchronize{
Tk::Tcllib::Plotchart::PlotSeries::SeriesID_TBL.delete(@path)
}
end
def plot(series, radius, angle)
tk_call_without_enc(@chart, 'plot', _get_eval_enc_str(series),
radius, angle)
self
end
def dataconfig(series, key, value=None)
if key.kind_of?(Hash)
tk_call_without_enc(@chart, 'dataconfig', _get_eval_enc_str(series),
*hash_kv(key, true))
else
tk_call(@chart, 'dataconfig', series, "-#{key}", value)
end
end
end
Polarplot = PolarPlot
############################
class IsometricPlot < Tk::Canvas
include ChartMethod
TkCommandNames = [
'canvas'.freeze,
'::Plotchart::createIsometricPlot'.freeze
].freeze
def initialize(*args) # args := ([parent,] xaxis, yaxis, [, step] [, keys])
# xaxis := Array of [minimum, maximum]
# yaxis := Array of [minimum, maximum]
# step := Float of stepsize | "noaxes" | :noaxes
if args[0].kind_of?(Array)
@xaxis = args.shift
@yaxis = args.shift
if args[0].kind_of?(Hash)
@stepsize = :noaxes
else
@stepsize = args.shift
end
super(*args) # create canvas widget
else
parent = args.shift
@xaxis = args.shift
@yaxis = args.shift
if args[0].kind_of?(Hash)
@stepsize = :noaxes
else
@stepsize = args.shift
end
if parent.kind_of?(Tk::Canvas)
@path = parent.path
else
super(parent, *args) # create canvas widget
end
end
@chart = _create_chart
end
def _create_chart
p self.class::TkCommandNames[1] if $DEBUG
tk_call_without_enc(self.class::TkCommandNames[1], @path,
array2tk_list(@xaxis), array2tk_list(@yaxis),
@stepsize)
end
private :_create_chart
def plot(type, *args)
self.__send__("plot_#{type.to_s.tr('-', '_')}", *args)
end
def plot_rectangle(*args) # args := x1, y1, x2, y2, color
tk_call_without_enc(@chart, 'plot', 'rectangle', *(args.flatten))
self
end
def plot_filled_rectangle(*args) # args := x1, y1, x2, y2, color
tk_call_without_enc(@chart, 'plot', 'filled-rectangle', *(args.flatten))
self
end
def plot_circle(*args) # args := xc, yc, radius, color
tk_call_without_enc(@chart, 'plot', 'circle', *(args.flatten))
self
end
def plot_filled_circle(*args) # args := xc, yc, radius, color
tk_call_without_enc(@chart, 'plot', 'filled-circle', *(args.flatten))
self
end
end
Isometricplot = IsometricPlot
############################
class Plot3D < Tk::Canvas
include ChartMethod
TkCommandNames = [
'canvas'.freeze,
'::Plotchart::create3DPlot'.freeze
].freeze
def initialize(*args) # args := ([parent,] xaxis, yaxis, zaxis [, keys])
# xaxis := Array of [minimum, maximum, stepsize]
# yaxis := Array of [minimum, maximum, stepsize]
# zaxis := Array of [minimum, maximum, stepsize]
if args[0].kind_of?(Array)
@xaxis = args.shift
@yaxis = args.shift
@zaxis = args.shift
super(*args) # create canvas widget
else
parent = args.shift
@xaxis = args.shift
@yaxis = args.shift
@zaxis = args.shift
if parent.kind_of?(Tk::Canvas)
@path = parent.path
else
super(parent, *args) # create canvas widget
end
end
@chart = _create_chart
end
def _create_chart
p self.class::TkCommandNames[1] if $DEBUG
tk_call_without_enc(self.class::TkCommandNames[1], @path,
array2tk_list(@xaxis),
array2tk_list(@yaxis),
array2tk_list(@zaxis))
end
private :_create_chart
def plot_function(cmd=Proc.new)
Tk.ip_eval("proc #{@path}_#{@chart} {x y} {#{install_cmd(cmd)} $x $y}")
tk_call_without_enc(@chart, 'plotfunc', "#{@path}_#{@chart}")
self
end
def plot_funcont(conts, cmd=Proc.new)
conts = array2tk_list(conts) if conts.kind_of?(Array)
Tk.ip_eval("proc #{@path}_#{@chart} {x y} {#{install_cmd(cmd)} $x $y}")
tk_call_without_enc(@chart, 'plotfuncont', "#{@path}_#{@chart}", conts)
self
end
def grid_size(nxcells, nycells)
tk_call_without_enc(@chart, 'gridsize', nxcells, nycells)
self
end
def plot_line(dat, color)
# dat has to be provided as a 2 level array.
# 1st level contains rows, drawn in y-direction,
# and each row is an array whose elements are drawn in x-direction,
# for the columns.
tk_call_without_enc(@chart, 'plotline', dat, color)
self
end
def plot_data(dat)
# dat has to be provided as a 2 level array.
# 1st level contains rows, drawn in y-direction,
# and each row is an array whose elements are drawn in x-direction,
# for the columns.
tk_call_without_enc(@chart, 'plotdata', dat)
self
end
def zconfig(key, value=None)
if key.kind_of?(Hash)
tk_call_without_enc(@chart, 'zconfig', *hash_kv(key, true))
else
tk_call(@chart, 'zconfig', "-#{key}", value)
end
self
end
def colour(fill, border)
# configure the colours to use for polygon borders and inner area
tk_call_without_enc(@chart, 'colour', fill, border)
self
end
alias colours colour
alias colors colour
alias color colour
end
############################
class Barchart3D < Tk::Canvas
include ChartMethod
TkCommandNames = [
'canvas'.freeze,
'::Plotchart::create3DBarchart'.freeze
].freeze
def initialize(*args) # args := ([parent,] yaxis, nobars [, keys])
# yaxis := Array of [minimum, maximum, stepsize]
# nobars := number of bars
if args[0].kind_of?(Array)
@yaxis = args.shift
@nobars = args.shift
super(*args) # create canvas widget
else
parent = args.shift
@yaxis = args.shift
@nobars = args.shift
if parent.kind_of?(Tk::Canvas)
@path = parent.path
else
super(parent, *args) # create canvas widget
end
end
@chart = _create_chart
end
def _create_chart
p self.class::TkCommandNames[1] if $DEBUG
tk_call_without_enc(self.class::TkCommandNames[1], @path,
array2tk_list(@yaxis), @nobars)
end
private :_create_chart
def plot(label, yvalue, color)
tk_call_without_enc(@chart, 'plot', _get_eval_enc_str(label),
_get_eval_enc_str(yvalue), color)
self
end
def config(key, value=None)
if key.kind_of?(Hash)
tk_call_without_enc(@chart, 'config', *hash_kv(key, true))
else
tk_call(@chart, 'config', "-#{key}", value)
end
self
end
end
############################
class RibbonChart3D < Tk::Canvas
include ChartMethod
TkCommandNames = [
'canvas'.freeze,
'::Plotchart::create3DRibbonChart'.freeze
].freeze
def initialize(*args) # args := ([parent,] names, yaxis, zaxis [, keys])
# names := Array of the series
# yaxis := Array of [minimum, maximum, stepsize]
# zaxis := Array of [minimum, maximum, stepsize]
if args[0].kind_of?(Array)
@names = args.shift
@yaxis = args.shift
@zaxis = args.shift
super(*args) # create canvas widget
else
parent = args.shift
@names = args.shift
@yaxis = args.shift
@zaxis = args.shift
if parent.kind_of?(Tk::Canvas)
@path = parent.path
else
super(parent, *args) # create canvas widget
end
end
@chart = _create_chart
end
def _create_chart
p self.class::TkCommandNames[1] if $DEBUG
tk_call_without_enc(self.class::TkCommandNames[1], @path,
array2tk_list(@names),
array2tk_list(@yaxis),
array2tk_list(@zaxis))
end
private :_create_chart
def line(*args) # xypairs, color
color = args.pop # last argument is a color
xypairs = TkComm.slice_ary(args.flatten, 2) # regenerate xypairs
tk_call_without_enc(@chart, 'line', xypairs, color)
self
end
def area(*args) # xypairs, color
color = args.pop # last argument is a color
xypairs = TkComm.slice_ary(args.flatten, 2) # regenerate xypairs
tk_call_without_enc(@chart, 'area', xypairs, color)
self
end
def zconfig(key, value=None)
if key.kind_of?(Hash)
tk_call_without_enc(@chart, 'zconfig', *hash_kv(key, true))
else
tk_call(@chart, 'zconfig',"-#{key}", value)
end
self
end
end
############################
class Piechart < Tk::Canvas
include ChartMethod
TkCommandNames = [
'canvas'.freeze,
'::Plotchart::createPiechart'.freeze
].freeze
def initialize(*args) # args := ([parent] [, keys])
if args[0].kind_of?(Tk::Canvas)
parent = args.shift
@path = parent.path
else
super(*args) # create canvas widget
end
@chart = _create_chart
end
def _create_chart
p self.class::TkCommandNames[1] if $DEBUG
tk_call_without_enc(self.class::TkCommandNames[1], @path)
end
private :_create_chart
def plot(*dat) # argument is a list of [label, value]
tk_call(@chart, 'plot', dat.flatten)
self
end
def colours(*list)
tk_call_without_enc(@chart, 'colours', *list)
self
end
alias colors colours
end
############################
class Radialchart < Tk::Canvas
include ChartMethod
TkCommandNames = [
'canvas'.freeze,
'::Plotchart::createRadialchart'.freeze
].freeze
def initialize(*args) # args := ([parent,] names, scale, style [, keys])
# radius_data := Array of [maximum_radius, stepsize]
if args[0].kind_of?(Array)
@names = args.shift
@scale = args.shift
@style = args.shift
super(*args) # create canvas widget
else
parent = args.shift
@names = args.shift
@scale = args.shift
@style = args.shift
if parent.kind_of?(Tk::Canvas)
@path = parent.path
else
super(parent, *args) # create canvas widget
end
end
@chart = _create_chart
end
def _create_chart
p self.class::TkCommandNames[1] if $DEBUG
tk_call_without_enc(self.class::TkCommandNames[1], @path,
array2tk_list(@names), @scale, @style)
end
private :_create_chart
def __destroy_hook__
Tk::Tcllib::Plotchart::PlotSeries::SeriesID_TBL.mutex.synchronize{
Tk::Tcllib::Plotchart::PlotSeries::SeriesID_TBL.delete(@path)
}
end
def plot(data, color, thickness)
tk_call_without_enc(@chart, 'plot', _get_eval_enc_str(data),
color, thickness)
self
end
def colours(*list)
tk_call_without_enc(@chart, 'colours', *list)
self
end
alias colors colours
end
############################
class Barchart < Tk::Canvas
include ChartMethod
TkCommandNames = [
'canvas'.freeze,
'::Plotchart::createBarchart'.freeze
].freeze
def initialize(*args)
# args := ([parent,] xlabels, ylabels [, series] [, keys])
# xlabels, ylabels := labels | axis ( depend on normal or horizontal )
# labels := Array of [label, label, ...]
# (It determines the number of bars that will be plotted per series.)
# axis := Array of [minimum, maximum, stepsize]
# series := Integer number of data series | 'stacked' | :stacked
if args[0].kind_of?(Array)
@xlabels = args.shift
@ylabels = args.shift
if args[0].kind_of?(Hash)
@series_size = :stacked
else
@series_size = args.shift
end
super(*args) # create canvas widget
else
parent = args.shift
@xlabels = args.shift
@ylabels = args.shift
if args[0].kind_of?(Hash)
@series_size = :stacked
else
@series_size = args.shift
end
if parent.kind_of?(Tk::Canvas)
@path = parent.path
else
super(parent, *args) # create canvas widget
end
end
@chart = _create_chart
end
def _create_chart
p self.class::TkCommandNames[1] if $DEBUG
tk_call_without_enc(self.class::TkCommandNames[1], @path,
array2tk_list(@xlabels), array2tk_list(@ylabels),
@series_size)
end
private :_create_chart
def __destroy_hook__
Tk::Tcllib::Plotchart::PlotSeries::SeriesID_TBL.mutex.synchronize{
Tk::Tcllib::Plotchart::PlotSeries::SeriesID_TBL.delete(@path)
}
end
def plot(series, dat, col=None)
tk_call(@chart, 'plot', series, dat, col)
self
end
def colours(*cols)
# set the colours to be used
tk_call(@chart, 'colours', *cols)
self
end
alias colour colours
alias colors colours
alias color colours
end
############################
class HorizontalBarchart < Barchart
TkCommandNames = [
'canvas'.freeze,
'::Plotchart::createHorizontalBarchart'.freeze
].freeze
end
############################
class Boxplot < Tk::Canvas
include ChartMethod
TkCommandNames = [
'canvas'.freeze,
'::Plotchart::createBoxplot'.freeze
].freeze
def initialize(*args) # args := ([parent,] xaxis, ylabels [, keys])
# xaxis := Array of [minimum, maximum, stepsize]
# yaxis := List of labels for the y-axis
if args[0].kind_of?(Array)
@xaxis = args.shift
@ylabels = args.shift
super(*args) # create canvas widget
else
parent = args.shift
@xaxis = args.shift
@ylabels = args.shift
if parent.kind_of?(Tk::Canvas)
@path = parent.path
else
super(parent, *args) # create canvas widget
end
end
@chart = _create_chart
end
def _create_chart
p self.class::TkCommandNames[1] if $DEBUG
tk_call_without_enc(self.class::TkCommandNames[1], @path,
array2tk_list(@xaxis), array2tk_list(@ylabels))
end
private :_create_chart
def __destroy_hook__
Tk::Tcllib::Plotchart::PlotSeries::SeriesID_TBL.mutex.synchronize{
Tk::Tcllib::Plotchart::PlotSeries::SeriesID_TBL.delete(@path)
}
end
def plot(label, *values)
tk_call(@chart, 'plot', label, values.flatten)
self
end
end
############################
class RightAxis < Tk::Canvas
include ChartMethod
TkCommandNames = [
'canvas'.freeze,
'::Plotchart::createRightAxis'.freeze
].freeze
def initialize(*args) # args := ([parent,] yaxis [, keys])
# yaxis := Array of [minimum, maximum, stepsize]
if args[0].kind_of?(Array)
@yaxis = args.shift
super(*args) # create canvas widget
else
parent = args.shift
@yaxis = args.shift
if parent.kind_of?(Tk::Canvas)
@path = parent.path
else
super(parent, *args) # create canvas widget
end
end
@chart = _create_chart
end
def _create_chart
p self.class::TkCommandNames[1] if $DEBUG
tk_call_without_enc(self.class::TkCommandNames[1], @path,
array2tk_list(@yaxis))
end
private :_create_chart
def __destroy_hook__
Tk::Tcllib::Plotchart::PlotSeries::SeriesID_TBL.mutex.synchronize{
Tk::Tcllib::Plotchart::PlotSeries::SeriesID_TBL.delete(@path)
}
end
end
############################
class Timechart < Tk::Canvas
include ChartMethod
TkCommandNames = [
'canvas'.freeze,
'::Plotchart::createTimechart'.freeze
].freeze
def initialize(*args)
# args := ([parent,] time_begin, time_end, items [, keys])
# time_begin := String of time format (e.g. "1 january 2004")
# time_end := String of time format (e.g. "1 january 2004")
# items := Expected/maximum number of items
# ( This determines the vertical spacing. )
if args[0].kind_of?(String)
@time_begin = args.shift
@time_end = args.shift
@items = args.shift
super(*args) # create canvas widget
else
parent = args.shift
@time_begin = args.shift
@time_end = args.shift
@items = args.shift
if parent.kind_of?(Tk::Canvas)
@path = parent.path
else
super(parent, *args) # create canvas widget
end
end
@chart = _create_chart
end
def _create_chart
p self.class::TkCommandNames[1] if $DEBUG
tk_call_without_enc(self.class::TkCommandNames[1], @path,
@time_begin, @time_end, @items)
end
private :_create_chart
def period(txt, time_begin, time_end, col=None)
tk_call(@chart, 'period', txt, time_begin, time_end, col)
self
end
def milestone(txt, time, col=None)
tk_call(@chart, 'milestone', txt, time, col)
self
end
def vertline(txt, time)
tk_call(@chart, 'vertline', txt, time)
self
end
def hscroll=(scr)
tk_call_without_enc(@chart, 'hscroll', scr)
scr
end
def hscroll(scr)
tk_call_without_enc(@chart, 'hscroll', scr)
self
end
def vscroll=(scr)
tk_call_without_enc(@chart, 'vscroll', scr)
scr
end
def vscroll(scr)
tk_call_without_enc(@chart, 'vscroll', scr)
self
end
end
############################
class Ganttchart < Tk::Canvas
include ChartMethod
TkCommandNames = [
'canvas'.freeze,
'::Plotchart::createGanttchart'.freeze
].freeze
def initialize(*args)
# args := ([parent,] time_begin, time_end, items [, text_width] [, keys])
# time_begin := String of time format (e.g. "1 january 2004")
# time_end := String of time format (e.g. "1 january 2004")
# args := Expected/maximum number of items
# ( This determines the vertical spacing. ),
# Expected/maximum width of items,
# Option Hash ( { key=>value, ... } )
if args[0].kind_of?(String)
@time_begin = args.shift
@time_end = args.shift
@args = args
super(*args) # create canvas widget
else
parent = args.shift
@time_begin = args.shift
@time_end = args.shift
@args = args
if parent.kind_of?(Tk::Canvas)
@path = parent.path
else
super(parent, *args) # create canvas widget
end
end
@chart = _create_chart
end
def _create_chart
p self.class::TkCommandNames[1] if $DEBUG
tk_call(self.class::TkCommandNames[1], @path,
@time_begin, @time_end, *args)
end
private :_create_chart
def task(txt, time_begin, time_end, completed=0.0)
list(tk_call(@chart, 'task', txt, time_begin, time_end,
completed)).collect!{|id|
TkcItem.id2obj(self, id)
}
end
def milestone(txt, time, col=None)
tk_call(@chart, 'milestone', txt, time, col)
self
end
def vertline(txt, time)
tk_call(@chart, 'vertline', txt, time)
self
end
def connect(from_task, to_task)
from_task = array2tk_list(from_task) if from_task.kind_of?(Array)
to_task = array2tk_list(to_task) if to_task.kind_of?(Array)
tk_call(@chart, 'connect', from_task, to_task)
self
end
def summary(txt, tasks)
tasks = array2tk_list(tasks) if tasks.kind_of?(Array)
tk_call(@chart, 'summary', tasks)
self
end
def color_of_part(keyword, newcolor)
tk_call(@chart, 'color', keyword, newcolor)
self
end
def font_of_part(keyword, newfont)
tk_call(@chart, 'font', keyword, newfont)
self
end
def hscroll=(scr)
tk_call_without_enc(@chart, 'hscroll', scr)
scr
end
def hscroll(scr)
tk_call_without_enc(@chart, 'hscroll', scr)
self
end
def vscroll=(scr)
tk_call_without_enc(@chart, 'vscroll', scr)
scr
end
def vscroll(scr)
tk_call_without_enc(@chart, 'vscroll', scr)
self
end
end
############################
class PlotSeries < TkObject
SeriesID_TBL = TkCore::INTERP.create_table
(Series_ID = ['series'.freeze, TkUtil.untrust('00000')]).instance_eval{
@mutex = Mutex.new
def mutex; @mutex; end
freeze
}
TkCore::INTERP.init_ip_env{
SeriesID_TBL.mutex.synchronize{ SeriesID_TBL.clear }
}
def self.id2obj(chart, id)
path = chart.path
SeriesID_TBL.mutex.synchronize{
if SeriesID_TBL[path]
SeriesID_TBL[path][id]? SeriesID_TBL[path][id]: id
else
id
end
}
end
def initialize(chart, keys=nil)
@parent = @chart_obj = chart
@ppath = @chart_obj.path
Series_ID.mutex.synchronize{
@path = @series = @id = Series_ID.join(TkCore::INTERP._ip_id_)
Series_ID[1].succ!
}
SeriesID_TBL.mutex.synchronize{
SeriesID_TBL[@ppath] ||= {}
SeriesID_TBL[@ppath][@id] = self
}
dataconfig(keys) if keys.kind_of?(Hash)
end
def plot(*args)
@chart_obj.plot(@series, *args)
end
def dataconfig(key, value=None)
@chart_obj.dataconfig(@series, key, value)
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/specifications/net-ssh-2.2.2.gemspec
|
# -*- encoding: utf-8 -*-
# stub: net-ssh 2.2.2 ruby lib
Gem::Specification.new do |s|
s.name = "net-ssh"
s.version = "2.2.2"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib"]
s.authors = ["<NAME>", "<NAME>"]
s.date = "2012-01-05"
s.description = "Net::SSH: a pure-Ruby implementation of the SSH2 client protocol."
s.email = ["<EMAIL>"]
s.extra_rdoc_files = ["README.rdoc", "THANKS.rdoc", "CHANGELOG.rdoc"]
s.files = ["CHANGELOG.rdoc", "README.rdoc", "THANKS.rdoc"]
s.homepage = "http://github.com/net-ssh/net-ssh"
s.rdoc_options = ["--line-numbers", "--title", "Net::SSH: a pure-Ruby implementation of the SSH2 client protocol.", "--main", "README.rdoc"]
s.rubyforge_project = "net-ssh"
s.rubygems_version = "2.5.1"
s.summary = "Net::SSH: a pure-Ruby implementation of the SSH2 client protocol."
s.installed_by_version = "2.5.1" if s.respond_to? :installed_by_version
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/benchmark/prepare_so_reverse_complement.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/benchmark/prepare_so_reverse_complement.rb<gh_stars>10-100
require File.join(File.dirname(__FILE__), 'make_fasta_output')
prepare_fasta_output(2_500_000)
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/test_shellwords.rb
|
<filename>.rvm/src/ruby-2.3.0/test/test_shellwords.rb<gh_stars>1-10
# -*- coding: utf-8 -*-
# frozen_string_literal: false
require 'test/unit'
require 'shellwords'
class TestShellwords < Test::Unit::TestCase
include Shellwords
def test_shellwords
cmd1 = "ruby -i'.bak' -pe \"sub /foo/, '\\\\&bar'\" foobar\\ me.txt\n"
assert_equal(['ruby', '-i.bak', '-pe', "sub /foo/, '\\&bar'", "foobar me.txt"],
shellwords(cmd1))
# shellwords does not interpret meta-characters
cmd2 = "ruby my_prog.rb | less"
assert_equal(['ruby', 'my_prog.rb', '|', 'less'],
shellwords(cmd2))
end
def test_unmatched_double_quote
bad_cmd = 'one two "three'
assert_raise ArgumentError do
shellwords(bad_cmd)
end
end
def test_unmatched_single_quote
bad_cmd = "one two 'three"
assert_raise ArgumentError do
shellwords(bad_cmd)
end
end
def test_unmatched_quotes
bad_cmd = "one '"'"''""'""
assert_raise ArgumentError do
shellwords(bad_cmd)
end
end
def test_backslashes
cmdline, expected = [
%q{/a//b///c////d/////e/ "/a//b///c////d/////e/ "'/a//b///c////d/////e/ '/a//b///c////d/////e/ },
%q{a/b/c//d//e a/b/c//d//e /a//b///c////d/////e/ a/b/c//d//e }
].map { |str| str.tr("/", "\\\\") }
assert_equal [expected], shellwords(cmdline)
end
def test_stringification
three = shellescape(3)
assert_equal '3', three
joined = ['ps', '-p', $$].shelljoin
assert_equal "ps -p #{$$}", joined
end
def test_whitespace
empty = ''
space = " "
newline = "\n"
tab = "\t"
tokens = [
empty,
space,
space * 2,
newline,
newline * 2,
tab,
tab * 2,
empty,
space + newline + tab,
empty
]
tokens.each { |token|
assert_equal [token], shellescape(token).shellsplit
}
assert_equal tokens, shelljoin(tokens).shellsplit
end
def test_frozenness
[
shellescape(String.new),
shellescape(String.new('foo')),
shellescape(''.freeze),
shellescape("\n".freeze),
shellescape('foo'.freeze),
shelljoin(['ps'.freeze, 'ax'.freeze]),
].each { |object|
assert_not_predicate object, :frozen?
}
[
shellsplit('ps'),
shellsplit('ps ax'),
].each { |array|
array.each { |arg|
assert_not_predicate arg, :frozen?, array.inspect
}
}
end
def test_multibyte_characters
# This is not a spec. It describes the current behavior which may
# be changed in future. There would be no multibyte character
# used as shell meta-character that needs to be escaped.
assert_equal "\\あ\\い", "あい".shellescape
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/spec/unit/system_spec.rb
|
#
# Author:: <NAME> (<<EMAIL>>)
# Copyright:: Copyright (c) 2008 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.
#
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper.rb')
describe Ohai::System, "initialize" do
it "should return an Ohai::System object" do
Ohai::System.new.should be_a_kind_of(Ohai::System)
end
it "should set @data to a Mash" do
Ohai::System.new.data.should be_a_kind_of(Mash)
end
it "should set @seen_plugins to a Hash" do
Ohai::System.new.seen_plugins.should be_a_kind_of(Hash)
end
end
describe Ohai::System, "method_missing" do
before(:each) do
@ohai = Ohai::System.new
end
it "should take a missing method and store the method name as a key, with its arguments as values" do
@ohai.guns_n_roses("chinese democracy")
@ohai.data["guns_n_roses"].should eql("chinese democracy")
end
it "should return the current value of the method name" do
@ohai.guns_n_roses("chinese democracy").should eql("chinese democracy")
end
it "should allow you to get the value of a key by calling method_missing with no arguments" do
@ohai.guns_n_roses("chinese democracy")
@ohai.guns_n_roses.should eql("chinese democracy")
end
end
describe Ohai::System, "attribute?" do
before(:each) do
@ohai = Ohai::System.new
@ohai.metallica("death magnetic")
end
it "should return true if an attribute exists with the given name" do
@ohai.attribute?("metallica").should eql(true)
end
it "should return false if an attribute does not exist with the given name" do
@ohai.attribute?("alice in chains").should eql(false)
end
end
describe Ohai::System, "set_attribute" do
before(:each) do
@ohai = Ohai::System.new
end
it "should let you set an attribute" do
@ohai.set_attribute(:tea, "is soothing")
@ohai.data["tea"].should eql("is soothing")
end
end
describe Ohai::System, "get_attribute" do
before(:each) do
@ohai = Ohai::System.new
@ohai.set_attribute(:tea, "is soothing")
end
it "should let you get an attribute" do
@ohai.get_attribute("tea").should eql("is soothing")
end
end
describe Ohai::System, "require_plugin" do
tmp = ENV['TMPDIR'] || ENV['TMP'] || ENV['TEMP'] || '/tmp'
before(:each) do
@plugin_path = Ohai::Config[:plugin_path]
Ohai::Config[:plugin_path] = ["#{tmp}/plugins"]
File.stub!(:exists?).and_return(true)
@ohai = Ohai::System.new
@ohai.stub!(:from_file).and_return(true)
end
after(:each) do
Ohai::Config[:plugin_path] = @plugin_path
end
it "should convert the name of the plugin to a file path" do
plugin_name = "foo::bar"
plugin_name.should_receive(:gsub).with("::", File::SEPARATOR)
@ohai.require_plugin(plugin_name)
end
it "should check each part of the Ohai::Config[:plugin_path] for the plugin_filename.rb" do
@ohai.should_receive(:from_file).with(File.expand_path("#{tmp}/plugins/foo.rb")).and_return(true)
@ohai.require_plugin("foo")
end
it "should add a found plugin to the list of seen plugins" do
@ohai.require_plugin("foo")
@ohai.seen_plugins["foo"].should eql(true)
end
it "should return true if the plugin has been seen" do
@ohai.seen_plugins["foo"] = true
@ohai.require_plugin("foo")
end
it "should return true if the plugin has been loaded" do
@ohai.require_plugin("foo").should eql(true)
end
it "should return false if the plugin is in the disabled plugins list" do
Ohai::Config[:disabled_plugins] = [ "foo" ]
Ohai::Log.should_receive(:debug).with("Skipping disabled plugin foo")
@ohai.require_plugin("foo").should eql(false)
end
end
describe Ohai::System, "all_plugins" do
before(:each) do
@ohai = Ohai::System.new
@ohai.stub!(:from_file).and_return(true)
@ohai.stub!(:require_plugin).and_return(false)
@ohai.data[:os] = "ubuntu"
end
it "should load plugins when plugin_path has a trailing slash" do
Ohai::Config[:plugin_path] = ["/tmp/plugins/"]
File.stub(:expand_path).with("/tmp/plugins/").and_return("/tmp/plugins") # windows
Dir.should_receive(:[]).with("/tmp/plugins/*").and_return(["/tmp/plugins/darius.rb"])
Dir.should_receive(:[]).with("/tmp/plugins/ubuntu/**/*").and_return([])
@ohai.should_receive(:require_plugin).with("darius")
@ohai.all_plugins
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/bwidget/dropsite.rb
|
<gh_stars>10-100
#
# tkextlib/bwidget/dropsite.rb
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tkextlib/bwidget.rb'
module Tk
module BWidget
module DropSite
end
end
end
module Tk::BWidget::DropSite
include Tk
extend Tk
def self.include(klass, type)
tk_call('DropSite::include', klass, type)
end
def self.register(path, keys={})
tk_call('DropSite::register', path, *hash_kv(keys))
end
def self.set_cursor(cursor)
tk_call('DropSite::setcursor', cursor)
end
def self.set_drop(path, subpath, dropover, drop, force=None)
tk_call('DropSite::setdrop', path, subpath, dropover, drop, force)
end
def self.set_operation(op)
tk_call('DropSite::setoperation', op)
end
end
|
arnab0073/idea
|
.rvm/rubies/ruby-1.9.3-p551/lib/ruby/gems/1.9.1/specifications/minitest-2.5.1.gemspec
|
Gem::Specification.new do |s|
s.name = "minitest"
s.version = "2.5.1"
s.summary = "This minitest is bundled with Ruby"
s.executables = []
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/lib/rubygems/core_ext/kernel_gem.rb
|
# frozen_string_literal: false
##
# RubyGems adds the #gem method to allow activation of specific gem versions
# and overrides the #require method on Kernel to make gems appear as if they
# live on the <code>$LOAD_PATH</code>. See the documentation of these methods
# for further detail.
module Kernel
# REFACTOR: This should be pulled out into some kind of hacks file.
remove_method :gem if 'method' == defined? gem # from gem_prelude.rb on 1.9
##
# Use Kernel#gem to activate a specific version of +gem_name+.
#
# +requirements+ is a list of version requirements that the
# specified gem must match, most commonly "= example.version.number". See
# Gem::Requirement for how to specify a version requirement.
#
# If you will be activating the latest version of a gem, there is no need to
# call Kernel#gem, Kernel#require will do the right thing for you.
#
# Kernel#gem returns true if the gem was activated, otherwise false. If the
# gem could not be found, didn't match the version requirements, or a
# different version was already activated, an exception will be raised.
#
# Kernel#gem should be called *before* any require statements (otherwise
# RubyGems may load a conflicting library version).
#
# Kernel#gem only loads prerelease versions when prerelease +requirements+
# are given:
#
# gem 'rake', '>= 1.1.a', '< 2'
#
# In older RubyGems versions, the environment variable GEM_SKIP could be
# used to skip activation of specified gems, for example to test out changes
# that haven't been installed yet. Now RubyGems defers to -I and the
# RUBYLIB environment variable to skip activation of a gem.
#
# Example:
#
# GEM_SKIP=libA:libB ruby -I../libA -I../libB ./mycode.rb
def gem(gem_name, *requirements) # :doc:
skip_list = (ENV['GEM_SKIP'] || "").split(/:/)
raise Gem::LoadError, "skipping #{gem_name}" if skip_list.include? gem_name
if gem_name.kind_of? Gem::Dependency
unless Gem::Deprecate.skip
warn "#{Gem.location_of_caller.join ':'}:Warning: Kernel.gem no longer "\
"accepts a Gem::Dependency object, please pass the name "\
"and requirements directly"
end
requirements = gem_name.requirement
gem_name = gem_name.name
end
dep = Gem::Dependency.new(gem_name, *requirements)
loaded = Gem.loaded_specs[gem_name]
return false if loaded && dep.matches_spec?(loaded)
spec = dep.to_spec
Gem::LOADED_SPECS_MUTEX.synchronize {
spec.activate
} if spec
end
private :gem
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/gems/did_you_mean-1.0.0/test/core_ext/name_error_extension_test.rb
|
require 'test_helper'
class NameErrorExtensionTest < Minitest::Test
SPELL_CHECKERS = DidYouMean::SPELL_CHECKERS
class TestSpellChecker
def initialize(*); end
def corrections; ["Y U SO SLOW?"]; end
end
def setup
@org, SPELL_CHECKERS['NameError'] = SPELL_CHECKERS['NameError'], TestSpellChecker
@error = assert_raises(NameError){ doesnt_exist }
end
def teardown
SPELL_CHECKERS['NameError'] = @org
end
def test_message_provides_original_message
assert_match "undefined local variable or method", @error.to_s
end
def test_message
assert_match "Did you mean? Y U SO SLOW?", @error.to_s
assert_match "Did you mean? Y U SO SLOW?", @error.message
end
def test_to_s_does_not_make_disruptive_changes_to_error_message
error = assert_raises(NameError) do
raise NameError, "uninitialized constant Object"
end
assert_equal 1, error.to_s.scan("Did you mean?").count
end
end
class IgnoreCallersTest < Minitest::Test
SPELL_CHECKERS = DidYouMean::SPELL_CHECKERS
class Boomer
def initialize(*)
raise Exception, "spell checker was created when it shouldn't!"
end
end
def setup
@org, SPELL_CHECKERS['NameError'] = SPELL_CHECKERS['NameError'], Boomer
DidYouMean::IGNORED_CALLERS << /( |`)do_not_correct_typo'/
@error = assert_raises(NameError){ doesnt_exist }
end
def teardown
SPELL_CHECKERS['NameError'] = @org
DidYouMean::IGNORED_CALLERS.clear
end
def test_ignore
assert_nothing_raised { do_not_correct_typo }
end
private
def do_not_correct_typo; @error.message end
def assert_nothing_raised
yield
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/bwidget/bitmap.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/bwidget/bitmap.rb<gh_stars>10-100
#
# tkextlib/bwidget/bitmap.rb
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tk/image'
require 'tkextlib/bwidget.rb'
module Tk
module BWidget
class Bitmap < TkPhotoImage
end
end
end
class Tk::BWidget::Bitmap
def initialize(name)
@path = tk_call_without_enc('Bitmap::get', name)
Tk_IMGTBL[@path] = self
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/iwidgets/panedwindow.rb
|
#
# tkextlib/iwidgets/panedwindow.rb
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tkextlib/iwidgets.rb'
module Tk
module Iwidgets
class Panedwindow < Tk::Itk::Widget
end
end
end
class Tk::Iwidgets::Panedwindow
TkCommandNames = ['::iwidgets::panedwindow'.freeze].freeze
WidgetClassName = 'Panedwindow'.freeze
WidgetClassNames[WidgetClassName] ||= self
####################################
include TkItemConfigMethod
def __item_cget_cmd(id)
[self.path, 'panecget', id]
end
private :__item_cget_cmd
def __item_config_cmd(id)
[self.path, 'paneconfigure', id]
end
private :__item_config_cmd
def tagid(tagOrId)
if tagOrId.kind_of?(Tk::Itk::Component)
tagOrId.name
else
#_get_eval_string(tagOrId)
tagOrId
end
end
alias panecget_tkstring itemcget_tkstring
alias panecget itemcget
alias panecget_strict itemcget_strict
alias paneconfigure itemconfigure
alias paneconfiginfo itemconfiginfo
alias current_paneconfiginfo current_itemconfiginfo
private :itemcget_tkstring, :itemcget, :itemcget_strict
private :itemconfigure, :itemconfiginfo, :current_itemconfiginfo
####################################
def __boolval_optkeys
super() << 'showhandle'
end
private :__boolval_optkeys
def add(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', tagid(tag), *hash_kv(keys)))
tag
end
def child_site_list
list(tk_call(@path, 'childsite'))
end
def child_site(idx)
window(tk_call(@path, 'childsite', index(idx)))
end
def delete(idx)
tk_call(@path, 'delete', index(idx))
self
end
def fraction(*percentages)
tk_call(@path, 'fraction', *percentages)
self
end
def hide(idx)
tk_call(@path, 'hide', index(idx))
self
end
def index(idx)
number(tk_call(@path, 'index', tagid(idx)))
end
def insert(idx, 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), tagid(tag), *hash_kv(keys)))
tag
end
def invoke(idx=nil)
if idx
tk_call(@path, 'invoke', index(idx))
else
tk_call(@path, 'invoke')
end
self
end
def reset
tk_call(@path, 'reset')
self
end
def show(idx)
tk_call(@path, 'show', index(idx))
self
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/ripper/test_parser_events.rb
|
begin
require_relative 'dummyparser'
require 'test/unit'
ripper_test = true
module TestRipper; end
rescue LoadError
end
class TestRipper::ParserEvents < Test::Unit::TestCase
def test_event_coverage
dispatched = Ripper::PARSER_EVENTS
tested = self.class.instance_methods(false).grep(/\Atest_(\w+)/) {$1.intern}
assert_empty dispatched-tested
end
def parse(str, nm = nil, &bl)
dp = DummyParser.new(str)
dp.hook(*nm, &bl) if nm
dp.parse.to_s
end
def compile_error(str)
parse(str, :compile_error) {|e, msg| return msg}
end
def warning(str)
parse(str, :warning) {|e, *args| return args}
end
def warn(str)
parse(str, :warn) {|e, *args| return args}
end
def test_program
thru_program = false
assert_equal '[void()]', parse('', :on_program) {thru_program = true}
assert_equal true, thru_program
end
def test_stmts_new
assert_equal '[void()]', parse('')
end
def test_stmts_add
assert_equal '[ref(nil)]', parse('nil')
assert_equal '[ref(nil),ref(nil)]', parse('nil;nil')
assert_equal '[ref(nil),ref(nil),ref(nil)]', parse('nil;nil;nil')
end
def test_void_stmt
assert_equal '[void()]', parse('')
assert_equal '[void()]', parse('; ;')
end
def test_var_ref
assert_equal '[assign(var_field(a),ref(a))]', parse('a=a')
assert_equal '[ref(nil)]', parse('nil')
assert_equal '[ref(true)]', parse('true')
end
def test_vcall
assert_equal '[vcall(a)]', parse('a')
end
def test_BEGIN
assert_equal '[BEGIN([void()])]', parse('BEGIN{}')
assert_equal '[BEGIN([ref(nil)])]', parse('BEGIN{nil}')
end
def test_END
assert_equal '[END([void()])]', parse('END{}')
assert_equal '[END([ref(nil)])]', parse('END{nil}')
end
def test_alias
assert_equal '[alias(symbol_literal(a),symbol_literal(b))]', parse('alias a b')
end
def test_var_alias
assert_equal '[valias($a,$g)]', parse('alias $a $g')
end
def test_alias_error
assert_equal '[aliaserr(valias($a,$1))]', parse('alias $a $1')
end
def test_arglist
assert_equal '[fcall(m,[])]', parse('m()')
assert_equal '[fcall(m,[1])]', parse('m(1)')
assert_equal '[fcall(m,[1,2])]', parse('m(1,2)')
assert_equal '[fcall(m,[*vcall(r)])]', parse('m(*r)')
assert_equal '[fcall(m,[1,*vcall(r)])]', parse('m(1,*r)')
assert_equal '[fcall(m,[1,2,*vcall(r)])]', parse('m(1,2,*r)')
assert_equal '[fcall(m,[&vcall(r)])]', parse('m(&r)')
assert_equal '[fcall(m,[1,&vcall(r)])]', parse('m(1,&r)')
assert_equal '[fcall(m,[1,2,&vcall(r)])]', parse('m(1,2,&r)')
assert_equal '[fcall(m,[*vcall(a),&vcall(b)])]', parse('m(*a,&b)')
assert_equal '[fcall(m,[1,*vcall(a),&vcall(b)])]', parse('m(1,*a,&b)')
assert_equal '[fcall(m,[1,2,*vcall(a),&vcall(b)])]', parse('m(1,2,*a,&b)')
end
def test_args_add
thru_args_add = false
parse('m(a)', :on_args_add) {thru_args_add = true}
assert_equal true, thru_args_add
end
def test_args_add_block
thru_args_add_block = false
parse('m(&b)', :on_args_add_block) {thru_args_add_block = true}
assert_equal true, thru_args_add_block
end
def test_args_add_star
thru_args_add_star = false
parse('m(*a)', :on_args_add_star) {thru_args_add_star = true}
assert_equal true, thru_args_add_star
thru_args_add_star = false
parse('m(*a, &b)', :on_args_add_star) {thru_args_add_star = true}
assert_equal true, thru_args_add_star
end
def test_args_new
thru_args_new = false
parse('m()', :on_args_new) {thru_args_new = true}
assert_equal true, thru_args_new
end
def test_arg_paren
# FIXME
end
def test_aref
assert_equal '[aref(vcall(v),[1])]', parse('v[1]')
assert_equal '[aref(vcall(v),[1,2])]', parse('v[1,2]')
end
def test_assoclist_from_args
thru_assoclist_from_args = false
parse('{a=>b}', :on_assoclist_from_args) {thru_assoclist_from_args = true}
assert_equal true, thru_assoclist_from_args
end
def test_assocs
assert_equal '[fcall(m,[assocs(assoc(1,2))])]', parse('m(1=>2)')
assert_equal '[fcall(m,[assocs(assoc(1,2),assoc(3,4))])]', parse('m(1=>2,3=>4)')
assert_equal '[fcall(m,[3,assocs(assoc(1,2))])]', parse('m(3,1=>2)')
end
def test_assoc_new
thru_assoc_new = false
parse('{a=>b}', :on_assoc_new) {thru_assoc_new = true}
assert_equal true, thru_assoc_new
end
def test_assoc_splat
thru_assoc_splat = false
parse('m(**h)', :on_assoc_splat) {thru_assoc_splat = true}
assert_equal true, thru_assoc_splat
end
def test_aref_field
assert_equal '[assign(aref_field(vcall(a),[1]),2)]', parse('a[1]=2')
end
def test_arg_ambiguous
thru_arg_ambiguous = false
parse('m //', :on_arg_ambiguous) {thru_arg_ambiguous = true}
assert_equal true, thru_arg_ambiguous
end
def test_operator_ambiguous
thru_operator_ambiguous = false
parse('a=1; a %[]', :on_operator_ambiguous) {thru_operator_ambiguous = true}
assert_equal true, thru_operator_ambiguous
end
def test_array # array literal
assert_equal '[array([1,2,3])]', parse('[1,2,3]')
assert_equal '[array([abc,def])]', parse('%w[abc def]')
assert_equal '[array([abc,def])]', parse('%W[abc def]')
end
def test_assign # generic assignment
assert_equal '[assign(var_field(v),1)]', parse('v=1')
end
def test_assign_error
# for test_coverage
end
def test_assign_error_backref
thru_assign_error = false
parse('$` = 1', :on_assign_error) {thru_assign_error = true}
assert_equal true, thru_assign_error
thru_assign_error = false
parse('$`, _ = 1', :on_assign_error) {thru_assign_error = true}
assert_equal true, thru_assign_error
end
def test_assign_error_const_qualified
thru_assign_error = false
parse('self::X = 1', :on_assign_error) {thru_assign_error = true}
assert_equal false, thru_assign_error
parse("def m\n self::X = 1\nend", :on_assign_error) {thru_assign_error = true}
assert_equal true, thru_assign_error
thru_assign_error = false
parse("def m\n self::X, a = 1, 2\nend", :on_assign_error) {thru_assign_error = true}
assert_equal true, thru_assign_error
end
def test_assign_error_const
thru_assign_error = false
parse('X = 1', :on_assign_error) {thru_assign_error = true}
assert_equal false, thru_assign_error
parse("def m\n X = 1\nend", :on_assign_error) {thru_assign_error = true}
assert_equal true, thru_assign_error
thru_assign_error = false
parse("def m\n X, a = 1, 2\nend", :on_assign_error) {thru_assign_error = true}
assert_equal true, thru_assign_error
end
def test_assign_error_const_toplevel
thru_assign_error = false
parse('::X = 1', :on_assign_error) {thru_assign_error = true}
assert_equal false, thru_assign_error
parse("def m\n ::X = 1\nend", :on_assign_error) {thru_assign_error = true}
assert_equal true, thru_assign_error
thru_assign_error = false
parse("def m\n ::X, a = 1, 2\nend", :on_assign_error) {thru_assign_error = true}
assert_equal true, thru_assign_error
end
def test_bare_assoc_hash
thru_bare_assoc_hash = false
parse('x[a=>b]', :on_bare_assoc_hash) {thru_bare_assoc_hash = true}
assert_equal true, thru_bare_assoc_hash
thru_bare_assoc_hash = false
parse('x[1, a=>b]', :on_bare_assoc_hash) {thru_bare_assoc_hash = true}
assert_equal true, thru_bare_assoc_hash
thru_bare_assoc_hash = false
parse('x(a=>b)', :on_bare_assoc_hash) {thru_bare_assoc_hash = true}
assert_equal true, thru_bare_assoc_hash
thru_bare_assoc_hash = false
parse('x(1, a=>b)', :on_bare_assoc_hash) {thru_bare_assoc_hash = true}
assert_equal true, thru_bare_assoc_hash
end
def test_begin
thru_begin = false
parse('begin end', :on_begin) {thru_begin = true}
assert_equal true, thru_begin
end
%w"and or + - * / % ** | ^ & <=> > >= < <= == === != =~ !~ << >> && ||".each do |op|
define_method("test_binary(#{op})") do
thru_binary = false
parse("a #{op} b", :on_binary) {thru_binary = true}
assert_equal true, thru_binary
end
end
def test_blockarg
thru_blockarg = false
parse("def a(&b) end", :on_blockarg) {thru_blockarg = true}
assert_equal true, thru_blockarg
thru_blockarg = false
parse("def a(x, &b) end", :on_blockarg) {thru_blockarg = true}
assert_equal true, thru_blockarg
thru_blockarg = false
parse("proc{|&b|}", :on_blockarg) {thru_blockarg = true}
assert_equal true, thru_blockarg
thru_blockarg = false
parse("proc{|x, &b|}", :on_blockarg) {thru_blockarg = true}
assert_equal true, thru_blockarg
thru_blockarg = false
parse("proc{|&b;y|}", :on_blockarg) {thru_blockarg = true}
assert_equal true, thru_blockarg
thru_blockarg = false
parse("proc{|&b,x;y|}", :on_blockarg) {thru_blockarg = true}
assert_equal true, thru_blockarg
thru_blockarg = false
parse("proc do |&b| end", :on_blockarg) {thru_blockarg = true}
assert_equal true, thru_blockarg
thru_blockarg = false
parse("proc do |&b, x| end", :on_blockarg) {thru_blockarg = true}
assert_equal true, thru_blockarg
thru_blockarg = false
parse("proc do |&b;y| end", :on_blockarg) {thru_blockarg = true}
assert_equal true, thru_blockarg
thru_blockarg = false
parse("proc do |&b, x;y| end", :on_blockarg) {thru_blockarg = true}
assert_equal true, thru_blockarg
end
def test_block_var
thru_block_var = false
parse("proc{||}", :on_block_var) {thru_block_var = true}
assert_equal true, thru_block_var
thru_block_var = false
parse("proc{| |}", :on_block_var) {thru_block_var = true}
assert_equal true, thru_block_var
thru_block_var = false
parse("proc{|x|}", :on_block_var) {thru_block_var = true}
assert_equal true, thru_block_var
thru_block_var = false
parse("proc{|;y|}", :on_block_var) {thru_block_var = true}
assert_equal true, thru_block_var
thru_block_var = false
parse("proc{|x;y|}", :on_block_var) {thru_block_var = true}
assert_equal true, thru_block_var
thru_block_var = false
parse("proc do || end", :on_block_var) {thru_block_var = true}
assert_equal true, thru_block_var
thru_block_var = false
parse("proc do | | end", :on_block_var) {thru_block_var = true}
assert_equal true, thru_block_var
thru_block_var = false
parse("proc do |x| end", :on_block_var) {thru_block_var = true}
assert_equal true, thru_block_var
thru_block_var = false
parse("proc do |;y| end", :on_block_var) {thru_block_var = true}
assert_equal true, thru_block_var
thru_block_var = false
parse("proc do |x;y| end", :on_block_var) {thru_block_var = true}
assert_equal true, thru_block_var
end
def test_block_var_add_block
# not used
end
def test_block_var_add_star
# not used
end
def test_bodystmt
thru_bodystmt = false
parse("class X\nend", :on_bodystmt) {thru_bodystmt = true}
assert_equal true, thru_bodystmt
end
def test_call
bug2233 = '[ruby-core:26165]'
tree = nil
thru_call = false
assert_nothing_raised {
tree = parse("self.foo", :on_call) {thru_call = true}
}
assert_equal true, thru_call
assert_equal "[call(ref(self),.,foo)]", tree
thru_call = false
assert_nothing_raised {
tree = parse("self.foo()", :on_call) {thru_call = true}
}
assert_equal true, thru_call
assert_equal "[call(ref(self),.,foo,[])]", tree
thru_call = false
assert_nothing_raised(bug2233) {
tree = parse("foo.()", :on_call) {thru_call = true}
}
assert_equal true, thru_call
assert_equal "[call(vcall(foo),.,call,[])]", tree
thru_call = false
assert_nothing_raised {
tree = parse("self::foo", :on_call) {thru_call = true}
}
assert_equal true, thru_call
assert_equal "[call(ref(self),::,foo)]", tree
thru_call = false
assert_nothing_raised {
tree = parse("self::foo()", :on_call) {thru_call = true}
}
assert_equal true, thru_call
assert_equal "[call(ref(self),::,foo,[])]", tree
thru_call = false
assert_nothing_raised(bug2233) {
tree = parse("foo::()", :on_call) {thru_call = true}
}
assert_equal true, thru_call
assert_equal "[call(vcall(foo),::,call,[])]", tree
thru_call = false
tree = parse("self&.foo", :on_call) {thru_call = true}
assert_equal true, thru_call
assert_equal "[call(ref(self),&.,foo)]", tree
thru_call = false
tree = parse("self&.foo()", :on_call) {thru_call = true}
assert_equal true, thru_call
assert_equal "[call(ref(self),&.,foo,[])]", tree
end
def test_excessed_comma
thru_excessed_comma = false
parse("proc{|x,|}", :on_excessed_comma) {thru_excessed_comma = true}
assert_equal true, thru_excessed_comma
thru_excessed_comma = false
parse("proc{|x,y,|}", :on_excessed_comma) {thru_excessed_comma = true}
assert_equal true, thru_excessed_comma
thru_excessed_comma = false
parse("proc do |x,| end", :on_excessed_comma) {thru_excessed_comma = true}
assert_equal true, thru_excessed_comma
thru_excessed_comma = false
parse("proc do |x,y,| end", :on_excessed_comma) {thru_excessed_comma = true}
assert_equal true, thru_excessed_comma
end
def test_heredoc
bug1921 = '[ruby-core:24855]'
thru_heredoc_beg = false
tree = parse("<""<EOS\nheredoc\nEOS\n", :on_heredoc_beg) {thru_heredoc_beg = true}
assert_equal true, thru_heredoc_beg
assert_match(/string_content\(\),heredoc\n/, tree, bug1921)
heredoc = nil
parse("<""<EOS\nheredoc1\nheredoc2\nEOS\n", :on_string_add) {|e, n, s| heredoc = s}
assert_equal("heredoc1\nheredoc2\n", heredoc, bug1921)
heredoc = nil
parse("<""<-EOS\nheredoc1\nheredoc2\n\tEOS\n", :on_string_add) {|e, n, s| heredoc = s}
assert_equal("heredoc1\nheredoc2\n", heredoc, bug1921)
end
def test_heredoc_dedent
thru_heredoc_dedent = false
str = width = nil
tree = parse("<""<~EOS\n heredoc\nEOS\n", :on_heredoc_dedent) {|e, s, w|
thru_heredoc_dedent = true
str = s
width = w
}
assert_equal true, thru_heredoc_dedent
assert_match(/string_content\(\), heredoc\n/, tree)
assert_equal(1, width)
end
def test_massign
thru_massign = false
parse("a, b = 1, 2", :on_massign) {thru_massign = true}
assert_equal true, thru_massign
end
def test_mlhs_add
thru_mlhs_add = false
parse("a, b = 1, 2", :on_mlhs_add) {thru_mlhs_add = true}
assert_equal true, thru_mlhs_add
end
def test_mlhs_add_star
bug2232 = '[ruby-core:26163]'
bug4364 = '[ruby-core:35078]'
thru_mlhs_add_star = false
tree = parse("a, *b = 1, 2", :on_mlhs_add_star) {thru_mlhs_add_star = true}
assert_equal true, thru_mlhs_add_star
assert_match(/mlhs_add_star\(mlhs_add\(mlhs_new\(\),a\),b\)/, tree)
thru_mlhs_add_star = false
tree = parse("a, *b, c = 1, 2", :on_mlhs_add_star) {thru_mlhs_add_star = true}
assert_equal true, thru_mlhs_add_star
assert_match(/mlhs_add\(mlhs_add_star\(mlhs_add\(mlhs_new\(\),a\),b\),mlhs_add\(mlhs_new\(\),c\)\)/, tree, bug2232)
thru_mlhs_add_star = false
tree = parse("a, *, c = 1, 2", :on_mlhs_add_star) {thru_mlhs_add_star = true}
assert_equal true, thru_mlhs_add_star
assert_match(/mlhs_add\(mlhs_add_star\(mlhs_add\(mlhs_new\(\),a\)\),mlhs_add\(mlhs_new\(\),c\)\)/, tree, bug4364)
thru_mlhs_add_star = false
tree = parse("*b, c = 1, 2", :on_mlhs_add_star) {thru_mlhs_add_star = true}
assert_equal true, thru_mlhs_add_star
assert_match(/mlhs_add\(mlhs_add_star\(mlhs_new\(\),b\),mlhs_add\(mlhs_new\(\),c\)\)/, tree, bug4364)
thru_mlhs_add_star = false
tree = parse("*, c = 1, 2", :on_mlhs_add_star) {thru_mlhs_add_star = true}
assert_equal true, thru_mlhs_add_star
assert_match(/mlhs_add\(mlhs_add_star\(mlhs_new\(\)\),mlhs_add\(mlhs_new\(\),c\)\)/, tree, bug4364)
end
def test_mlhs_new
thru_mlhs_new = false
parse("a, b = 1, 2", :on_mlhs_new) {thru_mlhs_new = true}
assert_equal true, thru_mlhs_new
end
def test_mlhs_paren
thru_mlhs_paren = false
parse("a, b = 1, 2", :on_mlhs_paren) {thru_mlhs_paren = true}
assert_equal false, thru_mlhs_paren
thru_mlhs_paren = false
parse("(a, b) = 1, 2", :on_mlhs_paren) {thru_mlhs_paren = true}
assert_equal true, thru_mlhs_paren
end
def test_brace_block
thru_brace_block = false
parse('proc {}', :on_brace_block) {thru_brace_block = true}
assert_equal true, thru_brace_block
end
def test_break
thru_break = false
parse('proc {break}', :on_break) {thru_break = true}
assert_equal true, thru_break
end
def test_case
thru_case = false
parse('case foo when true; end', :on_case) {thru_case = true}
assert_equal true, thru_case
end
def test_class
thru_class = false
parse('class Foo; end', :on_class) {thru_class = true}
assert_equal true, thru_class
end
def test_class_name_error
thru_class_name_error = false
parse('class foo; end', :on_class_name_error) {thru_class_name_error = true}
assert_equal true, thru_class_name_error
end
def test_command
thru_command = false
parse('foo a b', :on_command) {thru_command = true}
assert_equal true, thru_command
end
def test_command_call
thru_command_call = false
parse('foo.bar a, b', :on_command_call) {thru_command_call = true}
assert_equal true, thru_command_call
end
def test_const_ref
thru_const_ref = false
parse('class A;end', :on_const_ref) {thru_const_ref = true}
assert_equal true, thru_const_ref
thru_const_ref = false
parse('module A;end', :on_const_ref) {thru_const_ref = true}
assert_equal true, thru_const_ref
end
def test_const_path_field
thru_const_path_field = false
parse('foo::X = 1', :on_const_path_field) {thru_const_path_field = true}
assert_equal true, thru_const_path_field
end
def test_const_path_ref
thru_const_path_ref = false
parse('foo::X', :on_const_path_ref) {thru_const_path_ref = true}
assert_equal true, thru_const_path_ref
end
def test_def
thru_def = false
parse('def foo; end', :on_def) {
thru_def = true
}
assert_equal true, thru_def
assert_equal '[def(foo,[],bodystmt([void()]))]', parse('def foo ;end')
end
def test_defined
thru_defined = false
parse('defined?(x)', :on_defined) {thru_defined = true}
assert_equal true, thru_defined
end
def test_defs
thru_defs = false
tree = parse('def foo.bar; end', :on_defs) {thru_defs = true}
assert_equal true, thru_defs
assert_equal("[defs(vcall(foo),.,bar,[],bodystmt([void()]))]", tree)
thru_parse_error = false
tree = parse('def foo&.bar; end', :on_parse_error) {thru_parse_error = true}
assert_equal(true, thru_parse_error)
end
def test_do_block
thru_do_block = false
parse('proc do end', :on_do_block) {thru_do_block = true}
assert_equal true, thru_do_block
end
def test_dot2
thru_dot2 = false
parse('a..b', :on_dot2) {thru_dot2 = true}
assert_equal true, thru_dot2
end
def test_dot3
thru_dot3 = false
parse('a...b', :on_dot3) {thru_dot3 = true}
assert_equal true, thru_dot3
end
def test_dyna_symbol
thru_dyna_symbol = false
parse(':"#{foo}"', :on_dyna_symbol) {thru_dyna_symbol = true}
assert_equal true, thru_dyna_symbol
thru_dyna_symbol = false
parse('{"#{foo}": 1}', :on_dyna_symbol) {thru_dyna_symbol = true}
assert_equal true, thru_dyna_symbol
end
def test_else
thru_else = false
parse('if foo; bar else zot end', :on_else) {thru_else = true}
assert_equal true, thru_else
end
def test_elsif
thru_elsif = false
parse('if foo; bar elsif qux; zot end', :on_elsif) {thru_elsif = true}
assert_equal true, thru_elsif
end
def test_ensure
thru_ensure = false
parse('begin foo ensure bar end', :on_ensure) {thru_ensure = true}
assert_equal true, thru_ensure
end
def test_fcall
thru_fcall = false
parse('foo()', :on_fcall) {thru_fcall = true}
assert_equal true, thru_fcall
end
def test_field
thru_field = false
parse('foo.x = 1', :on_field) {thru_field = true}
assert_equal true, thru_field
end
def test_for
thru_for = false
parse('for i in foo; end', :on_for) {thru_for = true}
assert_equal true, thru_for
end
def test_hash
thru_hash = false
parse('{1=>2}', :on_hash) {thru_hash = true}
assert_equal true, thru_hash
thru_hash = false
parse('{a: 2}', :on_hash) {thru_hash = true}
assert_equal true, thru_hash
end
def test_if
thru_if = false
parse('if false; end', :on_if) {thru_if = true}
assert_equal true, thru_if
end
def test_if_mod
thru_if_mod = false
parse('nil if nil', :on_if_mod) {thru_if_mod = true}
assert_equal true, thru_if_mod
end
def test_ifop
thru_ifop = false
parse('a ? b : c', :on_ifop) {thru_ifop = true}
assert_equal true, thru_ifop
end
def test_lambda
thru_lambda = false
parse('->{}', :on_lambda) {thru_lambda = true}
assert_equal true, thru_lambda
end
def test_magic_comment
thru_magic_comment = false
parse('# -*- bug-5753: ruby-dev:44984 -*-', :on_magic_comment) {|*x|thru_magic_comment = x}
assert_equal [:on_magic_comment, "bug_5753", "ruby-dev:44984"], thru_magic_comment
end
def test_method_add_block
thru_method_add_block = false
parse('a {}', :on_method_add_block) {thru_method_add_block = true}
assert_equal true, thru_method_add_block
thru_method_add_block = false
parse('a do end', :on_method_add_block) {thru_method_add_block = true}
assert_equal true, thru_method_add_block
end
def test_method_add_arg
thru_method_add_arg = false
parse('a()', :on_method_add_arg) {thru_method_add_arg = true}
assert_equal true, thru_method_add_arg
thru_method_add_arg = false
parse('a {}', :on_method_add_arg) {thru_method_add_arg = true}
assert_equal true, thru_method_add_arg
thru_method_add_arg = false
parse('a.b(1)', :on_method_add_arg) {thru_method_add_arg = true}
assert_equal true, thru_method_add_arg
thru_method_add_arg = false
parse('a::b(1)', :on_method_add_arg) {thru_method_add_arg = true}
assert_equal true, thru_method_add_arg
end
def test_module
thru_module = false
parse('module A; end', :on_module) {thru_module = true}
assert_equal true, thru_module
end
def test_mrhs_add
thru_mrhs_add = false
parse('a = a, b', :on_mrhs_add) {thru_mrhs_add = true}
assert_equal true, thru_mrhs_add
end
def test_mrhs_add_star
thru_mrhs_add_star = false
parse('a = a, *b', :on_mrhs_add_star) {thru_mrhs_add_star = true}
assert_equal true, thru_mrhs_add_star
end
def test_mrhs_new
thru_mrhs_new = false
parse('a = *a', :on_mrhs_new) {thru_mrhs_new = true}
assert_equal true, thru_mrhs_new
end
def test_mrhs_new_from_args
thru_mrhs_new_from_args = false
parse('a = a, b', :on_mrhs_new_from_args) {thru_mrhs_new_from_args = true}
assert_equal true, thru_mrhs_new_from_args
end
def test_next
thru_next = false
parse('a {next}', :on_next) {thru_next = true}
assert_equal true, thru_next
end
def test_opassign
thru_opassign = false
tree = parse('a += b', :on_opassign) {thru_opassign = true}
assert_equal true, thru_opassign
assert_equal "[opassign(var_field(a),+=,vcall(b))]", tree
thru_opassign = false
tree = parse('a -= b', :on_opassign) {thru_opassign = true}
assert_equal true, thru_opassign
assert_equal "[opassign(var_field(a),-=,vcall(b))]", tree
thru_opassign = false
tree = parse('a *= b', :on_opassign) {thru_opassign = true}
assert_equal true, thru_opassign
assert_equal "[opassign(var_field(a),*=,vcall(b))]", tree
thru_opassign = false
tree = parse('a /= b', :on_opassign) {thru_opassign = true}
assert_equal true, thru_opassign
assert_equal "[opassign(var_field(a),/=,vcall(b))]", tree
thru_opassign = false
tree = parse('a %= b', :on_opassign) {thru_opassign = true}
assert_equal true, thru_opassign
assert_equal "[opassign(var_field(a),%=,vcall(b))]", tree
thru_opassign = false
tree = parse('a **= b', :on_opassign) {thru_opassign = true}
assert_equal true, thru_opassign
assert_equal "[opassign(var_field(a),**=,vcall(b))]", tree
thru_opassign = false
tree = parse('a &= b', :on_opassign) {thru_opassign = true}
assert_equal true, thru_opassign
assert_equal "[opassign(var_field(a),&=,vcall(b))]", tree
thru_opassign = false
tree = parse('a |= b', :on_opassign) {thru_opassign = true}
assert_equal "[opassign(var_field(a),|=,vcall(b))]", tree
assert_equal true, thru_opassign
thru_opassign = false
tree = parse('a <<= b', :on_opassign) {thru_opassign = true}
assert_equal true, thru_opassign
assert_equal "[opassign(var_field(a),<<=,vcall(b))]", tree
thru_opassign = false
tree = parse('a >>= b', :on_opassign) {thru_opassign = true}
assert_equal true, thru_opassign
assert_equal "[opassign(var_field(a),>>=,vcall(b))]", tree
thru_opassign = false
tree = parse('a &&= b', :on_opassign) {thru_opassign = true}
assert_equal true, thru_opassign
assert_equal "[opassign(var_field(a),&&=,vcall(b))]", tree
thru_opassign = false
tree = parse('a ||= b', :on_opassign) {thru_opassign = true}
assert_equal true, thru_opassign
assert_equal "[opassign(var_field(a),||=,vcall(b))]", tree
thru_opassign = false
tree = parse('a::X ||= c 1', :on_opassign) {thru_opassign = true}
assert_equal true, thru_opassign
assert_equal "[opassign(const_path_field(vcall(a),X),||=,command(c,[1]))]", tree
thru_opassign = false
tree = parse("self.foo += 1", :on_opassign) {thru_opassign = true}
assert_equal true, thru_opassign
assert_equal "[opassign(field(ref(self),.,foo),+=,1)]", tree
thru_opassign = false
tree = parse("self&.foo += 1", :on_opassign) {thru_opassign = true}
assert_equal true, thru_opassign
assert_equal "[opassign(field(ref(self),&.,foo),+=,1)]", tree
end
def test_opassign_error
thru_opassign = []
events = [:on_opassign]
parse('$~ ||= 1', events) {|a,*b|
thru_opassign << a
}
assert_equal events, thru_opassign
end
def test_param_error
thru_param_error = false
parse('def foo(A) end', :on_param_error) {thru_param_error = true}
assert_equal true, thru_param_error
thru_param_error = false
parse('def foo($a) end', :on_param_error) {thru_param_error = true}
assert_equal true, thru_param_error
thru_param_error = false
parse('def foo(@a) end', :on_param_error) {thru_param_error = true}
assert_equal true, thru_param_error
thru_param_error = false
parse('def foo(@@a) end', :on_param_error) {thru_param_error = true}
assert_equal true, thru_param_error
end
def test_params
arg = nil
thru_params = false
parse('a {||}', :on_params) {|_, *v| thru_params = true; arg = v}
assert_equal true, thru_params
assert_equal [nil, nil, nil, nil, nil, nil, nil], arg
thru_params = false
parse('a {|x|}', :on_params) {|_, *v| thru_params = true; arg = v}
assert_equal true, thru_params
assert_equal [["x"], nil, nil, nil, nil, nil, nil], arg
thru_params = false
parse('a {|*x|}', :on_params) {|_, *v| thru_params = true; arg = v}
assert_equal true, thru_params
assert_equal [nil, nil, "*x", nil, nil, nil, nil], arg
thru_params = false
parse('a {|x: 1|}', :on_params) {|_, *v| thru_params = true; arg = v}
assert_equal true, thru_params
assert_equal [nil, nil, nil, nil, [["x:", "1"]], nil, nil], arg
thru_params = false
parse('a {|x:|}', :on_params) {|_, *v| thru_params = true; arg = v}
assert_equal true, thru_params
assert_equal [nil, nil, nil, nil, [["x:", false]], nil, nil], arg
thru_params = false
parse('a {|**x|}', :on_params) {|_, *v| thru_params = true; arg = v}
assert_equal true, thru_params
assert_equal [nil, nil, nil, nil, nil, "x", nil], arg
end
def test_paren
thru_paren = false
parse('()', :on_paren) {thru_paren = true}
assert_equal true, thru_paren
end
def test_parse_error
thru_parse_error = false
parse('<>', :on_parse_error) {thru_parse_error = true}
assert_equal true, thru_parse_error
end
def test_qwords_add
thru_qwords_add = false
parse('%w[a]', :on_qwords_add) {thru_qwords_add = true}
assert_equal true, thru_qwords_add
end
def test_qsymbols_add
thru_qsymbols_add = false
parse('%i[a]', :on_qsymbols_add) {thru_qsymbols_add = true}
assert_equal true, thru_qsymbols_add
end
def test_symbols_add
thru_symbols_add = false
parse('%I[a]', :on_symbols_add) {thru_symbols_add = true}
assert_equal true, thru_symbols_add
end
def test_qwords_new
thru_qwords_new = false
parse('%w[]', :on_qwords_new) {thru_qwords_new = true}
assert_equal true, thru_qwords_new
end
def test_qsymbols_new
thru_qsymbols_new = false
parse('%i[]', :on_qsymbols_new) {thru_qsymbols_new = true}
assert_equal true, thru_qsymbols_new
end
def test_symbols_new
thru_symbols_new = false
parse('%I[]', :on_symbols_new) {thru_symbols_new = true}
assert_equal true, thru_symbols_new
end
def test_redo
thru_redo = false
parse('redo', :on_redo) {thru_redo = true}
assert_equal true, thru_redo
end
def test_regexp_add
thru_regexp_add = false
parse('/foo/', :on_regexp_add) {thru_regexp_add = true}
assert_equal true, thru_regexp_add
end
def test_regexp_literal
thru_regexp_literal = false
parse('//', :on_regexp_literal) {thru_regexp_literal = true}
assert_equal true, thru_regexp_literal
end
def test_regexp_new
thru_regexp_new = false
parse('//', :on_regexp_new) {thru_regexp_new = true}
assert_equal true, thru_regexp_new
end
def test_rescue
thru_rescue = false
parsed = parse('begin; 1; rescue => e; 2; end', :on_rescue) {thru_rescue = true}
assert_equal true, thru_rescue
assert_match(/1.*rescue/, parsed)
assert_match(/rescue\(,var_field\(e\),\[2\]\)/, parsed)
end
def test_rescue_class
thru_rescue = false
parsed = parse('begin; 1; rescue RuntimeError => e; 2; end', :on_rescue) {thru_rescue = true}
assert_equal true, thru_rescue
assert_match(/1.*rescue/, parsed)
assert_match(/rescue\(\[ref\(RuntimeError\)\],var_field\(e\),\[2\]\)/, parsed)
end
def test_rescue_mod
thru_rescue_mod = false
parsed = parse('1 rescue 2', :on_rescue_mod) {thru_rescue_mod = true}
assert_equal true, thru_rescue_mod
bug4716 = '[ruby-core:36248]'
assert_equal "[rescue_mod(1,2)]", parsed, bug4716
end
def test_rest_param
thru_rest_param = false
parse('def a(*) end', :on_rest_param) {thru_rest_param = true}
assert_equal true, thru_rest_param
thru_rest_param = false
parse('def a(*x) end', :on_rest_param) {thru_rest_param = true}
assert_equal true, thru_rest_param
end
def test_retry
thru_retry = false
parse('retry', :on_retry) {thru_retry = true}
assert_equal true, thru_retry
end
def test_return
thru_return = false
parse('return a', :on_return) {thru_return = true}
assert_equal true, thru_return
end
def test_return0
thru_return0 = false
parse('return', :on_return0) {thru_return0 = true}
assert_equal true, thru_return0
end
def test_sclass
thru_sclass = false
parse('class << a; end', :on_sclass) {thru_sclass = true}
assert_equal true, thru_sclass
end
def test_string_add
thru_string_add = false
parse('"aa"', :on_string_add) {thru_string_add = true}
assert_equal true, thru_string_add
end
def test_string_concat
thru_string_concat = false
parse('"a" "b"', :on_string_concat) {thru_string_concat = true}
assert_equal true, thru_string_concat
end
def test_string_content
thru_string_content = false
parse('""', :on_string_content) {thru_string_content = true}
assert_equal true, thru_string_content
thru_string_content = false
parse('"a"', :on_string_content) {thru_string_content = true}
assert_equal true, thru_string_content
thru_string_content = false
parse('%[a]', :on_string_content) {thru_string_content = true}
assert_equal true, thru_string_content
thru_string_content = false
parse('\'a\'', :on_string_content) {thru_string_content = true}
assert_equal true, thru_string_content
thru_string_content = false
parse('%<a>', :on_string_content) {thru_string_content = true}
assert_equal true, thru_string_content
thru_string_content = false
parse('%!a!', :on_string_content) {thru_string_content = true}
assert_equal true, thru_string_content
thru_string_content = false
parse('%q!a!', :on_string_content) {thru_string_content = true}
assert_equal true, thru_string_content
thru_string_content = false
parse('%Q!a!', :on_string_content) {thru_string_content = true}
assert_equal true, thru_string_content
end
def test_string_dvar
thru_string_dvar = false
parse('"#$a"', :on_string_dvar) {thru_string_dvar = true}
assert_equal true, thru_string_dvar
thru_string_dvar = false
parse('\'#$a\'', :on_string_dvar) {thru_string_dvar = true}
assert_equal false, thru_string_dvar
thru_string_dvar = false
parse('"#@a"', :on_string_dvar) {thru_string_dvar = true}
assert_equal true, thru_string_dvar
thru_string_dvar = false
parse('\'#@a\'', :on_string_dvar) {thru_string_dvar = true}
assert_equal false, thru_string_dvar
thru_string_dvar = false
parse('"#@@a"', :on_string_dvar) {thru_string_dvar = true}
assert_equal true, thru_string_dvar
thru_string_dvar = false
parse('\'#@@a\'', :on_string_dvar) {thru_string_dvar = true}
assert_equal false, thru_string_dvar
thru_string_dvar = false
parse('"#$1"', :on_string_dvar) {thru_string_dvar = true}
assert_equal true, thru_string_dvar
thru_string_dvar = false
parse('\'#$1\'', :on_string_dvar) {thru_string_dvar = true}
assert_equal false, thru_string_dvar
end
def test_string_embexpr
thru_string_embexpr = false
parse('"#{}"', :on_string_embexpr) {thru_string_embexpr = true}
assert_equal true, thru_string_embexpr
thru_string_embexpr = false
parse('\'#{}\'', :on_string_embexpr) {thru_string_embexpr = true}
assert_equal false, thru_string_embexpr
end
def test_string_literal
thru_string_literal = false
parse('""', :on_string_literal) {thru_string_literal = true}
assert_equal true, thru_string_literal
end
def test_super
thru_super = false
parse('super()', :on_super) {thru_super = true}
assert_equal true, thru_super
end
def test_symbol
thru_symbol = false
parse(':a', :on_symbol) {thru_symbol = true}
assert_equal true, thru_symbol
thru_symbol = false
parse(':$a', :on_symbol) {thru_symbol = true}
assert_equal true, thru_symbol
thru_symbol = false
parse(':@a', :on_symbol) {thru_symbol = true}
assert_equal true, thru_symbol
thru_symbol = false
parse(':@@a', :on_symbol) {thru_symbol = true}
assert_equal true, thru_symbol
thru_symbol = false
parse(':==', :on_symbol) {thru_symbol = true}
assert_equal true, thru_symbol
end
def test_symbol_literal
thru_symbol_literal = false
parse(':a', :on_symbol_literal) {thru_symbol_literal = true}
assert_equal true, thru_symbol_literal
end
def test_top_const_field
thru_top_const_field = false
parse('::A=1', :on_top_const_field) {thru_top_const_field = true}
assert_equal true, thru_top_const_field
end
def test_top_const_ref
thru_top_const_ref = false
parse('::A', :on_top_const_ref) {thru_top_const_ref = true}
assert_equal true, thru_top_const_ref
end
def test_unary
thru_unary = false
parse('not a 1, 2', :on_unary) {thru_unary = true}
assert_equal true, thru_unary
thru_unary = false
parse('not (a)', :on_unary) {thru_unary = true}
assert_equal true, thru_unary
thru_unary = false
parse('!a', :on_unary) {thru_unary = true}
assert_equal true, thru_unary
thru_unary = false
parse('-10', :on_unary) {thru_unary = true}
assert_equal true, thru_unary
thru_unary = false
parse('-10*2', :on_unary) {thru_unary = true}
assert_equal true, thru_unary
thru_unary = false
parse('-10.1', :on_unary) {thru_unary = true}
assert_equal true, thru_unary
thru_unary = false
parse('-10.1*2', :on_unary) {thru_unary = true}
assert_equal true, thru_unary
thru_unary = false
parse('-a', :on_unary) {thru_unary = true}
assert_equal true, thru_unary
thru_unary = false
parse('+a', :on_unary) {thru_unary = true}
assert_equal true, thru_unary
thru_unary = false
parse('~a', :on_unary) {thru_unary = true}
assert_equal true, thru_unary
thru_unary = false
parse('not()', :on_unary) {thru_unary = true}
assert_equal true, thru_unary
end
def test_undef
thru_undef = false
parse('undef a', :on_undef) {thru_undef = true}
assert_equal true, thru_undef
thru_undef = false
parse('undef <=>', :on_undef) {thru_undef = true}
assert_equal true, thru_undef
thru_undef = false
parse('undef a, b', :on_undef) {thru_undef = true}
assert_equal true, thru_undef
end
def test_unless
thru_unless = false
parse('unless a; end', :on_unless) {thru_unless = true}
assert_equal true, thru_unless
end
def test_unless_mod
thru_unless_mod = false
parse('nil unless a', :on_unless_mod) {thru_unless_mod = true}
assert_equal true, thru_unless_mod
end
def test_until
thru_until = false
parse('until a; end', :on_until) {thru_until = true}
assert_equal true, thru_until
end
def test_until_mod
thru_until_mod = false
parse('nil until a', :on_until_mod) {thru_until_mod = true}
assert_equal true, thru_until_mod
end
def test_var_field
thru_var_field = false
parse('a = 1', :on_var_field) {thru_var_field = true}
assert_equal true, thru_var_field
thru_var_field = false
parse('a += 1', :on_var_field) {thru_var_field = true}
assert_equal true, thru_var_field
end
def test_when
thru_when = false
parse('case a when b; end', :on_when) {thru_when = true}
assert_equal true, thru_when
thru_when = false
parse('case when a; end', :on_when) {thru_when = true}
assert_equal true, thru_when
end
def test_while
thru_while = false
parse('while a; end', :on_while) {thru_while = true}
assert_equal true, thru_while
end
def test_while_mod
thru_while_mod = false
parse('nil while a', :on_while_mod) {thru_while_mod = true}
assert_equal true, thru_while_mod
end
def test_word_add
thru_word_add = false
parse('%W[a]', :on_word_add) {thru_word_add = true}
assert_equal true, thru_word_add
end
def test_word_new
thru_word_new = false
parse('%W[a]', :on_word_new) {thru_word_new = true}
assert_equal true, thru_word_new
end
def test_words_add
thru_words_add = false
parse('%W[a]', :on_words_add) {thru_words_add = true}
assert_equal true, thru_words_add
end
def test_words_new
thru_words_new = false
parse('%W[]', :on_words_new) {thru_words_new = true}
assert_equal true, thru_words_new
end
def test_xstring_add
thru_xstring_add = false
parse('`x`', :on_xstring_add) {thru_xstring_add = true}
assert_equal true, thru_xstring_add
end
def test_xstring_literal
thru_xstring_literal = false
parse('``', :on_xstring_literal) {thru_xstring_literal = true}
assert_equal true, thru_xstring_literal
end
def test_xstring_new
thru_xstring_new = false
parse('``', :on_xstring_new) {thru_xstring_new = true}
assert_equal true, thru_xstring_new
end
def test_yield
thru_yield = false
parse('yield a', :on_yield) {thru_yield = true}
assert_equal true, thru_yield
end
def test_yield0
thru_yield0 = false
parse('yield', :on_yield0) {thru_yield0 = true}
assert_equal true, thru_yield0
end
def test_zsuper
thru_zsuper = false
parse('super', :on_zsuper) {thru_zsuper = true}
assert_equal true, thru_zsuper
end
def test_local_variables
cmd = 'command(w,[regexp_literal(regexp_add(regexp_new(),25 # ),/)])'
div = 'binary(ref(w),/,25)'
bug1939 = '[ruby-core:24923]'
assert_equal("[#{cmd}]", parse('w /25 # /'), bug1939)
assert_equal("[assign(var_field(w),1),#{div}]", parse("w = 1; w /25 # /"), bug1939)
assert_equal("[fcall(p,[],&block([w],[#{div}]))]", parse("p{|w|w /25 # /\n}"), bug1939)
assert_equal("[def(p,[w],bodystmt([#{div}]))]", parse("def p(w)\nw /25 # /\nend"), bug1939)
end
def test_block_variables
assert_equal("[fcall(proc,[],&block([],[void()]))]", parse("proc{|;y|}"))
if defined?(Process::RLIMIT_AS)
assert_in_out_err(["-I#{File.dirname(__FILE__)}", "-rdummyparser"],
'Process.setrlimit(Process::RLIMIT_AS,100*1024*1024); puts DummyParser.new("proc{|;y|!y}").parse',
["[fcall(proc,[],&block([],[unary(!,ref(y))]))]"], [], '[ruby-dev:39423]')
end
end
def test_unterminated_regexp
assert_equal("unterminated regexp meets end of file", compile_error('/'))
end
def test_invalid_instance_variable_name
assert_equal("`@1' is not allowed as an instance variable name", compile_error('@1'))
assert_equal("`@%' is not allowed as an instance variable name", compile_error('@%'))
assert_equal("`@' without identifiers is not allowed as an instance variable name", compile_error('@'))
end
def test_invalid_class_variable_name
assert_equal("`@@1' is not allowed as a class variable name", compile_error('@@1'))
assert_equal("`@@%' is not allowed as a class variable name", compile_error('@@%'))
assert_equal("`@@' without identifiers is not allowed as a class variable name", compile_error('@@'))
end
def test_invalid_global_variable_name
assert_equal("`$%' is not allowed as a global variable name", compile_error('$%'))
assert_equal("`$' without identifiers is not allowed as a global variable name", compile_error('$'))
end
def test_warning_shadowing
fmt, *args = warning("x = 1; tap {|;x|}")
assert_match(/shadowing outer local variable/, fmt)
assert_equal("x", args[0])
assert_match(/x/, fmt % args)
end
def test_warning_ignored_magic_comment
fmt, *args = warning("1; #-*- frozen-string-literal: true -*-")
assert_match(/ignored after any tokens/, fmt)
assert_equal("frozen_string_literal", args[0])
end
def test_warn_cr_in_middle
fmt = nil
assert_warn("") {fmt, = warn("\r;")}
assert_match(/encountered/, fmt)
end
end if ripper_test
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tk/after.rb
|
<reponame>arnab0073/idea
#
# tk/after.rb : methods for Tcl/Tk after command
#
# $Id: after.rb 25189 2009-10-02 12:04:37Z akr $
#
require 'tk/timer'
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/bigdecimal/extconf.rb
|
<filename>.rvm/src/ruby-2.3.0/ext/bigdecimal/extconf.rb
# frozen_string_literal: false
require 'mkmf'
have_func("labs", "stdlib.h")
have_func("llabs", "stdlib.h")
have_type("struct RRational", "ruby.h")
have_func("rb_rational_num", "ruby.h")
have_func("rb_rational_den", "ruby.h")
create_makefile('bigdecimal')
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/iwidgets/sample/timeentry.rb
|
<reponame>arnab0073/idea<gh_stars>10-100
#!/usr/bin/env ruby
require 'tk'
require 'tkextlib/iwidgets'
Tk::Iwidgets::Timeentry.new.pack
Tk.mainloop
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/bwidget/panedwindow.rb
|
#
# tkextlib/bwidget/panedwindow.rb
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tk/frame'
require 'tkextlib/bwidget.rb'
module Tk
module BWidget
class PanedWindow < TkWindow
end
end
end
class Tk::BWidget::PanedWindow
TkCommandNames = ['PanedWindow'.freeze].freeze
WidgetClassName = 'PanedWindow'.freeze
WidgetClassNames[WidgetClassName] ||= self
def __strval_optkeys
super() << 'activator'
end
private :__strval_optkeys
def add(keys={})
window(tk_send('add', *hash_kv(keys)))
end
def get_frame(idx, &b)
win = window(tk_send_without_enc('getframe', idx))
if b
if TkCore::WITH_RUBY_VM ### Ruby 1.9 !!!!
win.instance_exec(self, &b)
else
win.instance_eval(&b)
end
end
win
end
end
|
arnab0073/idea
|
.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/executable-hooks-1.3.2/lib/executable-hooks/hooks.rb
|
<reponame>arnab0073/idea<gh_stars>10-100
module Gem
@executables_hooks ||= []
class << self
unless method_defined?(:execute)
def execute(&hook)
@executables_hooks << hook
end
attr_reader :executables_hooks
end
unless method_defined?(:load_executable_plugins)
def load_executable_plugins
if ENV['RUBYGEMS_LOAD_ALL_PLUGINS']
load_plugin_files find_files('rubygems_executable_plugin', false)
else
begin
load_plugin_files find_latest_files('rubygems_executable_plugin', false)
rescue NoMethodError
load_plugin_files find_files('rubygems_executable_plugin', false)
end
end
rescue ArgumentError, NoMethodError
# old rubygems
plugins = find_files('rubygems_executable_plugin')
plugins.each do |plugin|
# Skip older versions of the GemCutter plugin: Its commands are in
# RubyGems proper now.
next if plugin =~ /gemcutter-0\.[0-3]/
begin
load plugin
rescue ::Exception => e
details = "#{plugin.inspect}: #{e.message} (#{e.class})"
warn "Error loading RubyGems plugin #{details}"
end
end
end
end
end
class ExecutableHooks
def self.run(original_file)
Gem.load_executable_plugins
Gem.executables_hooks.each do |hook|
hook.call(original_file)
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/iwidgets/scrolledlistbox.rb
|
<reponame>arnab0073/idea<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/iwidgets/scrolledlistbox.rb
#
# tkextlib/iwidgets/scrolledlistbox.rb
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tk/listbox'
require 'tkextlib/iwidgets.rb'
module Tk
module Iwidgets
class Scrolledlistbox < Tk::Iwidgets::Scrolledwidget
end
end
end
class Tk::Iwidgets::Scrolledlistbox
TkCommandNames = ['::iwidgets::scrolledlistbox'.freeze].freeze
WidgetClassName = 'Scrolledlistbox'.freeze
WidgetClassNames[WidgetClassName] ||= self
def __strval_optkeys
super() << 'textbackground'
end
private :__strval_optkeys
def __tkvariable_optkeys
super() << 'listvariable'
end
private :__tkvariable_optkeys
def __font_optkeys
super() << 'textfont'
end
private :__font_optkeys
################################
def initialize(*args)
super(*args)
@listbox = component_widget('listbox')
end
def method_missing(id, *args)
if @listbox.respond_to?(id)
@listbox.__send__(id, *args)
else
super(id, *args)
end
end
################################
def clear
tk_call(@path, 'clear')
self
end
def get_curselection
tk_call(@path, 'getcurselection')
end
def justify(dir)
tk_call(@path, 'justify', dir)
self
end
def selected_item_count
number(tk_call(@path, 'selecteditemcount'))
end
def sort(*params, &b)
# see 'lsort' man page about params
if b
tk_call(@path, 'sort', '-command', proc(&b), *params)
else
tk_call(@path, 'sort', *params)
end
self
end
def sort_ascending
tk_call(@path, 'sort', 'ascending')
self
end
def sort_descending
tk_call(@path, 'sort', 'descending')
self
end
#####################################
def bbox(index)
list(tk_send_without_enc('bbox', index))
end
def delete(first, last=None)
tk_send_without_enc('delete', first, last)
self
end
def get(*index)
_fromUTF8(tk_send_without_enc('get', *index))
end
def insert(index, *args)
tk_send('insert', index, *args)
self
end
def scan_mark(x, y)
tk_send_without_enc('scan', 'mark', x, y)
self
end
def scan_dragto(x, y)
tk_send_without_enc('scan', 'dragto', x, y)
self
end
def see(index)
tk_send_without_enc('see', index)
self
end
#####################################
include TkListItemConfig
def tagid(tag)
if tag.kind_of?(Tk::Itk::Component)
tag.name
else
super(tag)
end
end
private :tagid
#####################################
def activate(y)
tk_send_without_enc('activate', y)
self
end
def curselection
list(tk_send_without_enc('curselection'))
end
def get(first, last=nil)
if last
# tk_split_simplelist(_fromUTF8(tk_send_without_enc('get', first, last)))
tk_split_simplelist(tk_send_without_enc('get', first, last),
false, true)
else
_fromUTF8(tk_send_without_enc('get', first))
end
end
def nearest(y)
tk_send_without_enc('nearest', y).to_i
end
def size
tk_send_without_enc('size').to_i
end
def selection_anchor(index)
tk_send_without_enc('selection', 'anchor', index)
self
end
def selection_clear(first, last=None)
tk_send_without_enc('selection', 'clear', first, last)
self
end
def selection_includes(index)
bool(tk_send_without_enc('selection', 'includes', index))
end
def selection_set(first, last=None)
tk_send_without_enc('selection', 'set', first, last)
self
end
def index(idx)
tk_send_without_enc('index', idx).to_i
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
def yview(*index)
if index.size == 0
list(tk_send_without_enc('yview'))
else
tk_send_without_enc('yview', *index)
self
end
end
def yview_moveto(*index)
yview('moveto', *index)
end
def yview_scroll(*index)
yview('scroll', *index)
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/rubygems/plugin/load/rubygems_plugin.rb
|
# frozen_string_literal: false
class TestGem
TEST_PLUGIN_LOAD = :loaded
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/demos-en/sayings.rb
|
<reponame>arnab0073/idea
# sayings.rb
#
# This demonstration script creates a listbox that can be scrolled
# both horizontally and vertically. It displays a collection of
# well-known sayings.
#
# listbox widget demo 'sayings' (called by 'widget')
#
# toplevel widget
if defined?($sayings_demo) && $sayings_demo
$sayings_demo.destroy
$sayings_demo = nil
end
# demo toplevel widget
$sayings_demo = TkToplevel.new {|w|
title("Listbox Demonstration (well-known sayings)")
iconname("sayings")
positionWindow(w)
}
base_frame = TkFrame.new($sayings_demo).pack(:fill=>:both, :expand=>true)
# label
msg = TkLabel.new(base_frame) {
font $font
wraplength '4i'
justify 'left'
text "The listbox below contains a collection of well-known sayings. You can scan the list using either of the scrollbars or by dragging in the listbox window with button 2 pressed."
}
msg.pack('side'=>'top')
# frame
TkFrame.new(base_frame) {|frame|
TkButton.new(frame) {
text 'Dismiss'
command proc{
tmppath = $sayings_demo
$sayings_demo = nil
tmppath.destroy
}
}.pack('side'=>'left', 'expand'=>'yes')
TkButton.new(frame) {
text 'Show Code'
command proc{showCode 'sayings'}
}.pack('side'=>'left', 'expand'=>'yes')
}.pack('side'=>'bottom', 'fill'=>'x', 'pady'=>'2m')
# frame
sayings_lbox = nil
TkFrame.new(base_frame, 'borderwidth'=>10) {|w|
sv = TkScrollbar.new(w)
sh = TkScrollbar.new(w, 'orient'=>'horizontal')
sayings_lbox = TkListbox.new(w) {
setgrid 1
width 20
height 10
yscrollcommand proc{|first,last| sv.set first,last}
xscrollcommand proc{|first,last| sh.set first,last}
}
sv.command(proc{|*args| sayings_lbox.yview(*args)})
sh.command(proc{|*args| sayings_lbox.xview(*args)})
if $tk_version =~ /^4\.[01]/
sv.pack('side'=>'right', 'fill'=>'y')
sh.pack('side'=>'bottom', 'fill'=>'x')
sayings_lbox.pack('expand'=>'yes', 'fill'=>'y')
else
sayings_lbox.grid('row'=>0, 'column'=>0,
'rowspan'=>1, 'columnspan'=>1, 'sticky'=>'news')
sv.grid('row'=>0, 'column'=>1,
'rowspan'=>1, 'columnspan'=>1, 'sticky'=>'news')
sh.grid('row'=>1, 'column'=>0,
'rowspan'=>1, 'columnspan'=>1, 'sticky'=>'news')
TkGrid.rowconfigure(w, 0, 'weight'=>1, 'minsize'=>0)
TkGrid.columnconfigure(w, 0, 'weight'=>1, 'minsize'=>0)
end
}.pack('side'=>'top', 'expand'=>'yes', 'fill'=>'y')
sayings_lbox.insert(0,
"Waste not, want not",
"Early to bed and early to rise makes a man healthy, wealthy, and wise",
"Ask not what your country can do for you, ask what you can do for your country",
"I shall return",
"NOT",
"A picture is worth a thousand words",
"User interfaces are hard to build",
"Thou shalt not steal",
"A penny for your thoughts",
"Fool me once, shame on you; fool me twice, shame on me",
"Every cloud has a silver lining",
"Where there's smoke there's fire",
"It takes one to know one",
"Curiosity killed the cat; but satisfaction brought it back",
"Take this job and shove it",
"Up a creek without a paddle",
"I'm mad as hell and I'm not going to take it any more",
"An apple a day keeps the doctor away",
"Don't look a gift horse in the mouth"
)
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/puma-1.6.3/lib/puma/compat.rb
|
# Provides code to work properly on 1.8 and 1.9
class String
unless method_defined? :bytesize
alias_method :bytesize, :size
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tcltklib/safeTk.rb
|
#!/usr/bin/env ruby
require 'tcltklib'
master = TclTkIp.new
slave_name = 'slave0'
slave = master.create_slave(slave_name, true)
master._eval("::safe::interpInit #{slave_name}")
master._eval("::safe::loadTk #{slave_name}")
master._invoke('label', '.l1', '-text', 'master')
master._invoke('pack', '.l1', '-padx', '30', '-pady', '50')
master._eval('label .l2 -text {root widget of master-ip}')
master._eval('pack .l2 -padx 30 -pady 50')
slave._invoke('label', '.l1', '-text', 'slave')
slave._invoke('pack', '.l1', '-padx', '30', '-pady', '50')
slave._eval('label .l2 -text {root widget of slave-ip}')
slave._eval('pack .l2 -padx 30 -pady 20')
slave._eval('label .l3 -text {( container frame widget of master-ip )}')
slave._eval('pack .l3 -padx 30 -pady 20')
TclTkLib.mainloop
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/lib/rubygems/package/source.rb
|
# frozen_string_literal: false
class Gem::Package::Source # :nodoc:
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/lib/ohai/plugins/windows/kernel_devices.rb
|
<reponame>arnab0073/idea
#
# 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.
#
require 'ruby-wmi'
WIN32OLE.codepage = WIN32OLE::CP_UTF8
kext = Mash.new
pnp_drivers = Mash.new
drivers = WMI::Win32_PnPSignedDriver.find(:all)
drivers.each do |driver|
pnp_drivers[driver.DeviceID] = Mash.new
driver.properties_.each do |p|
pnp_drivers[driver.DeviceID][p.name.wmi_underscore.to_sym] = driver.send(p.name)
end
if driver.DeviceName
kext[driver.DeviceName] = pnp_drivers[driver.DeviceID]
kext[driver.DeviceName][:version] = pnp_drivers[driver.DeviceID][:driver_version]
kext[driver.DeviceName][:date] = pnp_drivers[driver.DeviceID][:driver_date] ? pnp_drivers[driver.DeviceID][:driver_date].to_s[0..7] : nil
end
end
kernel[:pnp_drivers] = pnp_drivers
kernel[:modules] = kext
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/demos-en/entry3.rb
|
<reponame>arnab0073/idea
# entry3.rb --
#
# This demonstration script creates several entry widgets whose
# permitted input is constrained in some way. It also shows off a
# password entry.
#
# based on Tcl/Tk8.4.4 widget demos
if defined?($entry3_demo) && $entry3_demo
$entry3_demo.destroy
$entry3_demo = nil
end
$entry3_demo = TkToplevel.new {|w|
title("Constrained Entry Demonstration")
iconname("entry3")
positionWindow(w)
}
base_frame = TkFrame.new($entry3_demo).pack(:fill=>:both, :expand=>true)
TkLabel.new(base_frame,
:font=>$font, :wraplength=>'5i', :justify=>:left,
:text=><<EOL).pack(:side=>:top)
Four different entries are displayed below. You can add characters \
by pointing, clicking and typing, though each is constrained in what \
it will accept. The first only accepts integers or the empty string \
(checking when focus leaves it) and will flash to indicate any \
problem. The second only accepts strings with fewer than ten \
characters and sounds the bell when an attempt to go over the limit \
is made. The third accepts US phone numbers, mapping letters to \
their digit equivalent and sounding the bell on encountering an \
invalid character or if trying to type over a character that is not \
a digit. The fourth is a password field that accepts up to eight \
characters (silently ignoring further ones), and displaying them as \
asterisk characters.
EOL
TkFrame.new(base_frame){|f|
pack(:side=>:bottom, :fill=>:x, :pady=>'2m')
TkButton.new(f, :text=>'Dismiss', :width=>15, :command=>proc{
$entry3_demo.destroy
$entry3_demo = nil
}).pack(:side=>:left, :expand=>true)
TkButton.new(f, :text=>'See Code', :width=>15, :command=>proc{
showCode 'entry3'
}).pack(:side=>:left, :expand=>true)
}
# focusAndFlash --
# Error handler for entry widgets that forces the focus onto the
# widget and makes the widget flash by exchanging the foreground and
# background colours at intervals of 200ms (i.e. at approximately
# 2.5Hz).
#
# Arguments:
# widget - entry widget to flash
# fg - Initial foreground colour
# bg - Initial background colour
# count - Counter to control the number of times flashed
def focusAndFlash(widget, fg, bg, count=5)
return if count <= 0
if fg && !fg.empty? && bg && !bg.empty?
TkTimer.new(200, count,
proc{widget.configure(:foreground=>bg, :background=>fg)},
proc{widget.configure(:foreground=>fg, :background=>bg)}
).start
else
# TkTimer.new(150, 3){Tk.bell}.start
Tk.bell
TkTimer.new(200, count,
proc{widget.configure(:foreground=>'white',
:background=>'black')},
proc{widget.configure(:foreground=>'black',
:background=>'white')}
).at_end{begin
widget.configure(:foreground=>fg,
:background=>bg)
rescue
# ignore
end}.start
end
widget.focus(true)
end
l1 = TkLabelFrame.new(base_frame, :text=>"Integer Entry")
TkEntry.new(l1, :validate=>:focus,
:vcmd=>[
proc{|s| s == '' || /^[+-]?\d+$/ =~ s }, '%P'
]) {|e|
fg = e.foreground
bg = e.background
invalidcommand [proc{|w| focusAndFlash(w, fg, bg)}, '%W']
pack(:fill=>:x, :expand=>true, :padx=>'1m', :pady=>'1m')
}
l2 = TkLabelFrame.new(base_frame, :text=>"Length-Constrained Entry")
TkEntry.new(l2, :validate=>:key, :invcmd=>proc{Tk.bell},
:vcmd=>[proc{|s| s.length < 10}, '%P']
).pack(:fill=>:x, :expand=>true, :padx=>'1m', :pady=>'1m')
### PHONE NUMBER ENTRY ###
# Note that the source to this is quite a bit longer as the behaviour
# demonstrated is a lot more ambitious than with the others.
# Initial content for the third entry widget
entry3content = TkVariable.new("1-(000)-000-0000")
# Mapping from alphabetic characters to numbers.
$phoneNumberMap = {}
Hash[*(%w(abc 2 def 3 ghi 4 jkl 5 mno 6 pqrs 7 tuv 8 wxyz 9))].each{|chars, n|
chars.split('').each{|c|
$phoneNumberMap[c] = n
$phoneNumberMap[c.upcase] = n
}
}
# phoneSkipLeft --
# Skip over fixed characters in a phone-number string when moving left.
#
# Arguments:
# widget - The entry widget containing the phone-number.
def phoneSkipLeft(widget)
idx = widget.index('insert')
if idx == 8
# Skip back two extra characters
widget.cursor = idx - 2
elsif idx == 7 || idx == 12
# Skip back one extra character
widget.cursor = idx - 1
elsif idx <= 3
# Can't move any further
Tk.bell
Tk.callback_break
end
end
# phoneSkipRight --
# Skip over fixed characters in a phone-number string when moving right.
#
# Arguments:
# widget - The entry widget containing the phone-number.
# add - Offset to add to index before calculation (used by validation.)
def phoneSkipRight(widget, add = 0)
idx = widget.index('insert')
if (idx + add == 5)
# Skip forward two extra characters
widget.cursor = idx + 2
elsif (idx + add == 6 || idx + add == 10)
# Skip forward one extra character
widget.cursor = idx + 1
elsif (idx + add == 15 && add == 0)
# Can't move any further
Tk.bell
Tk.callback_break
end
end
# validatePhoneChange --
# Checks that the replacement (mapped to a digit) of the given
# character in an entry widget at the given position will leave a
# valid phone number in the widget.
#
# widget - entry widget to validate
# vmode - The widget's validation mode
# idx - The index where replacement is to occur
# char - The character (or string, though that will always be
# refused) to be overwritten at that point.
def validatePhoneChange(widget, vmode, idx, char)
return true if idx == nil
Tk.after_idle(proc{widget.configure(:validate=>vmode,
:invcmd=>proc{Tk.bell})})
if !(idx<3 || idx==6 || idx==7 || idx==11 || idx>15) && char =~ /[0-9A-Za-z]/
widget.delete(idx)
widget.insert(idx, $phoneNumberMap[char] || char)
Tk.after_idle(proc{phoneSkipRight(widget, -1)})
return true
# Tk.update(true) # <- Don't work 'update' inter validation callback.
# It depends on Tcl/Tk side (tested on Tcl/Tk8.5a1).
end
return false
end
l3 = TkLabelFrame.new(base_frame, :text=>"US Phone-Number Entry")
TkEntry.new(l3, :validate=>:key, :invcmd=>proc{Tk.bell},
:textvariable=>entry3content,
:vcmd=>[
proc{|w,v,i,s| validatePhoneChange(w,v,i,s)},
"%W %v %i %S"
]){|e|
# Click to focus goes to the first editable character...
bind('FocusIn', proc{|d,w|
if d != "NotifyAncestor"
w.cursor = 3
Tk.after_idle(proc{w.selection_clear})
end
}, '%d %W')
bind('Left', proc{|w| phoneSkipLeft(w)}, '%W')
bind('Right', proc{|w| phoneSkipRight(w)}, '%W')
pack(:fill=>:x, :expand=>true, :padx=>'1m', :pady=>'1m')
}
l4 = TkLabelFrame.new(base_frame, :text=>"Password Entry")
TkEntry.new(l4, :validate=>:key, :show=>'*',
:vcmd=>[
proc{|s| s.length <= 8},
'%P'
]).pack(:fill=>:x, :expand=>true, :padx=>'1m', :pady=>'1m')
TkFrame.new(base_frame){|f|
lower
TkGrid.configure(l1, l2, :in=>f, :padx=>'3m', :pady=>'1m', :sticky=>:ew)
TkGrid.configure(l3, l4, :in=>f, :padx=>'3m', :pady=>'1m', :sticky=>:ew)
TkGrid.columnconfigure(f, [0,1], :uniform=>1)
pack(:fill=>:both, :expand=>true)
}
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/tk/lib/tkextlib/tkDND/tkdnd.rb
|
<reponame>arnab0073/idea
# frozen_string_literal: false
#
# tkextlib/tkDND/tkdnd.rb
# by <NAME> (<EMAIL>)
#
require 'tk'
# call setup script for general 'tkextlib' libraries
require 'tkextlib/setup.rb'
# call setup script
require 'tkextlib/tkDND/setup.rb'
TkPackage.require('tkdnd')
module Tk
module TkDND
PACKAGE_NAME = 'tkdnd'.freeze
def self.package_name
PACKAGE_NAME
end
def self.package_version
begin
TkPackage.require('tkdnd')
rescue
''
end
end
class DND_Subst < TkUtil::CallbackSubst
KEY_TBL = [
[ ?a, ?l, :actions ],
[ ?A, ?s, :action ],
[ ?b, ?L, :codes ],
[ ?c, ?s, :code ],
[ ?d, ?l, :descriptions ],
[ ?D, ?l, :data ],
[ ?L, ?l, :source_types ],
[ ?m, ?l, :modifiers ],
[ ?t, ?l, :types ],
[ ?T, ?s, :type ],
[ ?W, ?w, :widget ],
[ ?x, ?n, :x ],
[ ?X, ?n, :x_root ],
[ ?y, ?n, :y ],
[ ?Y, ?n, :y_root ],
nil
]
PROC_TBL = [
[ ?n, TkComm.method(:num_or_str) ],
[ ?s, TkComm.method(:string) ],
[ ?l, TkComm.method(:list) ],
[ ?L, TkComm.method(:simplelist) ],
[ ?w, TkComm.method(:window) ],
nil
]
=begin
# for Ruby m17n :: ?x --> String --> char-code ( getbyte(0) )
KEY_TBL.map!{|inf|
if inf.kind_of?(Array)
inf[0] = inf[0].getbyte(0) if inf[0].kind_of?(String)
inf[1] = inf[1].getbyte(0) if inf[1].kind_of?(String)
end
inf
}
PROC_TBL.map!{|inf|
if inf.kind_of?(Array)
inf[0] = inf[0].getbyte(0) if inf[0].kind_of?(String)
end
inf
}
=end
# setup tables
_setup_subst_table(KEY_TBL, PROC_TBL);
end
module DND
def self.version
begin
TkPackage.require('tkdnd')
rescue
''
end
end
def dnd_bindtarget_info(type=nil, event=nil)
if event
procedure(tk_call('dnd', 'bindtarget', @path, type, event))
elsif type
procedure(tk_call('dnd', 'bindtarget', @path, type))
else
simplelist(tk_call('dnd', 'bindtarget', @path))
end
end
#def dnd_bindtarget(type, event, cmd=Proc.new, prior=50, *args)
# event = tk_event_sequence(event)
# if prior.kind_of?(Numeric)
# tk_call('dnd', 'bindtarget', @path, type, event,
# install_bind_for_event_class(DND_Subst, cmd, *args),
# prior)
# else
# tk_call('dnd', 'bindtarget', @path, type, event,
# install_bind_for_event_class(DND_Subst, cmd, prior, *args))
# end
# self
#end
def dnd_bindtarget(type, event, *args)
# 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
prior = 50
prior = args.shift unless args.empty?
event = tk_event_sequence(event)
if prior.kind_of?(Numeric)
tk_call('dnd', 'bindtarget', @path, type, event,
install_bind_for_event_class(DND_Subst, cmd, *args),
prior)
else
tk_call('dnd', 'bindtarget', @path, type, event,
install_bind_for_event_class(DND_Subst, cmd, prior, *args))
end
self
end
def dnd_cleartarget
tk_call('dnd', 'cleartarget', @path)
self
end
def dnd_bindsource_info(type=nil)
if type
procedure(tk_call('dnd', 'bindsource', @path, type))
else
simplelist(tk_call('dnd', 'bindsource', @path))
end
end
#def dnd_bindsource(type, cmd=Proc.new, prior=None)
# tk_call('dnd', 'bindsource', @path, type, cmd, prior)
# self
#end
def dnd_bindsource(type, *args)
# 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
args = [TkComm::None] if args.empty?
tk_call('dnd', 'bindsource', @path, type, cmd, *args)
self
end
def dnd_clearsource()
tk_call('dnd', 'clearsource', @path)
self
end
def dnd_drag(keys=nil)
tk_call('dnd', 'drag', @path, *hash_kv(keys))
self
end
end
end
end
class TkWindow
include Tk::TkDND::DND
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/net-ssh-multi-1.2.0/lib/net/ssh/multi/dynamic_server.rb
|
<reponame>arnab0073/idea<filename>.rvm/gems/ruby-2.3.0/gems/net-ssh-multi-1.2.0/lib/net/ssh/multi/dynamic_server.rb
require 'net/ssh/multi/server'
module Net; module SSH; module Multi
# Represents a lazily evaluated collection of servers. This will usually be
# created via Net::SSH::Multi::Session#use(&block), and is useful for creating
# server definitions where the name or address of the servers are not known
# until run-time.
#
# session.use { lookup_ip_address_of_server }
#
# This prevents +lookup_ip_address_of_server+ from being invoked unless the
# server is actually needed, at which point it is invoked and the result
# cached.
#
# The callback should return either +nil+ (in which case no new servers are
# instantiated), a String (representing a connection specification), an
# array of Strings, or an array of Net::SSH::Multi::Server instances.
class DynamicServer
# The Net::SSH::Multi::Session instance that owns this dynamic server record.
attr_reader :master
# The Proc object to call to evaluate the server(s)
attr_reader :callback
# The hash of options that will be used to initialize the server records.
attr_reader :options
# Create a new DynamicServer record, owned by the given Net::SSH::Multi::Session
# +master+, with the given hash of +options+, and using the given Proc +callback+
# to lazily evaluate the actual server instances.
def initialize(master, options, callback)
@master, @options, @callback = master, options, callback
@servers = nil
end
# Returns the value for the given +key+ in the :properties hash of the
# +options+. If no :properties hash exists in +options+, this returns +nil+.
def [](key)
(options[:properties] ||= {})[key]
end
# Sets the given key/value pair in the +:properties+ key in the options
# hash. If the options hash has no :properties key, it will be created.
def []=(key, value)
(options[:properties] ||= {})[key] = value
end
# Iterates over every instantiated server record in this dynamic server.
# If the servers have not yet been instantiated, this does nothing (e.g.,
# it does _not_ automatically invoke #evaluate!).
def each
(@servers || []).each { |server| yield server }
end
# Evaluates the callback and instantiates the servers, memoizing the result.
# Subsequent calls to #evaluate! will simply return the cached list of
# servers.
def evaluate!
@servers ||= Array(callback[options]).map do |server|
case server
when String then Net::SSH::Multi::Server.new(master, server, options)
else server
end
end
end
alias to_ary evaluate!
end
end; end; end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/examples/names.rb
|
<gh_stars>100-1000
# :stopdoc:
#
# Loggers and appenders can be looked up by name. The bracket notation is
# used to find these objects:
#
# Logging.logger['foo']
# Logging.appenders['bar']
#
# A logger will be created if a new name is used. Appenders are different;
# nil is returned when an unknown appender name is used. The reason for this
# is that appenders come in many different flavors (so it is unclear which
# type should be created), but there is only one type of logger.
#
# So it is useful to be able to create an appender and then reference it by
# name to add it to multiple loggers. When the same name is used, the same
# object will be returned by the bracket methods.
#
# Layouts do not have names. Some are stateful, and none are threadsafe. So
# each appender is configured with it's own layout.
#
require 'logging'
Logging.appenders.file('Debug File', :filename => 'debug.log')
Logging.appenders.stderr('Standard Error', :level => :error)
# configure the root logger
Logging.logger.root.appenders = 'Debug File'
Logging.logger.root.level = :debug
# add the Standard Error appender to the Critical logger (it will use it's
# own appender and the root logger's appender, too)
Logging.logger['Critical'].appenders = 'Standard Error'
# if you'll notice above, assigning appenders using just the name is valid
# the logger is smart enough to figure out it was given a string and then
# go lookup the appender by name
# and now log some messages
Logging.logger['Critical'].info 'just keeping you informed'
Logging.logger['Critical'].fatal 'WTF!!'
# :startdoc:
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/ruby/test_threadgroup.rb
|
<gh_stars>10-100
# frozen_string_literal: false
require 'test/unit'
require 'thread'
class TestThreadGroup < Test::Unit::TestCase
def test_thread_init
thgrp = ThreadGroup.new
th = Thread.new{
thgrp.add(Thread.current)
Thread.new{sleep 1}
}.value
assert_equal(thgrp, th.group)
ensure
th.join
end
def test_frozen_thgroup
thgrp = ThreadGroup.new
t = Thread.new{1}
Thread.new{
thgrp.add(Thread.current)
thgrp.freeze
assert_raise(ThreadError) do
Thread.new{1}.join
end
assert_raise(ThreadError) do
thgrp.add(t)
end
assert_raise(ThreadError) do
ThreadGroup.new.add Thread.current
end
}.join
t.join
end
def test_enclosed_thgroup
thgrp = ThreadGroup.new
assert_equal(false, thgrp.enclosed?)
t = Thread.new{1}
Thread.new{
thgrp.add(Thread.current)
thgrp.enclose
assert_equal(true, thgrp.enclosed?)
assert_nothing_raised do
Thread.new{1}.join
end
assert_raise(ThreadError) do
thgrp.add t
end
assert_raise(ThreadError) do
ThreadGroup.new.add Thread.current
end
}.join
t.join
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/-test-/wait_for_single_fd/extconf.rb
|
create_makefile("-test-/wait_for_single_fd/wait_for_single_fd")
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/prelude.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/prelude.rb
class Mutex
# call-seq:
# mutex.synchronize { ... }
#
# Obtains a lock, runs the block, and releases the lock when the
# block completes. See the example under Mutex.
def synchronize
self.lock
begin
yield
ensure
self.unlock rescue nil
end
end
end
class Thread
MUTEX_FOR_THREAD_EXCLUSIVE = Mutex.new # :nodoc:
# call-seq:
# Thread.exclusive { block } => obj
#
# Wraps a block in Thread.critical, restoring the original value
# upon exit from the critical section, and returns the value of the
# block.
def self.exclusive
MUTEX_FOR_THREAD_EXCLUSIVE.synchronize{
yield
}
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/rdoc/test_rdoc_markup_indented_paragraph.rb
|
<reponame>arnab0073/idea<gh_stars>10-100
# frozen_string_literal: false
require 'rdoc/test_case'
class TestRDocMarkupIndentedParagraph < RDoc::TestCase
def setup
super
@IP = RDoc::Markup::IndentedParagraph
end
def test_initialize
ip = @IP.new 2, 'a', 'b'
assert_equal 2, ip.indent
assert_equal %w[a b], ip.parts
end
def test_accept
visitor = Object.new
def visitor.accept_indented_paragraph(obj) @obj = obj end
def visitor.obj() @obj end
paragraph = @IP.new 0
paragraph.accept visitor
assert_equal paragraph, visitor.obj
end
def test_equals2
one = @IP.new 1
two = @IP.new 2
assert_equal one, one
refute_equal one, two
end
def test_text
paragraph = @IP.new(2, 'hello', ' world')
assert_equal 'hello world', paragraph.text
end
def test_text_break
paragraph = @IP.new(2, 'hello', hard_break, 'world')
assert_equal 'helloworld', paragraph.text
assert_equal "hello\n world", paragraph.text("\n")
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/tk/lib/tkextlib/tcllib/toolbar.rb
|
# frozen_string_literal: false
#
# tkextlib/tcllib/toolbar.rb
# by <NAME> (<EMAIL>)
#
# * Part of tcllib extension
# * toolbar widget
#
require 'tk'
require 'tkextlib/tcllib.rb'
# TkPackage.require('widget::toolbar', '1.2')
TkPackage.require('widget::toolbar')
module Tk::Tcllib
module Widget
class Toolbar < TkWindow
PACKAGE_NAME = 'widget::toolbar'.freeze
def self.package_name
PACKAGE_NAME
end
def self.package_version
begin
TkPackage.require('widget::toolbar')
rescue
''
end
end
end
module ToolbarItemConfig
include TkItemConfigMethod
end
end
end
class Tk::Tcllib::Widget::ToolbarItem < TkObject
include TkTreatTagFont
ToolbarItemID_TBL = TkCore::INTERP.create_table
TkCore::INTERP.init_ip_env{
TTagID_TBL.mutex.synchronize{ TTagID_TBL.clear }
}
def ToolbarItem.id2obj(tbar, id)
tpath = tbar.path
ToolbarItemID_TBL.mutex.synchronize{
if ToolbarItemID_TBL[tpath]
ToolbarItemID_TBL[tpath][id]? ToolbarItemID_TBL[tpath][id]: id
else
id
end
}
end
def initaialize(parent, *args)
@parent = @t = parent
@tpath = parent.path
@path = @id = @t.tk_send('add', *args)
# A same id is rejected by the Tcl function.
ToolbarItemID_TBL.mutex.synchronize{
ToolbarItemID_TBL[@id] = self
ToolbarItemID_TBL[@tpath] = {} unless ToolbarItemID_TBL[@tpath]
ToolbarItemID_TBL[@tpath][@id] = self
}
end
def [](key)
cget key
end
def []=(key,val)
configure key, val
val
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 delete
@t.delete(@id)
end
def itemid
@t.itemid(@id)
end
def remove
@t.remove(@id)
end
def remove_with_destroy
@t.remove_with_destroy(@id)
end
end
class Tk::Tcllib::Widget::Toolbar
include Tk::Tcllib::Widget::ToolbarItemConfig
TkCommandNames = ['::widget::toolbar'.freeze].freeze
def __destroy_hook__
Tk::Tcllib::Widget::ToolbarItem::ToolbarItemID_TBL.mutex.synchronize{
Tk::Tcllib::Widget::ToolbarItem::ToolbarItemID_TBL.delete(@path)
}
end
def create_self(keys)
if keys and keys != None
tk_call_without_enc(self.class::TkCommandNames[0], @path,
*hash_kv(keys, true))
else
tk_call_without_enc(self.class::TkCommandNames[0], @path)
end
end
private :create_self
def getframe
window(tk_send('getframe'))
end
alias get_frame getframe
def add(*args)
Tk::Tcllib::Widget::Toolbar.new(self, *args)
end
def itemid(item)
window(tk_send('itemid'))
end
def items(pattern)
tk_split_simplelist(tk_send('items', pattern)).map{|id|
Tk::Tcllib::Widget::ToolbarItem.id2obj(self, id)
}
end
def remove(*items)
tk_send('remove', *items)
self
end
def remove_with_destroy(*items)
tk_send('remove', '-destroy', *items)
self
end
def delete(*items)
tk_send('delete', *items)
self
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/rubygems/bad_rake.rb
|
# frozen_string_literal: false
exit 1
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/psych/test_marshalable.rb
|
<filename>.rvm/src/ruby-2.3.0/test/psych/test_marshalable.rb<gh_stars>10-100
# frozen_string_literal: false
require_relative 'helper'
require 'delegate'
module Psych
class TestMarshalable < TestCase
def test_objects_defining_marshal_dump_and_marshal_load_can_be_dumped
sd = SimpleDelegator.new(1)
loaded = Psych.load(Psych.dump(sd))
assert_instance_of(SimpleDelegator, loaded)
assert_equal(sd, loaded)
end
class PsychCustomMarshalable < BasicObject
attr_reader :foo
def initialize(foo)
@foo = foo
end
def marshal_dump
[foo]
end
def mashal_load(data)
@foo = data[0]
end
def init_with(coder)
@foo = coder['foo']
end
def encode_with(coder)
coder['foo'] = 2
end
def respond_to?(method)
[:marshal_dump, :marshal_load, :init_with, :encode_with].include?(method)
end
def class
PsychCustomMarshalable
end
end
def test_init_with_takes_priority_over_marshal_methods
obj = PsychCustomMarshalable.new(1)
loaded = Psych.load(Psych.dump(obj))
assert(PsychCustomMarshalable === loaded)
assert_equal(2, loaded.foo)
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/excon-0.49.0/lib/excon/middlewares/decompress.rb
|
<gh_stars>0
module Excon
module Middleware
class Decompress < Excon::Middleware::Base
def request_call(datum)
unless datum.has_key?(:response_block)
key = datum[:headers].keys.detect {|k| k.to_s.casecmp('Accept-Encoding') == 0 } || 'Accept-Encoding'
if datum[:headers][key].to_s.empty?
datum[:headers][key] = 'deflate, gzip'
end
end
@stack.request_call(datum)
end
def response_call(datum)
body = datum[:response][:body]
unless datum.has_key?(:response_block) || body.nil? || body.empty?
if key = datum[:response][:headers].keys.detect {|k| k.casecmp('Content-Encoding') == 0 }
encodings = Utils.split_header_value(datum[:response][:headers][key])
if encoding = encodings.last
if encoding.casecmp('deflate') == 0
# assume inflate omits header
datum[:response][:body] = Zlib::Inflate.new(-Zlib::MAX_WBITS).inflate(body)
encodings.pop
elsif encoding.casecmp('gzip') == 0 || encoding.casecmp('x-gzip') == 0
datum[:response][:body] = Zlib::GzipReader.new(StringIO.new(body)).read
encodings.pop
end
datum[:response][:headers][key] = encodings.join(', ')
end
end
end
@stack.response_call(datum)
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/lib/test/unit/parallel.rb
|
# frozen_string_literal: false
$LOAD_PATH.unshift "#{File.dirname(__FILE__)}/../.."
require 'test/unit'
module Test
module Unit
class Worker < Runner # :nodoc:
class << self
undef autorun
end
alias orig_run_suite mini_run_suite
undef _run_suite
undef _run_suites
undef run
def increment_io(orig) # :nodoc:
*rest, io = 32.times.inject([orig.dup]){|ios, | ios << ios.last.dup }
rest.each(&:close)
io
end
def _run_suites(suites, type) # :nodoc:
suites.map do |suite|
_run_suite(suite, type)
end
end
def _run_suite(suite, type) # :nodoc:
@partial_report = []
orig_testout = MiniTest::Unit.output
i,o = IO.pipe
MiniTest::Unit.output = o
orig_stdin, orig_stdout = $stdin, $stdout
th = Thread.new do
begin
while buf = (self.verbose ? i.gets : i.readpartial(1024))
_report "p", buf
end
rescue IOError
rescue Errno::EPIPE
end
end
e, f, s = @errors, @failures, @skips
begin
result = orig_run_suite(suite, type)
rescue Interrupt
@need_exit = true
result = [nil,nil]
end
MiniTest::Unit.output = orig_testout
$stdin = orig_stdin
$stdout = orig_stdout
o.close
begin
th.join
rescue IOError
raise unless ["stream closed","closed stream"].include? $!.message
end
i.close
result << @partial_report
@partial_report = nil
result << [@errors-e,@failures-f,@skips-s]
result << ($: - @old_loadpath)
result << suite.name
begin
_report "done", Marshal.dump(result)
rescue Errno::EPIPE; end
return result
ensure
MiniTest::Unit.output = orig_stdout
$stdin = orig_stdin if orig_stdin
$stdout = orig_stdout if orig_stdout
o.close if o && !o.closed?
i.close if i && !i.closed?
end
def run(args = []) # :nodoc:
process_args args
@@stop_auto_run = true
@opts = @options.dup
@need_exit = false
@old_loadpath = []
begin
begin
@stdout = increment_io(STDOUT)
@stdin = increment_io(STDIN)
rescue
exit 2
end
exit 2 unless @stdout && @stdin
@stdout.sync = true
_report "ready!"
while buf = @stdin.gets
case buf.chomp
when /^loadpath (.+?)$/
@old_loadpath = $:.dup
$:.push(*Marshal.load($1.unpack("m")[0].force_encoding("ASCII-8BIT"))).uniq!
when /^run (.+?) (.+?)$/
_report "okay"
@options = @opts.dup
suites = MiniTest::Unit::TestCase.test_suites
begin
require File.realpath($1)
rescue LoadError
_report "after", Marshal.dump([$1, ProxyError.new($!)])
_report "ready"
next
end
_run_suites MiniTest::Unit::TestCase.test_suites-suites, $2.to_sym
if @need_exit
begin
_report "bye"
rescue Errno::EPIPE; end
exit
else
_report "ready"
end
when /^quit$/
begin
_report "bye"
rescue Errno::EPIPE; end
exit
end
end
rescue Errno::EPIPE
rescue Exception => e
begin
trace = e.backtrace || ['unknown method']
err = ["#{trace.shift}: #{e.message} (#{e.class})"] + trace.map{|t| t.prepend("\t") }
_report "bye", Marshal.dump(err.join("\n"))
rescue Errno::EPIPE;end
exit
ensure
@stdin.close if @stdin
@stdout.close if @stdout
end
end
def _report(res, *args) # :nodoc:
res = "#{res} #{args.pack("m0")}" unless args.empty?
@stdout.puts(res)
end
def puke(klass, meth, e) # :nodoc:
if e.is_a?(MiniTest::Skip)
new_e = MiniTest::Skip.new(e.message)
new_e.set_backtrace(e.backtrace)
e = new_e
end
@partial_report << [klass.name, meth, e.is_a?(MiniTest::Assertion) ? e : ProxyError.new(e)]
super
end
end
end
end
if $0 == __FILE__
module Test
module Unit
class TestCase < MiniTest::Unit::TestCase # :nodoc: all
undef on_parallel_worker?
def on_parallel_worker?
true
end
end
end
end
require 'rubygems'
module Gem # :nodoc:
end
class Gem::TestCase < MiniTest::Unit::TestCase # :nodoc:
@@project_dir = File.expand_path('../../../../..', __FILE__)
end
Test::Unit::Worker.new.run(ARGV)
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/gssapi-1.2.0/test/spec/gssapi_simple_spec.rb
|
<gh_stars>1-10
$: << File.dirname(__FILE__) + '/../../lib/'
require 'gssapi'
require 'base64'
require 'yaml'
describe GSSAPI::Simple, 'Test the Simple GSSAPI interface' do
before :all do
@conf = YAML.load_file "#{File.dirname(__FILE__)}/conf_file.yaml"
end
it 'should get the initial context for a client' do
gsscli = GSSAPI::Simple.new(@conf[:c_host], @conf[:c_service])
token = gsscli.init_context
token.should_not be_empty
end
it 'should acquire credentials for a server service' do
gsscli = GSSAPI::Simple.new(@conf[:s_host], @conf[:s_service], @conf[:keytab])
gsscli.acquire_credentials.should be_true
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/lib/rdoc/markup/to_joined_paragraph.rb
|
<reponame>arnab0073/idea
# frozen_string_literal: false
##
# Joins the parts of an RDoc::Markup::Paragraph into a single String.
#
# This allows for easier maintenance and testing of Markdown support.
#
# This formatter only works on Paragraph instances. Attempting to process
# other markup syntax items will not work.
class RDoc::Markup::ToJoinedParagraph < RDoc::Markup::Formatter
def initialize # :nodoc:
super nil
end
def start_accepting # :nodoc:
end
def end_accepting # :nodoc:
end
##
# Converts the parts of +paragraph+ to a single entry.
def accept_paragraph paragraph
parts = []
string = false
paragraph.parts.each do |part|
if String === part then
if string then
string << part
else
parts << part
string = part
end
else
parts << part
string = false
end
end
parts = parts.map do |part|
if String === part then
part.rstrip
else
part
end
end
# TODO use Enumerable#chunk when Ruby 1.8 support is dropped
#parts = paragraph.parts.chunk do |part|
# String === part
#end.map do |string, chunk|
# string ? chunk.join.rstrip : chunk
#end.flatten
paragraph.parts.replace parts
end
alias accept_block_quote ignore
alias accept_heading ignore
alias accept_list_end ignore
alias accept_list_item_end ignore
alias accept_list_item_start ignore
alias accept_list_start ignore
alias accept_raw ignore
alias accept_rule ignore
alias accept_verbatim ignore
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/nori-2.6.0/lib/nori/core_ext/object.rb
|
class Nori
module CoreExt
module Object
def blank?
respond_to?(:empty?) ? empty? : !self
end unless method_defined?(:blank?)
end
end
end
Object.send :include, Nori::CoreExt::Object
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/test/openssl/test_ssl.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/test/openssl/test_ssl.rb
# encoding: utf-8
require_relative "utils"
if defined?(OpenSSL)
class OpenSSL::TestSSL < OpenSSL::SSLTestCase
def test_ctx_setup
ctx = OpenSSL::SSL::SSLContext.new
assert_equal(ctx.setup, true)
assert_equal(ctx.setup, nil)
end
def test_ctx_setup_no_compression
ctx = OpenSSL::SSL::SSLContext.new
ctx.options = OpenSSL::SSL::OP_ALL | OpenSSL::SSL::OP_NO_COMPRESSION
assert_equal(ctx.setup, true)
assert_equal(ctx.setup, nil)
assert_equal(OpenSSL::SSL::OP_NO_COMPRESSION,
ctx.options & OpenSSL::SSL::OP_NO_COMPRESSION)
end if defined?(OpenSSL::SSL::OP_NO_COMPRESSION)
def test_not_started_session
skip "non socket argument of SSLSocket.new is not supported on this platform" if /mswin|mingw/ =~ RUBY_PLATFORM
open(__FILE__) do |f|
assert_nil OpenSSL::SSL::SSLSocket.new(f).cert
end
end
def test_ssl_read_nonblock
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true) { |server, port|
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true
ssl.connect
assert_raise(IO::WaitReadable) { ssl.read_nonblock(100) }
ssl.write("abc\n")
IO.select [ssl]
assert_equal('a', ssl.read_nonblock(1))
assert_equal("bc\n", ssl.read_nonblock(100))
assert_raise(IO::WaitReadable) { ssl.read_nonblock(100) }
}
end
def test_connect_and_close
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
assert(ssl.connect)
ssl.close
assert(!sock.closed?)
sock.close
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true # !!
assert(ssl.connect)
ssl.close
assert(sock.closed?)
}
end
def test_read_and_write
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true
ssl.connect
# syswrite and sysread
ITERATIONS.times{|i|
str = "x" * 100 + "\n"
ssl.syswrite(str)
assert_equal(str, ssl.sysread(str.size))
str = "x" * i * 100 + "\n"
buf = ""
ssl.syswrite(str)
assert_equal(buf.object_id, ssl.sysread(str.size, buf).object_id)
assert_equal(str, buf)
}
# puts and gets
ITERATIONS.times{
str = "x" * 100 + "\n"
ssl.puts(str)
assert_equal(str, ssl.gets)
str = "x" * 100
ssl.puts(str)
assert_equal(str, ssl.gets("\n", 100))
assert_equal("\n", ssl.gets)
}
# read and write
ITERATIONS.times{|i|
str = "x" * 100 + "\n"
ssl.write(str)
assert_equal(str, ssl.read(str.size))
str = "x" * i * 100 + "\n"
buf = ""
ssl.write(str)
assert_equal(buf.object_id, ssl.read(str.size, buf).object_id)
assert_equal(str, buf)
}
ssl.close
}
end
def test_client_auth
vflag = OpenSSL::SSL::VERIFY_PEER|OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT
start_server(PORT, vflag, true){|server, port|
assert_raise(OpenSSL::SSL::SSLError, Errno::ECONNRESET){
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.connect
}
ctx = OpenSSL::SSL::SSLContext.new
ctx.key = @cli_key
ctx.cert = @cli_cert
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
ssl.sync_close = true
ssl.connect
ssl.puts("foo")
assert_equal("foo\n", ssl.gets)
ssl.close
called = nil
ctx = OpenSSL::SSL::SSLContext.new
ctx.client_cert_cb = Proc.new{ |sslconn|
called = true
[@cli_cert, @cli_key]
}
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
ssl.sync_close = true
ssl.connect
assert(called)
ssl.puts("foo")
assert_equal("foo\n", ssl.gets)
ssl.close
}
end
def test_client_ca
ctx_proc = Proc.new do |ctx|
ctx.client_ca = [@ca_cert]
end
vflag = OpenSSL::SSL::VERIFY_PEER|OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT
start_server(PORT, vflag, true, :ctx_proc => ctx_proc){|server, port|
ctx = OpenSSL::SSL::SSLContext.new
client_ca_from_server = nil
ctx.client_cert_cb = Proc.new do |sslconn|
client_ca_from_server = sslconn.client_ca
[@cli_cert, @cli_key]
end
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
ssl.sync_close = true
ssl.connect
assert_equal([@ca], client_ca_from_server)
ssl.close
}
end
def test_starttls
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, false){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true
str = "x" * 1000 + "\n"
OpenSSL::TestUtils.silent do
ITERATIONS.times{
ssl.puts(str)
assert_equal(str, ssl.gets)
}
starttls(ssl)
end
ITERATIONS.times{
ssl.puts(str)
assert_equal(str, ssl.gets)
}
ssl.close
}
end
def test_parallel
GC.start
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|server, port|
ssls = []
10.times{
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.connect
ssl.sync_close = true
ssls << ssl
}
str = "x" * 1000 + "\n"
ITERATIONS.times{
ssls.each{|ssl|
ssl.puts(str)
assert_equal(str, ssl.gets)
}
}
ssls.each{|ssl| ssl.close }
}
end
def test_verify_result
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ctx = OpenSSL::SSL::SSLContext.new
ctx.set_params
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
assert_raise(OpenSSL::SSL::SSLError){ ssl.connect }
assert_equal(OpenSSL::X509::V_ERR_SELF_SIGNED_CERT_IN_CHAIN, ssl.verify_result)
sock = TCPSocket.new("127.0.0.1", port)
ctx = OpenSSL::SSL::SSLContext.new
ctx.set_params(
:verify_callback => Proc.new do |preverify_ok, store_ctx|
store_ctx.error = OpenSSL::X509::V_OK
true
end
)
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
ssl.connect
assert_equal(OpenSSL::X509::V_OK, ssl.verify_result)
sock = TCPSocket.new("127.0.0.1", port)
ctx = OpenSSL::SSL::SSLContext.new
ctx.set_params(
:verify_callback => Proc.new do |preverify_ok, store_ctx|
store_ctx.error = OpenSSL::X509::V_ERR_APPLICATION_VERIFICATION
false
end
)
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
assert_raise(OpenSSL::SSL::SSLError){ ssl.connect }
assert_equal(OpenSSL::X509::V_ERR_APPLICATION_VERIFICATION, ssl.verify_result)
}
end
def test_exception_in_verify_callback_is_ignored
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ctx = OpenSSL::SSL::SSLContext.new
ctx.set_params(
:verify_callback => Proc.new do |preverify_ok, store_ctx|
store_ctx.error = OpenSSL::X509::V_OK
raise RuntimeError
end
)
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
OpenSSL::TestUtils.silent do
# SSLError, not RuntimeError
assert_raise(OpenSSL::SSL::SSLError) { ssl.connect }
end
assert_equal(OpenSSL::X509::V_ERR_CERT_REJECTED, ssl.verify_result)
ssl.close
}
end
def test_sslctx_set_params
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ctx = OpenSSL::SSL::SSLContext.new
ctx.set_params
assert_equal(OpenSSL::SSL::VERIFY_PEER, ctx.verify_mode)
assert_equal(OpenSSL::SSL::SSLContext::DEFAULT_PARAMS[:options], ctx.options)
ciphers = ctx.ciphers
ciphers_versions = ciphers.collect{|_, v, _, _| v }
ciphers_names = ciphers.collect{|v, _, _, _| v }
assert(ciphers_names.all?{|v| /ADH/ !~ v })
assert(ciphers_versions.all?{|v| /SSLv2/ !~ v })
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
assert_raise(OpenSSL::SSL::SSLError){ ssl.connect }
assert_equal(OpenSSL::X509::V_ERR_SELF_SIGNED_CERT_IN_CHAIN, ssl.verify_result)
}
end
def test_post_connection_check
sslerr = OpenSSL::SSL::SSLError
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.connect
assert_raise(sslerr){ssl.post_connection_check("localhost.localdomain")}
assert_raise(sslerr){ssl.post_connection_check("127.0.0.1")}
assert(ssl.post_connection_check("localhost"))
assert_raise(sslerr){ssl.post_connection_check("foo.example.com")}
cert = ssl.peer_cert
assert(!OpenSSL::SSL.verify_certificate_identity(cert, "localhost.localdomain"))
assert(!OpenSSL::SSL.verify_certificate_identity(cert, "127.0.0.1"))
assert(OpenSSL::SSL.verify_certificate_identity(cert, "localhost"))
assert(!OpenSSL::SSL.verify_certificate_identity(cert, "foo.example.com"))
}
now = Time.now
exts = [
["keyUsage","keyEncipherment,digitalSignature",true],
["subjectAltName","DNS:localhost.localdomain",false],
["subjectAltName","IP:127.0.0.1",false],
]
@svr_cert = issue_cert(@svr, @svr_key, 4, now, now+1800, exts,
@ca_cert, @ca_key, OpenSSL::Digest::SHA1.new)
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.connect
assert(ssl.post_connection_check("localhost.localdomain"))
assert(ssl.post_connection_check("127.0.0.1"))
assert_raise(sslerr){ssl.post_connection_check("localhost")}
assert_raise(sslerr){ssl.post_connection_check("foo.example.com")}
cert = ssl.peer_cert
assert(OpenSSL::SSL.verify_certificate_identity(cert, "localhost.localdomain"))
assert(OpenSSL::SSL.verify_certificate_identity(cert, "127.0.0.1"))
assert(!OpenSSL::SSL.verify_certificate_identity(cert, "localhost"))
assert(!OpenSSL::SSL.verify_certificate_identity(cert, "foo.example.com"))
}
now = Time.now
exts = [
["keyUsage","keyEncipherment,digitalSignature",true],
["subjectAltName","DNS:*.localdomain",false],
]
@svr_cert = issue_cert(@svr, @svr_key, 5, now, now+1800, exts,
@ca_cert, @ca_key, OpenSSL::Digest::SHA1.new)
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.connect
assert(ssl.post_connection_check("localhost.localdomain"))
assert_raise(sslerr){ssl.post_connection_check("127.0.0.1")}
assert_raise(sslerr){ssl.post_connection_check("localhost")}
assert_raise(sslerr){ssl.post_connection_check("foo.example.com")}
cert = ssl.peer_cert
assert(OpenSSL::SSL.verify_certificate_identity(cert, "localhost.localdomain"))
assert(!OpenSSL::SSL.verify_certificate_identity(cert, "127.0.0.1"))
assert(!OpenSSL::SSL.verify_certificate_identity(cert, "localhost"))
assert(!OpenSSL::SSL.verify_certificate_identity(cert, "foo.example.com"))
}
end
def test_verify_certificate_identity
[true, false].each do |criticality|
cert = create_null_byte_SAN_certificate(criticality)
assert_equal(false, OpenSSL::SSL.verify_certificate_identity(cert, 'www.example.com'))
assert_equal(true, OpenSSL::SSL.verify_certificate_identity(cert, "www.example.com\0.evil.com"))
assert_equal(false, OpenSSL::SSL.verify_certificate_identity(cert, '192.168.7.255'))
assert_equal(true, OpenSSL::SSL.verify_certificate_identity(cert, '192.168.7.1'))
assert_equal(false, OpenSSL::SSL.verify_certificate_identity(cert, 'fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b'))
assert_equal(true, OpenSSL::SSL.verify_certificate_identity(cert, 'fc00:e968:6179::de52:7100'))
end
end
def test_verify_hostname
assert_equal(true, OpenSSL::SSL.verify_hostname("www.example.com", "*.example.com"))
assert_equal(false, OpenSSL::SSL.verify_hostname("www.subdomain.example.com", "*.example.com"))
end
def test_verify_wildcard
assert_equal(false, OpenSSL::SSL.verify_wildcard("foo", "x*"))
assert_equal(true, OpenSSL::SSL.verify_wildcard("foo", "foo"))
assert_equal(true, OpenSSL::SSL.verify_wildcard("foo", "f*"))
assert_equal(true, OpenSSL::SSL.verify_wildcard("foo", "*"))
assert_equal(false, OpenSSL::SSL.verify_wildcard("abc*bcd", "abcd"))
assert_equal(false, OpenSSL::SSL.verify_wildcard("xn--qdk4b9b", "x*"))
assert_equal(false, OpenSSL::SSL.verify_wildcard("xn--qdk4b9b", "*--qdk4b9b"))
assert_equal(true, OpenSSL::SSL.verify_wildcard("xn--qdk4b9b", "xn--qdk4b9b"))
end
# Comments in this test is excerpted from http://tools.ietf.org/html/rfc6125#page-27
def test_post_connection_check_wildcard_san
# case-insensitive ASCII comparison
# RFC 6125, section 6.4.1
#
# "..matching of the reference identifier against the presented identifier
# is performed by comparing the set of domain name labels using a
# case-insensitive ASCII comparison, as clarified by [DNS-CASE] (e.g.,
# "WWW.Example.Com" would be lower-cased to "www.example.com" for
# comparison purposes)
assert_equal(true, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_san('DNS:*.example.com'), 'www.example.com'))
assert_equal(true, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_san('DNS:*.Example.COM'), 'www.example.com'))
assert_equal(true, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_san('DNS:*.example.com'), 'WWW.Example.COM'))
# 1. The client SHOULD NOT attempt to match a presented identifier in
# which the wildcard character comprises a label other than the
# left-most label (e.g., do not match bar.*.example.net).
assert_equal(false, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_san('DNS:www.*.com'), 'www.example.com'))
# 2. If the wildcard character is the only character of the left-most
# label in the presented identifier, the client SHOULD NOT compare
# against anything but the left-most label of the reference
# identifier (e.g., *.example.com would match foo.example.com but
# not bar.foo.example.com or example.com).
assert_equal(true, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_san('DNS:*.example.com'), 'foo.example.com'))
assert_equal(false, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_san('DNS:*.example.com'), 'bar.foo.example.com'))
# 3. The client MAY match a presented identifier in which the wildcard
# character is not the only character of the label (e.g.,
# baz*.example.net and *baz.example.net and b*z.example.net would
# be taken to match baz1.example.net and foobaz.example.net and
# buzz.example.net, respectively). ...
assert_equal(true, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_san('DNS:baz*.example.com'), 'baz1.example.com'))
assert_equal(true, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_san('DNS:*baz.example.com'), 'foobaz.example.com'))
assert_equal(true, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_san('DNS:b*z.example.com'), 'buzz.example.com'))
# Section 6.4.3 of RFC6125 states that client should NOT match identifier
# where wildcard is other than left-most label.
#
# Also implicitly mentions the wildcard character only in singular form,
# and discourages matching against more than one wildcard.
#
# See RFC 6125, section 7.2, subitem 2.
assert_equal(false, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_san('DNS:*b*.example.com'), 'abc.example.com'))
assert_equal(false, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_san('DNS:*b*.example.com'), 'ab.example.com'))
assert_equal(false, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_san('DNS:*b*.example.com'), 'bc.example.com'))
# ... However, the client SHOULD NOT
# attempt to match a presented identifier where the wildcard
# character is embedded within an A-label or U-label [IDNA-DEFS] of
# an internationalized domain name [IDNA-PROTO].
assert_equal(true, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_san('DNS:xn*.example.com'), 'xn1ca.example.com'))
# part of A-label
assert_equal(false, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_san('DNS:xn--*.example.com'), 'xn--1ca.example.com'))
# part of U-label
# dNSName in RFC5280 is an IA5String so U-label should NOT be allowed
# regardless of wildcard.
#
# See Section 7.2 of RFC 5280:
# IA5String is limited to the set of ASCII characters.
assert_equal(false, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_name('á*.example.com'), 'á1.example.com'))
end
def test_post_connection_check_wildcard_cn
assert_equal(true, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_name('*.example.com'), 'www.example.com'))
assert_equal(true, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_name('*.Example.COM'), 'www.example.com'))
assert_equal(true, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_name('*.example.com'), 'WWW.Example.COM'))
assert_equal(false, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_name('www.*.com'), 'www.example.com'))
assert_equal(true, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_name('*.example.com'), 'foo.example.com'))
assert_equal(false, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_name('*.example.com'), 'bar.foo.example.com'))
assert_equal(true, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_name('baz*.example.com'), 'baz1.example.com'))
assert_equal(true, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_name('*baz.example.com'), 'foobaz.example.com'))
assert_equal(true, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_name('b*z.example.com'), 'buzz.example.com'))
# Section 6.4.3 of RFC6125 states that client should NOT match identifier
# where wildcard is other than left-most label.
#
# Also implicitly mentions the wildcard character only in singular form,
# and discourages matching against more than one wildcard.
#
# See RFC 6125, section 7.2, subitem 2.
assert_equal(false, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_name('*b*.example.com'), 'abc.example.com'))
assert_equal(false, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_name('*b*.example.com'), 'ab.example.com'))
assert_equal(false, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_name('*b*.example.com'), 'bc.example.com'))
assert_equal(true, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_name('xn*.example.com'), 'xn1ca.example.com'))
assert_equal(false, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_name('xn--*.example.com'), 'xn--1ca.example.com'))
# part of U-label
# Subject in RFC5280 states case-insensitive ASCII comparison.
#
# See Section 7.2 of RFC 5280:
# IA5String is limited to the set of ASCII characters.
assert_equal(false, OpenSSL::SSL.verify_certificate_identity(
create_cert_with_name('á*.example.com'), 'á1.example.com'))
end
def create_cert_with_san(san)
ef = OpenSSL::X509::ExtensionFactory.new
cert = OpenSSL::X509::Certificate.new
cert.subject = OpenSSL::X509::Name.parse("/DC=some/DC=site/CN=Some Site")
ext = ef.create_ext('subjectAltName', san)
cert.add_extension(ext)
cert
end
def create_cert_with_name(name)
cert = OpenSSL::X509::Certificate.new
cert.subject = OpenSSL::X509::Name.new([['DC', 'some'], ['DC', 'site'], ['CN', name]])
cert
end
# Create NULL byte SAN certificate
def create_null_byte_SAN_certificate(critical = false)
ef = OpenSSL::X509::ExtensionFactory.new
cert = OpenSSL::X509::Certificate.new
cert.subject = OpenSSL::X509::Name.parse "/DC=some/DC=site/CN=Some Site"
ext = ef.create_ext('subjectAltName', 'DNS:placeholder,IP:192.168.7.1,IP:fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b', critical)
ext_asn1 = OpenSSL::ASN1.decode(ext.to_der)
san_list_der = ext_asn1.value.reduce(nil) { |memo,val| val.tag == 4 ? val.value : memo }
san_list_asn1 = OpenSSL::ASN1.decode(san_list_der)
san_list_asn1.value[0].value = "www.example.com\0.evil.com"
pos = critical ? 2 : 1
ext_asn1.value[pos].value = san_list_asn1.to_der
real_ext = OpenSSL::X509::Extension.new ext_asn1
cert.add_extension(real_ext)
cert
end
def test_tlsext_hostname
return unless OpenSSL::SSL::SSLSocket.instance_methods.include?(:hostname)
ctx_proc = Proc.new do |ctx, ssl|
foo_ctx = ctx.dup
ctx.servername_cb = Proc.new do |ssl2, hostname|
case hostname
when 'foo.example.com'
foo_ctx
when 'bar.example.com'
nil
else
raise "unknown hostname #{hostname.inspect}"
end
end
end
server_proc = Proc.new do |ctx, ssl|
readwrite_loop(ctx, ssl)
end
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true, :ctx_proc => ctx_proc, :server_proc => server_proc) do |server, port|
2.times do |i|
sock = TCPSocket.new("127.0.0.1", port)
ctx = OpenSSL::SSL::SSLContext.new
if defined?(OpenSSL::SSL::OP_NO_TICKET)
# disable RFC4507 support
ctx.options = OpenSSL::SSL::OP_NO_TICKET
end
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
ssl.sync_close = true
ssl.hostname = (i & 1 == 0) ? 'foo.example.com' : 'bar.example.com'
ssl.connect
str = "x" * 100 + "\n"
ssl.puts(str)
assert_equal(str, ssl.gets)
ssl.close
end
end
end
def test_multibyte_read_write
#German a umlaut
auml = [%w{ C3 A4 }.join('')].pack('H*')
auml.force_encoding(Encoding::UTF_8)
[10, 1000, 100000].each {|i|
str = nil
num_written = nil
server_proc = Proc.new {|ctx, ssl|
cmp = ssl.read
raw_size = cmp.size
cmp.force_encoding(Encoding::UTF_8)
assert_equal(str, cmp)
assert_equal(num_written, raw_size)
ssl.close
}
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true, :server_proc => server_proc){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true
ssl.connect
str = auml * i
num_written = ssl.write(str)
ssl.close
}
}
end
def test_unset_OP_ALL
ctx_proc = Proc.new { |ctx|
ctx.options = OpenSSL::SSL::OP_ALL & ~OpenSSL::SSL::OP_DONT_INSERT_EMPTY_FRAGMENTS
}
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true, :ctx_proc => ctx_proc){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true
ssl.connect
ssl.puts('hello')
assert_equal("hello\n", ssl.gets)
ssl.close
}
end
def test_invalid_shutdown_by_gc
assert_nothing_raised {
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|server, port|
10.times {
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
GC.start
ssl.connect
sock.close
}
}
}
end
def test_close_after_socket_close
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true
ssl.connect
sock.close
assert_nothing_raised do
ssl.close
end
}
end
end
end
|
arnab0073/idea
|
.rvm/rubies/ruby-1.9.3-p551/lib/ruby/gems/1.9.1/specifications/rake-0.9.2.2.gemspec
|
<gh_stars>0
Gem::Specification.new do |s|
s.name = "rake"
s.version = "0.9.2.2"
s.summary = "This rake is bundled with Ruby"
s.executables = ["rake"]
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/socket/test_tcp.rb
|
# frozen_string_literal: true
begin
require "socket"
require "test/unit"
rescue LoadError
end
class TestSocket_TCPSocket < Test::Unit::TestCase
def test_initialize_failure
# These addresses are chosen from TEST-NET-1, TEST-NET-2, and TEST-NET-3.
# [RFC 5737]
# They are chosen because probably they are not used as a host address.
# Anyway the addresses are used for bind() and should be failed.
# So no packets should be generated.
test_ip_addresses = [
'192.0.2.1', '192.0.2.42', # TEST-NET-1
'198.51.100.1', '198.51.100.42', # TEST-NET-2
'203.0.113.1', '203.0.113.42', # TEST-NET-3
]
begin
list = Socket.ip_address_list
rescue NotImplementedError
return
end
test_ip_addresses -= list.reject {|ai| !ai.ipv4? }.map {|ai| ai.ip_address }
if test_ip_addresses.empty?
return
end
client_addr = test_ip_addresses.first
client_port = 8000
server_addr = '127.0.0.1'
server_port = 80
begin
# Since client_addr is not an IP address of this host,
# bind() in TCPSocket.new should fail as EADDRNOTAVAIL.
t = TCPSocket.new(server_addr, server_port, client_addr, client_port)
flunk "expected SystemCallError"
rescue SystemCallError => e
assert_match "for \"#{client_addr}\" port #{client_port}", e.message
end
ensure
t.close if t && !t.closed?
end
def test_recvfrom
TCPServer.open("localhost", 0) {|svr|
th = Thread.new {
c = svr.accept
c.write "foo"
c.close
}
addr = svr.addr
TCPSocket.open(addr[3], addr[1]) {|sock|
assert_equal(["foo", nil], sock.recvfrom(0x10000))
}
th.join
}
end
def test_encoding
TCPServer.open("localhost", 0) {|svr|
th = Thread.new {
c = svr.accept
c.write "foo\r\n"
c.close
}
addr = svr.addr
TCPSocket.open(addr[3], addr[1]) {|sock|
assert_equal(true, sock.binmode?)
s = sock.gets
assert_equal("foo\r\n", s)
assert_equal(Encoding.find("ASCII-8BIT"), s.encoding)
}
th.join
}
end
def test_accept_nonblock
TCPServer.open("localhost", 0) {|svr|
assert_raise(IO::WaitReadable) { svr.accept_nonblock }
assert_equal :wait_readable, svr.accept_nonblock(exception: false)
assert_raise(IO::WaitReadable) { svr.accept_nonblock(exception: true) }
}
end
end if defined?(TCPSocket)
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/lib/logging/layouts/parseable.rb
|
require 'socket'
module Logging::Layouts
# Accessor for the Parseable layout.
#
def self.parseable
::Logging::Layouts::Parseable
end
# Factory for the Parseable layout using JSON formatting.
#
def self.json( *args )
::Logging::Layouts::Parseable.json(*args)
end
# Factory for the Parseable layout using YAML formatting.
#
def self.yaml( *args )
::Logging::Layouts::Parseable.yaml(*args)
end
# This layout will produce parseable log output in either JSON or YAML
# format. This makes it much easier for machines to parse log files and
# perform analysis on those logs.
#
# The information about the log event can be configured when the layout is
# created. Any or all of the following labels can be set as the _items_ to
# log:
#
# 'logger' Used to output the name of the logger that generated the
# log event.
# 'timestamp' Used to output the timestamp of the log event.
# 'level' Used to output the level of the log event.
# 'message' Used to output the application supplied message
# associated with the log event.
# 'file' Used to output the file name where the logging request
# was issued.
# 'line' Used to output the line number where the logging request
# was issued.
# 'method' Used to output the method name where the logging request
# was issued.
# 'hostname' Used to output the hostname
# 'pid' Used to output the process ID of the currently running
# program.
# 'millis' Used to output the number of milliseconds elapsed from
# the construction of the Layout until creation of the log
# event.
# 'thread_id' Used to output the object ID of the thread that generated
# the log event.
# 'thread' Used to output the name of the thread that generated the
# log event. Name can be specified using Thread.current[:name]
# notation. Output empty string if name not specified. This
# option helps to create more human readable output for
# multithread application logs.
#
# These items are supplied to the layout as an array of strings. The items
# 'file', 'line', and 'method' will only work if the Logger generating the
# events is configured to generate tracing information. If this is not the
# case these fields will always be empty.
#
# When configured to output log events in YAML format, each log message
# will be formatted as a hash in it's own YAML document. The hash keys are
# the name of the item, and the value is what you would expect it to be.
# Therefore, for the default set of times log message would appear as
# follows:
#
# ---
# timestamp: 2009-04-17T16:15:42
# level: INFO
# logger: Foo::Bar
# message: this is a log message
# ---
# timestamp: 2009-04-17T16:15:43
# level: ERROR
# logger: Foo
# message: <RuntimeError> Oooops!!
#
# The output order of the fields is not guaranteed to be the same as the
# order specified in the _items_ list. This is because Ruby hashes are not
# ordered by default (unless you're running this in Ruby 1.9).
#
# When configured to output log events in JSON format, each log message
# will be formatted as an object (in the JSON sense of the word) on it's
# own line in the log output. Therefore, to parse the output you must read
# it line by line and parse the individual objects. Taking the same
# example above the JSON output would be:
#
# {"timestamp":"2009-04-17T16:15:42","level":"INFO","logger":"Foo::Bar","message":"this is a log message"}
# {"timestamp":"2009-04-17T16:15:43","level":"ERROR","logger":"Foo","message":"<RuntimeError> Oooops!!"}
#
# The output order of the fields is guaranteed to be the same as the order
# specified in the _items_ list.
#
class Parseable < ::Logging::Layout
# :stopdoc:
# Arguments to sprintf keyed to directive letters
DIRECTIVE_TABLE = {
'logger' => 'event.logger'.freeze,
'timestamp' => 'iso8601_format(event.time)'.freeze,
'level' => '::Logging::LNAMES[event.level]'.freeze,
'message' => 'format_obj(event.data)'.freeze,
'file' => 'event.file'.freeze,
'line' => 'event.line'.freeze,
'method' => 'event.method'.freeze,
'hostname' => "'#{Socket.gethostname}'".freeze,
'pid' => 'Process.pid'.freeze,
'millis' => 'Integer((event.time-@created_at)*1000)'.freeze,
'thread_id' => 'Thread.current.object_id'.freeze,
'thread' => 'Thread.current[:name]'.freeze,
'mdc' => 'Logging::MappedDiagnosticContext.context'.freeze,
'ndc' => 'Logging::NestedDiagnosticContext.context'.freeze
}
# call-seq:
# Pattern.create_yaml_format_methods( layout )
#
# This method will create the +format+ method in the given Parseable
# _layout_ based on the configured items for the layout instance.
#
def self.create_yaml_format_method( layout )
code = "undef :format if method_defined? :format\n"
code << "def format( event )\nstr = {\n"
code << layout.items.map {|name|
"'#{name}' => #{Parseable::DIRECTIVE_TABLE[name]}"
}.join(",\n")
code << "\n}.to_yaml\nreturn str\nend\n"
(class << layout; self end).class_eval(code, __FILE__, __LINE__)
end
# call-seq:
# Pattern.create_json_format_methods( layout )
#
# This method will create the +format+ method in the given Parseable
# _layout_ based on the configured items for the layout instance.
#
def self.create_json_format_method( layout )
code = "undef :format if method_defined? :format\n"
code << "def format( event )\nh = {\n"
code << layout.items.map {|name|
"'#{name}' => #{Parseable::DIRECTIVE_TABLE[name]}"
}.join(",\n")
code << "\n}\nMultiJson.encode(h) << \"\\n\"\nend\n"
(class << layout; self end).class_eval(code, __FILE__, __LINE__)
end
# :startdoc:
# call-seq:
# Parseable.json( opts )
#
# Create a new Parseable layout that outputs log events using JSON style
# formatting. See the initializer documentation for available options.
#
def self.json( opts = {} )
opts[:style] = 'json'
new(opts)
end
# call-seq:
# Parseable.yaml( opts )
#
# Create a new Parseable layout that outputs log events using YAML style
# formatting. See the initializer documentation for available options.
#
def self.yaml( opts = {} )
opts[:style] = 'yaml'
new(opts)
end
# call-seq:
# Parseable.new( opts )
#
# Creates a new Parseable layout using the following options:
#
# :style => :json or :yaml
# :items => %w[timestamp level logger message]
#
def initialize( opts = {} )
super
@created_at = Time.now
@style = opts.fetch(:style, 'json').to_s.intern
self.items = opts.fetch(:items, %w[timestamp level logger message])
end
attr_reader :items
# call-seq:
# layout.items = %w[timestamp level logger message]
#
# Set the log event items that will be formatted by this layout. These
# items, and only these items, will appear in the log output.
#
def items=( ary )
@items = Array(ary).map {|name| name.to_s.downcase}
valid = DIRECTIVE_TABLE.keys
@items.each do |name|
raise ArgumentError, "unknown item - #{name.inspect}" unless valid.include? name
end
create_format_method
end
# Public: Take a given object and convert it into a format suitable for
# inclusion as a log message. The conversion allows the object to be more
# easily expressed in YAML or JSON form.
#
# If the object is an Exception, then this method will return a Hash
# containing the exception class name, message, and backtrace (if any).
#
# obj - The Object to format
#
# Returns the formatted Object.
#
def format_obj( obj )
case obj
when Exception
h = { :class => obj.class.name,
:message => obj.message }
h[:backtrace] = obj.backtrace if @backtrace && !obj.backtrace.nil?
h
when Time
iso8601_format(obj)
else
obj
end
end
private
# Call the appropriate class level create format method based on the
# style of this parseable layout.
#
def create_format_method
case @style
when :json; Parseable.create_json_format_method(self)
when :yaml; Parseable.create_yaml_format_method(self)
else raise ArgumentError, "unknown format style '#@style'" end
end
# Convert the given time _value_ into an ISO8601 formatted time string.
#
def iso8601_format( value )
str = value.strftime('%Y-%m-%dT%H:%M:%S')
str << ('.%06d' % value.usec)
offset = value.gmt_offset.abs
return str << 'Z' if offset == 0
offset = sprintf('%02d:%02d', offset / 3600, offset % 3600 / 60)
return str << (value.gmt_offset < 0 ? '-' : '+') << offset
end
end # Parseable
end # Logging::Layouts
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/lib/rubygems/path_support.rb
|
<gh_stars>1-10
##
# Gem::PathSupport facilitates the GEM_HOME and GEM_PATH environment settings
# to the rest of RubyGems.
#
class Gem::PathSupport
##
# The default system path for managing Gems.
attr_reader :home
##
# Array of paths to search for Gems.
attr_reader :path
##
#
# Constructor. Takes a single argument which is to be treated like a
# hashtable, or defaults to ENV, the system environment.
#
def initialize(env=ENV)
@env = env
# note 'env' vs 'ENV'...
@home = env["GEM_HOME"] || ENV["GEM_HOME"] || Gem.default_dir
if File::ALT_SEPARATOR then
@home = @home.gsub(File::ALT_SEPARATOR, File::SEPARATOR)
end
self.path = env["GEM_PATH"] || ENV["GEM_PATH"]
end
private
##
# Set the Gem home directory (as reported by Gem.dir).
def home=(home)
@home = home.to_s
end
##
# Set the Gem search path (as reported by Gem.path).
def path=(gpaths)
gem_path = [@home]
# FIX: I can't tell wtf this is doing.
gpaths ||= (ENV['GEM_PATH'] || "").empty? ? nil : ENV["GEM_PATH"]
if gpaths then
if gpaths.kind_of?(Array) then
gem_path.push(*gpaths)
else
gem_path.push(*gpaths.split(File::PATH_SEPARATOR))
end
if File::ALT_SEPARATOR then
gem_path.map! do |this_path|
this_path.gsub File::ALT_SEPARATOR, File::SEPARATOR
end
end
else
gem_path.push(*Gem.default_path)
gem_path << APPLE_GEM_HOME if defined?(APPLE_GEM_HOME)
end
@path = gem_path.uniq
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/coverage/extconf.rb
|
require 'mkmf'
$INCFLAGS << " -I$(topdir) -I$(top_srcdir)"
create_makefile('coverage')
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/iwidgets/sample/toolbar.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/iwidgets/sample/toolbar.rb<gh_stars>1-10
#!/usr/bin/env ruby
require 'tk'
require 'tkextlib/iwidgets'
##########################################
# icon images
editcopy22 = TkPhotoImage.new(:data=><<'EOD')
R0lGODlhFgAWAIUAAPwCBBQSFPz+/DQyNISChDw6PMzKzMTGxERGRIyKjFxa
XMTCvKSmpHR2dPz6/Pz29PTq3MS2rPz69MTCxFxWVHx6dJyWjNzSzPz27Pzy
7Pzu5PTm3NTKvIR+fJyGfHxuZHxqXNTCtPTq5PTi1PTezNS+rExOTFRORMyy
lPTaxOzWxOzSvNze3NTOxMy2nMyulMyqjAQCBAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAAWABYAAAbY
QIBwSCwahYGkUnk0BgTQ6IAQaBKfUWhBYKhaAU+CgXAQIAyChLeJzSIQhcH6
GFaM0QtGY5kstqEODw8QEQELAhJTc08KBBMEFBUWDRcBE1pca20SGBkaEBsc
AY5maFRIAgoLHRQRHh8gIQFlZnByqA8ZGSIQIyQjJQEmYgJ5p2ACrK4gJx4g
KIZZAgdeAQ4ZI9kjKSor0AwEjeAs1S0cHAslLi4vMDDRWeRIfEsxMeET4ATy
VoYLC5fizXEiAR84BeMG+pEm8EsAFhAjSlR4hR6fLxiF0AkCACH+aENyZWF0
ZWQgYnkgQk1QVG9HSUYgUHJvIHZlcnNpb24gMi41DQqpIERldmVsQ29yIDE5
OTcsMTk5OC4gQWxsIHJpZ2h0cyByZXNlcnZlZC4NCmh0dHA6Ly93d3cuZGV2
ZWxjb3IuY29tADs=
EOD
editcut22 = TkPhotoImage.new(:data=><<'EOD')
R0lGODlhFgAWAIMAAPwCBAQCBAwCBPz+/OTi5JyanOzq7DQyNGxqbAAAAAAA
AAAAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAAWABYAAARbEMhJq704gxBE
0Bf3cZo4kRJqBQNRfBucyudgvJS6VaxLzyMa6/bLiWA9HOg4VIIkL5vzuRkc
pkvRIIAorphJLzBW84WEuRZWp6uaT7J2Sh1Hit3OY/ZO7WvsEQAh/mhDcmVh
dGVkIGJ5IEJNUFRvR0lGIFBybyB2ZXJzaW9uIDIuNQ0KqSBEZXZlbENvciAx
OTk3LDE5OTguIEFsbCByaWdodHMgcmVzZXJ2ZWQuDQpodHRwOi8vd3d3LmRl
dmVsY29yLmNvbQA7
EOD
editpaste22 = TkPhotoImage.new(:data=><<'EOD')
R0lGODlhFgAWAIYAAPwCBBQWFDw6FHRuFGRaBFxSBAQCBAQKBCQiBIx6HPz6
/NTOfKyiXDQuFOTm5Pz+/Ozu7PTq5Pz63PTyxNTOjKSeRExGLMTGxMzKzNTS
1NTW1Dw2NKSmpKyqrKSipJyanNzWlLy6ZLSuVIx6FISChIyKhJSSlCQiJLS2
tDw6NDQyNCQiFCQmHBQSDGRiZHRydGxubHx6dGxqbFxeXGRmZFxaXCwuLOzq
7KyurHx+fDwmFEQuFCweFCQWDBQODBwaHBweHKSinJSWlOTi5JyepHR2dDw6
PBQSFNze3ERGRIyKjIyOjISGhPz29Pzy7MS2rMzOzFRWVHx2dHxybDQiFPz2
7Pzu5PTq3PTm1NTCtJyGdHxuZHxqXPzq3PTaxNS6pFxWVFRKRNS2nPTi1PTS
tNSulNzOxNSynMymhAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAAA
LAAAAAAWABYAAAf/gACCgwABAgMEBYSLggaOjgcICQoLDA2Pj4MGDg8QEZ4F
D<KEY>fCQ8gCyEiFSMWJCUkJieNEB4dKB4pKissK8wr
LS4vMDHBAAYQHx8dFx0fJDIzNDU0M+IyHzaNNyg43Ng5Ojs7Ojw9Pj9AMkCN
DiZB/h9CSOx4QLCgihItqBkYgqIDESElitAYWJCgkQcXjjRCgi1Ihw4BB5LA
QOLCgyQYHihpUU3DBw5ElpAgAYNixSRJjKjQaECDCRPZPDB5IbIGSQwKLnh4
wbInLA4kmJB4oaPiAwVNnER40hRK1BIAaVatUZJEFCkmpmjgCeWDCalFe4q4
oFKwSRUrEa5gycLzwq8lUnPQ4PEgSpYcUZ5o2cIlS1O/JHLEDdfjQZMIVrpg
weLFy5e+M6WSmBGlxYMYYBRzCaOFi5imHWBIfOEiShLTVjaP6eyFTBmN1TA5
O<KEY>
O<KEY>
LmNvbQA7
EOD
editdelete22 = TkPhotoImage.new(:data=><<'EOD')
R0lGODlhFgAWAIYAAASC/FRSVExKTERCRDw6PDQyNCwuLBweHBwaHAwODAwK
DAQCBExOTNze3NTW1MTGxLS2tJyanPz+/Ozu7BQSFCwqLDw+POTi5PTu7MzK
xIR+fCQmJPz6/Oze1NTGvPz69Pzy7Pz29LyyrPy+vPyupPTm1BQWFIQCBPwC
BMS6rPzSzNTOxPTi1NS+rPTezNzOxPTizOzWxMy2pOzaxMy2nPTaxOzOtMyy
nOzSvMyqjPx+fOzGpMSihPTq3OzKrOTCpNzKxNTCtAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAAA
LAAAAAAWABYAAAf8gACCAQIDBAUGBwgJCgsLgpCRAAwNlZYODxALEY+SkAMN
EqKjEw0UD5yegqCjrRMVEqidkgWhraMWF7GptLa3EgEWFRSOnhW+vxgZEBqz
kBvItxwdHryRCNGjHyAhHSLOgtgSI60c2yQjJd+eJqEnKK0hJCgnJSngAO0S
F+8qEvL0VrBogW+BLX4oVKgIyMIFQU8KfDV4R+8FDBcxZBREthAFiRIsOsyg
sVEUh4Un3pGoUcPGjZInK65QicPlxg8oX5RwqNJGjo0hdJwQ6EIkjRM6dvDY
CKIHSBc1Ztjw4eOH0oIrsgIJEqSFDBo0cuTgsdSTo7No0xYTZCcQACH+aENy
ZWF0ZWQgYnkgQk1QVG9HSUYgUHJvIHZlcnNpb24gMi41DQqpIERldmVsQ29y
IDE5OTcsMTk5OC4gQWxsIHJpZ2h0cyByZXNlcnZlZC4NCmh0dHA6Ly93d3cu
ZGV2ZWxjb3IuY29tADs=
EOD
text22 = TkPhotoImage.new(:data=><<'EOD')
R0lGODlhFgAWAIQAAPwCBAQCBBwaHAwKDBQSFLy+vLS2tJSWlBQWFKyqrFRS
VCwqLDQyNNTS1GxqbFxaXJyanIyOjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAAWABYAAAVcICCOZGmK
QSoMaZsShBsQBdAapHvgaIDUqUPJlRjSbAoT0fRDKgODRbF0PLUYjZO2F2Bs
t9evNix+dsvDlGKK5jraudQb7qbX6a2HEJ+ycyF+LRE8ZTI+fX5oGCEAIf5o
Q3JlYXRlZCBieSBCTVBUb0dJRiBQcm8gdmVyc2lvbiAyLjUNCqkgRGV2ZWxD
b3IgMTk5NywxOTk4LiBBbGwgcmlnaHRzIHJlc2VydmVkLg0KaHR0cDovL3d3
dy5kZXZlbGNvci5jb20AOw==
EOD
##########################################
bmp_dir = File.join(File.dirname(File.expand_path(__FILE__)),
'../catalog_demo/images')
##########################################
status_var = TkVariable.new
radio_var = TkVariable.new
check_var1 = TkVariable.new
check_var2 = TkVariable.new
tb = Tk::Iwidgets::Toolbar.new(:helpvariable=>status_var)
##########################################
tb.add(:button, :helpstr=>'Copy It', :image=>editcopy22,
:balloonstr=>'Copy', :command=>proc{puts 'Copy It'})
tb.add(:button, :helpstr=>'Cut It', :image=>editcut22,
:balloonstr=>'Cut', :command=>proc{puts 'Cut It'})
tb.add(:button, :helpstr=>'Paste It', :image=>editpaste22,
:balloonstr=>'Paste', :command=>proc{puts 'Paste It'})
tb.add(:button, :helpstr=>'Delete It', :image=>editdelete22,
:balloonstr=>'Delete', :command=>proc{puts 'Delete It'})
#--------------------------------
tb.add(:frame, :borderwidth=>1, :width=>10, :height=>10)
#--------------------------------
tb.add(:radiobutton, :variable=>radio_var, :value=>'Box',
:bitmap=>"@#{bmp_dir}/box.xbm",
:helpstr=>'Radio Button #1', :balloonstr=>'Radio',
:command=>proc{puts 'Radio Button "Box"'})
tb.add(:radiobutton, :variable=>radio_var, :value=>'Line',
:bitmap=>"@#{bmp_dir}/line.xbm",
:helpstr=>'Radio Button #2', :balloonstr=>'Radio',
:command=>proc{puts 'Radio Button "Line"'})
tb.add(:radiobutton, :variable=>radio_var, :value=>'Oval',
:bitmap=>"@#{bmp_dir}/oval.xbm",
:helpstr=>'Radio Button #3', :balloonstr=>'Radio',
:command=>proc{puts 'Radio Button "Oval"'})
#--------------------------------
tb.add(:frame, :borderwidth=>1, :width=>10, :height=>10)
#--------------------------------
tb.add(:checkbutton, :variable=>check_var1, :onvalue=>'yes', :offvalue=>'no',
:image=>text22, :command=>proc{puts 'Checkbutton 1'})
tb.add(:checkbutton, :variable=>check_var2, :onvalue=>'yes', :offvalue=>'no',
:bitmap=>"@#{bmp_dir}/points.xbm", :command=>proc{puts 'Checkbutton 2'})
tb.pack(:side=>:top, :anchor=>:nw)
Tk.mainloop
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/test_tmpdir.rb
|
<gh_stars>10-100
# frozen_string_literal: false
require 'test/unit'
require 'tmpdir'
class TestTmpdir < Test::Unit::TestCase
def test_tmpdir_modifiable
tmpdir = Dir.tmpdir
assert_equal(false, tmpdir.frozen?)
tmpdir_org = tmpdir.dup
tmpdir << "foo"
assert_equal(tmpdir_org, Dir.tmpdir)
end
def test_tmpdir_modifiable_safe
Thread.new {
$SAFE = 1
tmpdir = Dir.tmpdir
assert_equal(false, tmpdir.frozen?)
tmpdir_org = tmpdir.dup
tmpdir << "foo"
assert_equal(tmpdir_org, Dir.tmpdir)
}.join
end
def test_world_writable
skip "no meaning on this platform" if /mswin|mingw/ =~ RUBY_PLATFORM
Dir.mktmpdir do |tmpdir|
# ToDo: fix for parallel test
olddir, ENV["TMPDIR"] = ENV["TMPDIR"], tmpdir
begin
assert_equal(tmpdir, Dir.tmpdir)
File.chmod(0777, tmpdir)
assert_not_equal(tmpdir, Dir.tmpdir)
File.chmod(01777, tmpdir)
assert_equal(tmpdir, Dir.tmpdir)
ensure
ENV["TMPDIR"] = olddir
end
end
end
def test_no_homedir
bug7547 = '[ruby-core:50793]'
home, ENV["HOME"] = ENV["HOME"], nil
dir = assert_nothing_raised(bug7547) do
break Dir.mktmpdir("~")
end
assert_match(/\A~/, File.basename(dir), bug7547)
ensure
ENV["HOME"] = home
Dir.rmdir(dir) if dir
end
def test_mktmpdir_nil
Dir.mktmpdir(nil) {|d|
assert_kind_of(String, d)
}
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/tkHTML/ss.rb
|
#!/usr/bin/env ruby
#
# This script implements the "ss" application. "ss" implements
# a presentation slide-show based on HTML slides.
#
require 'tk'
require 'tkextlib/tkHTML'
file = ARGV[0]
class TkHTML_File_Viewer
include TkComm
# These are images to use with the actual image specified in a
# "<img>" markup can't be found.
#
@@biggray = TkPhotoImage.new(:data=><<'EOD')
R0lGODdhPAA+APAAALi4uAAAACwAAAAAPAA+AAACQISPqcvtD6OctNqLs968+w+G4kiW5omm
6sq27gvH8kzX9o3n+s73/g8MCofEovGITCqXzKbzCY1Kp9Sq9YrNFgsAO///
EOD
@@smgray = TkPhotoImage.new(:data=><<'EOD')
R0lGODdhOAAYAPAAALi4uAAAACwAAAAAOAAYAAACI4SPqcvtD6OctNqLs968+w+G4kiW5omm
6sq27gvH8kzX9m0VADv/
EOD
def initialize(file = nil)
@root = TkRoot.new(:title=>'HTML File Viewer', :iconname=>'HV')
@fswin = nil
@html = nil
@html_fs = nil
@hotkey = {}
@applet_arg = TkVarAccess.new_hash('AppletArg')
@images = {}
@old_imgs = {}
@big_imgs = {}
@last_dir = Dir.pwd
@last_file = ''
@key_block = false
Tk::HTML_Widget::ClippingWindow.bind('1',
proc{|w, ksym| key_press(w, ksym)},
'%W Down')
Tk::HTML_Widget::ClippingWindow.bind('3',
proc{|w, ksym| key_press(w, ksym)},
'%W Up')
Tk::HTML_Widget::ClippingWindow.bind('2',
proc{|w, ksym| key_press(w, ksym)},
'%W Down')
Tk::HTML_Widget::ClippingWindow.bind('KeyPress',
proc{|w, ksym| key_press(w, ksym)},
'%W %K')
############################################
#
# Build the half-size view of the page
#
menu_spec = [
[['File', 0],
['Open', proc{sel_load()}, 0],
['Full Screen', proc{fullscreen()}, 0],
['Refresh', proc{refresh()}, 0],
'---',
['Exit', proc{exit}, 1]]
]
mbar = @root.add_menubar(menu_spec)
@html = Tk::HTML_Widget.new(:width=>512, :height=>384,
:padx=>5, :pady=>9,
:formcommand=>proc{|*args| form_cmd(*args)},
:imagecommand=>proc{|*args|
image_cmd(1, *args)
},
:scriptcommand=>proc{|*args|
script_cmd(*args)
},
:appletcommand=>proc{|*args|
applet_cmd(*args)
},
:hyperlinkcommand=>proc{|*args|
hyper_cmd(*args)
},
:fontcommand=>proc{|*args|
pick_font(*args)
},
:appletcommand=>proc{|*args|
run_applet('small', *args)
},
:bg=>'white', :tablerelief=>:raised)
@html.token_handler('meta', proc{|*args| meta(@html, *args)})
vscr = @html.yscrollbar(TkScrollbar.new)
hscr = @html.xscrollbar(TkScrollbar.new)
Tk.grid(@html, vscr, :sticky=>:news)
Tk.grid(hscr, :sticky=>:ew)
@root.grid_columnconfigure(0, :weight=>1)
@root.grid_columnconfigure(1, :weight=>0)
@root.grid_rowconfigure(0, :weight=>1)
@root.grid_rowconfigure(1, :weight=>0)
############################################
@html.clipwin.focus
# If an arguent was specified, read it into the HTML widget.
#
Tk.update
if file && file != ""
load_file(file)
end
end
#
# A font chooser routine.
#
# html[:fontcommand] = pick_font
def pick_font(size, attrs)
# puts "FontCmd: #{size} #{attrs}"
[ ((attrs =~ /fixed/)? 'courier': 'charter'),
(12 * (1.2**(size.to_f - 4.0))).to_i,
((attrs =~ /italic/)? 'italic': 'roman'),
((attrs =~ /bold/)? 'bold': 'normal') ].join(' ')
end
# This routine is called to pick fonts for the fullscreen view.
#
def pick_font_fs(size, attrs)
baseFontSize = 24
# puts "FontCmd: #{size} #{attrs}"
[ ((attrs =~ /fixed/)? 'courier': 'charter'),
(baseFontSize * (1.2**(size.to_f - 4.0))).to_i,
((attrs =~ /italic/)? 'italic': 'roman'),
((attrs =~ /bold/)? 'bold': 'normal') ].join(' ')
end
#
#
def hyper_cmd(*args)
puts "HyperlinkCommand: #{args.inspect}"
end
# This routine is called to run an applet
#
def run_applet(size, w, arglist)
applet_arg.value = Hash[*simplelist(arglist)]
return unless @applet_arg.key?('src')
src = @html.remove(@applet_arg['src'])
@applet_arg['window'] = w
@applet_arg['fontsize'] = size
begin
Tk.load_tclscript(src)
rescue => e
puts "Applet error: #{e.message}"
end
end
#
#
def form_cmd(n, cmd, *args)
# p [n, cmd, *args]
end
#
#
def move_big_image(b)
return unless @big_imgs.key?(b)
b.copy(@big_imgs[b])
@big_imgs[b].delete
@big_imgs.delete(b)
end
def image_cmd(hs, *args)
fn = args[0]
if @old_imgs.key?(fn)
return (@images[fn] = @old_imgs.delete(fn))
end
begin
img = TkPhotoImage.new(:file=>fn)
rescue
return ((hs)? @@smallgray: @@biggray)
end
if hs
img2 = TkPhotoImage.new
img2.copy(img, :subsample=>[2,2])
img.delete
img = img2
end
if img.width * img.height > 20000
b = TkPhotoImage.new(:width=>img.width, :height=>img.height)
@big_imgs[b] = img
img = b
Tk.after_idle(proc{ move_big_image(b) })
end
@images[fn] = img
img
end
#
# This routine is called for every <SCRIPT> markup
#
def script_cmd(*args)
# puts "ScriptCmd: #{args.inspect}"
end
# This routine is called for every <APPLET> markup
#
def applet_cmd(w, arglist)
# puts "AppletCmd: w=#{w} arglist=#{arglist}"
#TkLabel.new(w, :text=>"The Applet #{w}", :bd=>2, :relief=>raised)
end
# This binding fires when there is a click on a hyperlink
#
def href_binding(w, x, y)
lst = w.href(x, y)
unless lst.empty?
process_url(lst)
end
end
#
#
def sel_load
filetypes = [
['Html Files', ['.html', '.htm']],
['All Files', '*']
]
f = Tk.getOpenFile(:initialdir=>@last_dir, :filetypes=>filetypes)
if f != ''
load_file(f)
@last_dir = File.dirname(f)
end
end
# Clear the screen.
#
def clear_screen
if @html_fs && @html_fs.exist?
w = @html_fs
else
w = @html
end
w.clear
@old_imgs.clear
@big_imgs.clear
@hotkey.clear
@images.each{|k, v| @old_imgs[k] = v }
@images.clear
end
# Read a file
#
def read_file(name)
begin
fp = open(name, 'r')
ret = fp.read(File.size(name))
rescue
ret = nil
fp = nil
Tk.messageBox(:icon=>'error', :message=>"fail to open '#{name}'",
:type=>:ok)
ensure
fp.close if fp
end
ret
end
# Process the given URL
#
def process_url(url)
case url[0]
when /^file:/
load_file(url[0][5..-1])
when /^exec:/
Tk.ip_eval(url[0][5..-1].tr('\\', ' '))
else
load_file(url[0])
end
end
# Load a file into the HTML widget
#
def load_file(name)
return unless (doc = read_file(name))
clear_screen()
@last_file = name
if @html_fs && @html_fs.exist?
w = @html_fs
else
w = @html
end
w.configure(:base=>name)
w.parse(doc)
w.configure(:cursor=>'top_left_arrow')
@old_imgs.clear
end
# Refresh the current file.
#
def refresh(*args)
load_file(@last_file) if @last_file
end
# This routine is called whenever a "<meta>" markup is seen.
#
def meta(w, tag, alist)
v = Hash[*simplelist(alist)]
if v.key?('key') && v.key?('href')
@hotkey[v['key']] = w.resolve(v['href'])
end
if v.key?('next')
@hotkey['Down'] =v['next']
end
if v.key?('prev')
@hotkey['Up'] =v['prev']
end
if v.key?('other')
@hotkey['o'] =v['other']
end
end
# Go from full-screen mode back to window mode.
#
def fullscreen_off
@fswin.destroy
@root.deiconify
Tk.update
@root.raise
@html.clipwin.focus
clear_screen()
@old_imgs.clear
refresh()
end
# Go from window mode to full-screen mode.
#
def fullscreen
if @fswin && @fswin.exist?
@fswin.deiconify
Tk.update
@fswin.raise
return
end
width = @root.winfo_screenwidth
height = @root.winfo_screenheight
@fswin = TkToplevel.new(:overrideredirect=>true,
:geometry=>"#{width}x#{height}+0+0")
@html_fs = Tk::HTML_Widget.new(@fswin, :padx=>5, :pady=>9,
:formcommand=>proc{|*args|
form_cmd(*args)
},
:imagecommand=>proc{|*args|
image_cmd(0, *args)
},
:scriptcommand=>proc{|*args|
script_cmd(*args)
},
:appletcommand=>proc{|*args|
applet_cmd(*args)
},
:hyperlinkcommand=>proc{|*args|
hyper_cmd(*args)
},
:appletcommand=>proc{|*args|
run_applet('big', *args)
},
:fontcommand=>proc{|*args|
pick_font_fs(*args)
},
:bg=>'white', :tablerelief=>:raised,
:cursor=>:tcross) {
pack(:fill=>:both, :expand=>true)
token_handler('meta', proc{|*args| meta(self, *args)})
}
clear_screen()
@old_imgs.clear
refresh()
Tk.update
@html_fs.clipwin.focus
end
#
#
def key_press(w, keysym)
return if @key_block
@key_block = true
Tk.after(250, proc{@key_block = false})
if @hotkey.key?(keysym)
process_url(@hotkey[keysym])
end
case keysym
when 'Escape'
if @fswin && @fswin.exist?
fullscreen_off()
else
fullscreen()
end
end
end
end
############################################
TkHTML_File_Viewer.new(file)
Tk.mainloop
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tk/winpkg.rb
|
#
# tk/winpkg.rb : methods for Tcl/Tk packages for Microsoft Windows
# 2000/11/22 by <NAME> <<EMAIL>>
#
# ATTENTION !!
# This is NOT TESTED. Because I have no test-environment.
#
require 'tk'
module Tk::WinDDE
end
#TkWinDDE = Tk::WinDDE
#Tk.__set_toplevel_aliases__(:Tk, Tk::WinDDE, :TkWinDDE)
Tk.__set_loaded_toplevel_aliases__('tk/winpkg.rb', :Tk, Tk::WinDDE, :TkWinDDE)
module Tk::WinDDE
extend Tk
extend Tk::WinDDE
TkCommandNames = ['dde'.freeze].freeze
PACKAGE_NAME = 'dde'.freeze
def self.package_name
PACKAGE_NAME
end
if self.const_defined? :FORCE_VERSION
tk_call_without_enc('package', 'require', 'dde', FORCE_VERSION)
else
tk_call_without_enc('package', 'require', 'dde')
end
#def servername(topic=None)
# tk_call('dde', 'servername', topic)
#end
def servername(*args)
if args.size == 0
tk_call('dde', 'servername')
else
if args[-1].kind_of?(Hash) # dde 1.2 +
keys = _symbolkey2str(args.pop)
force = (keys.delete('force'))? '-force': None
exact = (keys.delete('exact'))? '-exact': None
if keys.size == 0
tk_call('dde', 'servername', force, exact)
elsif args.size == 0
tk_call('dde', 'servername', force, exact, *hash_kv(keys))
else
tk_call('dde', 'servername', force, exact,
*((hash_kv(keys) << '--') + args))
end
else
tk_call('dde', 'servername', *args)
end
end
end
def execute(service, topic, data)
tk_call('dde', 'execute', service, topic, data)
end
def async_execute(service, topic, data)
tk_call('dde', '-async', 'execute', service, topic, data)
end
def poke(service, topic, item, data)
tk_call('dde', 'poke', service, topic, item, data)
end
def request(service, topic, item)
tk_call('dde', 'request', service, topic, item)
end
def binary_request(service, topic, item)
tk_call('dde', 'request', '-binary', service, topic, item)
end
def services(service, topic)
tk_call('dde', 'services', service, topic)
end
def eval(topic, cmd, *args)
tk_call('dde', 'eval', topic, cmd, *args)
end
def async_eval(topic, cmd, *args)
tk_call('dde', 'eval', -async, topic, cmd, *args)
end
module_function :servername, :execute, :async_execute,
:poke, :request, :services, :eval
end
module Tk::WinRegistry
end
#TkWinRegistry = Tk::WinRegistry
#Tk.__set_toplevel_aliases__(:Tk, Tk::WinRegistry, :TkWinRegistry)
Tk.__set_loaded_toplevel_aliases__('tk/winpkg.rb', :Tk, Tk::WinRegistry,
:TkWinRegistry)
module Tk::WinRegistry
extend Tk
extend Tk::WinRegistry
TkCommandNames = ['registry'.freeze].freeze
if self.const_defined? :FORCE_VERSION
tk_call('package', 'require', 'registry', FORCE_VERSION)
else
tk_call('package', 'require', 'registry')
end
def broadcast(keynam, timeout=nil)
if timeout
tk_call('registry', 'broadcast', keynam, '-timeout', timeout)
else
tk_call('registry', 'broadcast', keynam)
end
end
def delete(keynam, valnam=None)
tk_call('registry', 'delete', keynam, valnam)
end
def get(keynam, valnam)
tk_call('registry', 'get', keynam, valnam)
end
def keys(keynam, pattern=nil)
lst = tk_split_simplelist(tk_call('registry', 'keys', keynam))
if pattern
lst.find_all{|key| key =~ pattern}
else
lst
end
end
def set(keynam, valnam=None, data=None, dattype=None)
tk_call('registry', 'set', keynam, valnam, data, dattype)
end
def type(keynam, valnam)
tk_call('registry', 'type', keynam, valnam)
end
def values(keynam, pattern=nil)
lst = tk_split_simplelist(tk_call('registry', 'values', keynam))
if pattern
lst.find_all{|val| val =~ pattern}
else
lst
end
end
module_function :delete, :get, :keys, :set, :type, :values
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/gssapi-1.2.0/lib/gssapi.rb
|
=begin
Copyright © 2010 <NAME> <<EMAIL>>
Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
=end
require 'ffi'
module GSSAPI
module LibGSSAPI
extend FFI::Library
FFI::add_typedef(:uint32, :OM_uint32)
GSSAPI_LIB_TYPE = :mit unless defined?(GSSAPI_LIB_TYPE)
end
end
require 'gssapi/exceptions'
require 'gssapi/lib_gssapi'
require 'gssapi/simple'
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/test/benchmark.rb
|
<filename>.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/test/benchmark.rb
require 'rubygems'
libpath = File.expand_path('../../lib', __FILE__)
$:.unshift libpath
require 'logging'
begin
gem 'log4r'
require 'log4r'
$log4r = true
rescue LoadError
$log4r = false
end
require 'benchmark'
require 'logger'
module Logging
class Benchmark
def run
this_many = 300_000
pattern = Logging.layouts.pattern \
:pattern => '%.1l, [%d #%p] %5l -- %c: %m\n',
:date_pattern => "%Y-%m-%dT%H:%M:%S.%s"
Logging.appenders.string_io('sio', :layout => pattern)
sio = Logging.appenders['sio'].sio
logging = ::Logging.logger['benchmark']
logging.level = :warn
logging.appenders = 'sio'
logger = ::Logger.new sio
logger.level = ::Logger::WARN
log4r = if $log4r
l4r = ::Log4r::Logger.new('benchmark')
l4r.level = ::Log4r::WARN
l4r.add ::Log4r::IOOutputter.new(
'benchmark', sio,
:formatter => ::Log4r::PatternFormatter.new(
:pattern => "%.1l, [%d #\#{Process.pid}] %5l : %M\n",
:date_pattern => "%Y-%m-%dT%H:%M:%S.%6N"
)
)
l4r
end
puts "== Debug (not logged) ==\n"
::Benchmark.bm(10) do |bm|
bm.report('Logging:') {this_many.times {logging.debug 'not logged'}}
bm.report('Logger:') {this_many.times {logger.debug 'not logged'}}
bm.report('Log4r:') {this_many.times {log4r.debug 'not logged'}} if log4r
end
puts "\n== Warn (logged) ==\n"
::Benchmark.bm(10) do |bm|
sio.seek 0
bm.report('Logging:') {this_many.times {logging.warn 'logged'}}
sio.seek 0
bm.report('Logger:') {this_many.times {logger.warn 'logged'}}
sio.seek 0
bm.report('Log4r:') {this_many.times {log4r.warn 'logged'}} if log4r
end
puts "\n== Concat ==\n"
::Benchmark.bm(10) do |bm|
sio.seek 0
bm.report('Logging:') {this_many.times {logging << 'logged'}}
sio.seek 0
bm.report('Logger:') {this_many.times {logger << 'logged'}}
puts "Log4r: not supported" if log4r
end
write_size = 250
auto_flushing_size = 500
logging_async = ::Logging.logger['AsyncFile']
logging_async.level = :info
logging_async.appenders = Logging.appenders.file \
'benchmark_async.log',
:layout => pattern,
:write_size => write_size,
:auto_flushing => auto_flushing_size,
:async => true
logging_sync = ::Logging.logger['SyncFile']
logging_sync.level = :info
logging_sync.appenders = Logging.appenders.file \
'benchmark_sync.log',
:layout => pattern,
:write_size => write_size,
:auto_flushing => auto_flushing_size,
:async => false
puts "\n== File ==\n"
::Benchmark.bm(20) do |bm|
bm.report('Logging (Async):') {this_many.times { |n| logging_async.info "Iteration #{n}"}}
bm.report('Logging (Sync):') {this_many.times { |n| logging_sync.info "Iteration #{n}"}}
end
File.delete('benchmark_async.log')
File.delete('benchmark_sync.log')
end
end
end
if __FILE__ == $0
bm = ::Logging::Benchmark.new
bm.run
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/blt/spline.rb
|
#
# tkextlib/blt/spline.rb
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tkextlib/blt.rb'
module Tk::BLT
module Spline
extend TkCore
TkCommandNames = ['::blt::spline'.freeze].freeze
def self.natural(x, y, sx, sy)
tk_call('::blt::spline', 'natural', x, y, sx, sy)
end
def self.quadratic(x, y, sx, sy)
tk_call('::blt::spline', 'quadratic', x, y, sx, sy)
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/demos-en/dialog2.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/sample/demos-en/dialog2.rb
#
# a dialog box with a global grab (called by 'widget')
#
class TkDialog_Demo2 < TkDialog
###############
private
###############
def title
"Dialog with global grab"
end
def message
"This dialog box uses a global grab, so it prevents you from interacting with anything on your display until you invoke one of the buttons below. Global grabs are almost always a bad idea; don't use them unless you're truly desperate."
end
def bitmap
'info'
end
def default_button
0
end
def buttons
["OK", "Cancel", "Show Code"]
end
end
ret = TkDialog_Demo2.new('message_config'=>{'wraplength'=>'4i'},
'prev_command'=>proc{|dialog|
Tk.after 100, proc{dialog.grab('global')}
}).value
case ret
when 0
print "\You pressed OK\n"
when 1
print "You pressed Cancel\n"
when 2
showCode 'dialog2'
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/win32/extconf.rb
|
# frozen_string_literal: false
if compiled?('fiddle') and $mswin||$mingw||$cygwin
create_makefile('win32')
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/tool/insns2vm.rb
|
#!ruby
require 'optparse'
Version = %w$Revision: 11626 $[1..-1]
require "#{File.join(File.dirname(__FILE__), 'instruction')}"
if $0 == __FILE__
opts = ARGV.options
maker = RubyVM::SourceCodeGenerator.def_options(opts)
files = opts.parse!
generator = maker.call
generator.generate(files)
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/gyoku-1.3.1/spec/gyoku/xml_key_spec.rb
|
<reponame>arnab0073/idea
require "spec_helper"
describe Gyoku::XMLKey do
describe ".create" do
it "removes exclamation marks from the end of a String" do
expect(create("value!")).to eq("value")
end
it "removes forward slashes from the end of a String" do
expect(create("self-closing/")).to eq("self-closing")
end
it "does not convert snake_case Strings" do
expect(create("lower_camel_case")).to eq("lower_camel_case")
end
it "converts snake_case Symbols to lowerCamelCase Strings" do
expect(create(:lower_camel_case)).to eq("lowerCamelCase")
expect(create(:lower_camel_case!)).to eq("lowerCamelCase")
end
context "when the converter option is set to camelcase" do
it "should replace / with ::, and turn snake case into camel case" do
input = "hello_world_bob/how_are_you|there:foo^bar".to_sym
expected_output = "HelloWorldBob::HowAreYou|there:foo^bar"
expect(create(input, {key_converter: :camelcase})).to eq(expected_output)
end
end
context "with key_converter" do
it "accepts lambda converters" do
expect(create(:some_text, {key_converter: lambda { |k| k.reverse }})).to eq("txet_emos")
end
it "convert symbol to the specified type" do
expect(create(:some_text, {key_converter: :camelcase})).to eq("SomeText")
expect(create(:some_text, {key_converter: :upcase})).to eq("SOME_TEXT")
expect(create(:some_text, {key_converter: :none})).to eq("some_text")
end
it "when key_to_convert is defined, convert only this key" do
options = {key_converter: :camelcase, key_to_convert: 'somekey'}
expect(create(:some_key, options)).to eq("someKey")
options = {key_converter: :camelcase, key_to_convert: 'some_key'}
expect(create(:some_key, options)).to eq("SomeKey")
end
it "when except is defined, dont convert this key" do
options = {key_converter: :camelcase, except: 'some_key'}
expect(create(:some_key, options)).to eq("someKey")
end
end
context "with :element_form_default set to :qualified and a :namespace" do
it "adds the given namespace" do
key = create :qualify, :element_form_default => :qualified, :namespace => :v1
expect(key).to eq("v1:qualify")
end
it "does not add the given namespace if the key starts with a colon" do
key = create ":qualify", :element_form_default => :qualified, :namespace => :v1
expect(key).to eq("qualify")
end
it "adds a given :namespace after converting the key" do
key = create :username, :element_form_default => :qualified, :namespace => :v1, :key_converter => :camelcase
expect(key).to eq("v1:Username")
end
end
end
def create(key, options = {})
Gyoku::XMLKey.create(key, options)
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/setup.rb
|
#
# setup.rb -- setup script before using Tk extension libraries
#
# If you need some setup operations for Tk extensions (for example,
# modify the dynamic library path) required, please write the setup
# operations in this file. This file is required at the last of
# "require 'tk'".
#
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/examples/custom_log_levels.rb
|
<gh_stars>1000+
# :stopdoc:
#
# It's useful to define custom log levels that denote success, or otherwise
# meaningful events that happen to not be negative (more than 50% of the
# levels are given to warn, error, fail - quite a pessimistic view of one's
# application's chances of success, no? ;-) )
#
# Here, we define two new levels, 'happy' and 'success' and make them soothing
# colours.
#
require 'logging'
# https://github.com/TwP/logging/blob/master/lib/logging.rb#L250-285
# The levels run from lowest level to highest level.
Logging.init :debug, :info, :happy, :warn, :success, :error, :fatal
Logging.color_scheme( 'soothing_ish',
:levels => {
:info => :cyan,
:happy => :green,
:warn => :yellow,
:success => [:blue],
:error => :red,
:fatal => [:white, :on_red]
},
:date => :cyan,
:logger => :cyan,
:message => :orange
)
Logging.appenders.stdout(
'stdout',
:layout => Logging.layouts.pattern(
:pattern => '[%d] %-7l %c: %m\n',
:color_scheme => 'soothing_ish'
)
)
log = Logging.logger['Soothing::Colors']
log.add_appenders 'stdout'
log.level = :debug
log.debug 'a very nice little debug message'
log.info 'things are operating nominally'
log.happy 'What a beautiful day'
log.warn 'this is your last warning'
log.success 'I am INWEENCIBLE!!'
log.error StandardError.new('something went horribly wrong')
log.fatal 'I Die!'
# :startdoc:
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tcltklib/lines2.rb
|
<reponame>arnab0073/idea
#! /usr/local/bin/ruby
require "tk"
def drawlines()
print Time.now, "\n"
for j in 0 .. 99
print "*"
$stdout.flush
if (j & 1) != 0
col = "blue"
else
col = "red"
end
for i in 0 .. 99
# TkcLine.new($a, i, 0, 0, 500 - i, "-fill", col)
end
end
print Time.now, "\n"
for j in 0 .. 99
print "*"
$stdout.flush
if (j & 1) != 0
col = "blue"
else
col = "red"
end
for i in 0 .. 99
TkcLine.new($a, i, 0, 0, 500 - i, "-fill", col)
end
end
print Time.now, "\n"
# Tk.root.destroy
end
$a = TkCanvas.new{
height(500)
width(500)
}
$b = TkButton.new{
text("draw")
command(proc{drawlines()})
}
TkPack.configure($a, $b, {"side"=>"left"})
Tk.mainloop
# eof
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/tcllib/dateentry.rb
|
<gh_stars>1-10
#
# tkextlib/tcllib/dateentry.rb
# by <NAME> (<EMAIL>)
#
# * Part of tcllib extension
# * dateentry widget
#
require 'tk'
require 'tkextlib/tcllib.rb'
# TkPackage.require('widget::dateentry', '0.91')
TkPackage.require('widget::dateentry')
module Tk::Tcllib
module Widget
class Dateentry < Tk::Tile::TEntry
PACKAGE_NAME = 'widget::dateentry'.freeze
def self.package_name
PACKAGE_NAME
end
def self.package_version
begin
TkPackage.require('widget::dateentry')
rescue
''
end
end
end
DateEntry = Dateentry
end
end
class Tk::Tcllib::Widget::Dateentry
TkCommandNames = ['::widget::dateentry'.freeze].freeze
def __strval_optkeys
super() << ['dateformat']
end
private :__strval_optkeys
def create_self(keys)
if keys and keys != None
tk_call_without_enc(self.class::TkCommandNames[0], @path,
*hash_kv(keys, true))
else
tk_call_without_enc(self.class::TkCommandNames[0], @path)
end
end
private :create_self
def post
tk_send('post')
self
end
def unpost
tk_send('unpost')
self
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/fog-core-1.40.0/lib/fog/compute/models/server.rb
|
require "fog/core/model"
module Fog
module Compute
class Server < Fog::Model
attr_writer :username, :private_key, :private_key_path, :public_key, :public_key_path, :ssh_port, :ssh_options
# Sets the proc used to determine the IP Address used for ssh/scp interactions.
# @example
# service.servers.bootstrap :name => "bootstrap-server",
# :flavor_id => service.flavors.first.id,
# :image_id => service.images.find {|img| img.name =~ /Ubuntu/}.id,
# :public_key_path => "~/.ssh/fog_rsa.pub",
# :private_key_path => "~/.ssh/fog_rsa",
# :ssh_ip_address => Proc.new {|server| server.private_ip_address }
#
# @note By default scp/ssh will use the public_ip_address if this proc is not set.
attr_writer :ssh_ip_address
def username
@username ||= "root"
end
def private_key_path
@private_key_path ||= Fog.credentials[:private_key_path]
@private_key_path &&= File.expand_path(@private_key_path)
end
def private_key
@private_key ||= private_key_path && File.read(private_key_path)
end
def public_key_path
@public_key_path ||= Fog.credentials[:public_key_path]
@public_key_path &&= File.expand_path(@public_key_path)
end
def public_key
@public_key ||= public_key_path && File.read(public_key_path)
end
# Port used for ssh/scp interactions with server.
# @return [Integer] IP port
# @note By default this returns 22
def ssh_port
@ssh_port ||= 22
end
# IP Address used for ssh/scp interactions with server.
# @return [String] IP Address
# @note By default this returns the public_ip_address
def ssh_ip_address
return public_ip_address unless @ssh_ip_address
return @ssh_ip_address.call(self) if @ssh_ip_address.is_a?(Proc)
@ssh_ip_address
end
def ssh_options
@ssh_options ||= {}
ssh_options = @ssh_options.merge(:port => ssh_port)
if private_key
ssh_options[:key_data] = [private_key]
ssh_options[:auth_methods] = %w(publickey)
end
ssh_options
end
def scp(local_path, remote_path, upload_options = {})
requires :ssh_ip_address, :username
Fog::SCP.new(ssh_ip_address, username, ssh_options).upload(local_path, remote_path, upload_options)
end
alias_method :scp_upload, :scp
def scp_download(remote_path, local_path, download_options = {})
requires :ssh_ip_address, :username
Fog::SCP.new(ssh_ip_address, username, ssh_options).download(remote_path, local_path, download_options)
end
def ssh(commands, options = {}, &blk)
requires :ssh_ip_address, :username
options = ssh_options.merge(options)
Fog::SSH.new(ssh_ip_address, username, options).run(commands, &blk)
end
def sshable?(options = {})
ready? && !ssh_ip_address.nil? && !!Timeout.timeout(8) { ssh("pwd", options) }
rescue SystemCallError, Net::SSH::AuthenticationFailed, Net::SSH::Disconnect, Timeout::Error
false
end
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/mixlib-shellout-2.2.6/lib/mixlib/shellout/windows/core_ext.rb
|
#--
# Author:: <NAME> (<<EMAIL>>)
# Author:: <NAME> (<<EMAIL>>)
# Copyright:: Copyright (c) 2011, 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.
#
require 'win32/process'
# Add new constants for Logon
module Process::Constants
private
LOGON32_LOGON_INTERACTIVE = 0x00000002
LOGON32_PROVIDER_DEFAULT = 0x00000000
UOI_NAME = 0x00000002
WAIT_OBJECT_0 = 0
WAIT_TIMEOUT = 0x102
WAIT_ABANDONED = 128
WAIT_ABANDONED_0 = WAIT_ABANDONED
WAIT_FAILED = 0xFFFFFFFF
end
# Define the functions needed to check with Service windows station
module Process::Functions
ffi_lib :advapi32
attach_pfunc :LogonUserW,
[:buffer_in, :buffer_in, :buffer_in, :ulong, :ulong, :pointer], :bool
attach_pfunc :CreateProcessAsUserW,
[:ulong, :buffer_in, :buffer_inout, :pointer, :pointer, :int,
:ulong, :buffer_in, :buffer_in, :pointer, :pointer], :bool
ffi_lib :user32
attach_pfunc :GetProcessWindowStation,
[], :ulong
attach_pfunc :GetUserObjectInformationA,
[:ulong, :uint, :buffer_out, :ulong, :pointer], :bool
end
# Override Process.create to check for running in the Service window station and doing
# a full logon with LogonUser, instead of a CreateProcessWithLogon
# Cloned from https://github.com/djberg96/win32-process/blob/ffi/lib/win32/process.rb
# as of 2015-10-15 from commit cc066e5df25048f9806a610f54bf5f7f253e86f7
module Process
# Explicitly reopen singleton class so that class/constant declarations from
# extensions are visible in Modules.nesting.
class << self
def create(args)
unless args.kind_of?(Hash)
raise TypeError, 'hash keyword arguments expected'
end
valid_keys = %w[
app_name command_line inherit creation_flags cwd environment
startup_info thread_inherit process_inherit close_handles with_logon
domain password
]
valid_si_keys = %w[
startf_flags desktop title x y x_size y_size x_count_chars
y_count_chars fill_attribute sw_flags stdin stdout stderr
]
# Set default values
hash = {
'app_name' => nil,
'creation_flags' => 0,
'close_handles' => true
}
# Validate the keys, and convert symbols and case to lowercase strings.
args.each{ |key, val|
key = key.to_s.downcase
unless valid_keys.include?(key)
raise ArgumentError, "invalid key '#{key}'"
end
hash[key] = val
}
si_hash = {}
# If the startup_info key is present, validate its subkeys
if hash['startup_info']
hash['startup_info'].each{ |key, val|
key = key.to_s.downcase
unless valid_si_keys.include?(key)
raise ArgumentError, "invalid startup_info key '#{key}'"
end
si_hash[key] = val
}
end
# The +command_line+ key is mandatory unless the +app_name+ key
# is specified.
unless hash['command_line']
if hash['app_name']
hash['command_line'] = hash['app_name']
hash['app_name'] = nil
else
raise ArgumentError, 'command_line or app_name must be specified'
end
end
env = nil
# The env string should be passed as a string of ';' separated paths.
if hash['environment']
env = hash['environment']
unless env.respond_to?(:join)
env = hash['environment'].split(File::PATH_SEPARATOR)
end
env = env.map{ |e| e + 0.chr }.join('') + 0.chr
env.to_wide_string! if hash['with_logon']
end
# Process SECURITY_ATTRIBUTE structure
process_security = nil
if hash['process_inherit']
process_security = SECURITY_ATTRIBUTES.new
process_security[:nLength] = 12
process_security[:bInheritHandle] = 1
end
# Thread SECURITY_ATTRIBUTE structure
thread_security = nil
if hash['thread_inherit']
thread_security = SECURITY_ATTRIBUTES.new
thread_security[:nLength] = 12
thread_security[:bInheritHandle] = 1
end
# Automatically handle stdin, stdout and stderr as either IO objects
# or file descriptors. This won't work for StringIO, however. It also
# will not work on JRuby because of the way it handles internal file
# descriptors.
#
['stdin', 'stdout', 'stderr'].each{ |io|
if si_hash[io]
if si_hash[io].respond_to?(:fileno)
handle = get_osfhandle(si_hash[io].fileno)
else
handle = get_osfhandle(si_hash[io])
end
if handle == INVALID_HANDLE_VALUE
ptr = FFI::MemoryPointer.new(:int)
if windows_version >= 6 && get_errno(ptr) == 0
errno = ptr.read_int
else
errno = FFI.errno
end
raise SystemCallError.new("get_osfhandle", errno)
end
# Most implementations of Ruby on Windows create inheritable
# handles by default, but some do not. RF bug #26988.
bool = SetHandleInformation(
handle,
HANDLE_FLAG_INHERIT,
HANDLE_FLAG_INHERIT
)
raise SystemCallError.new("SetHandleInformation", FFI.errno) unless bool
si_hash[io] = handle
si_hash['startf_flags'] ||= 0
si_hash['startf_flags'] |= STARTF_USESTDHANDLES
hash['inherit'] = true
end
}
procinfo = PROCESS_INFORMATION.new
startinfo = STARTUPINFO.new
unless si_hash.empty?
startinfo[:cb] = startinfo.size
startinfo[:lpDesktop] = si_hash['desktop'] if si_hash['desktop']
startinfo[:lpTitle] = si_hash['title'] if si_hash['title']
startinfo[:dwX] = si_hash['x'] if si_hash['x']
startinfo[:dwY] = si_hash['y'] if si_hash['y']
startinfo[:dwXSize] = si_hash['x_size'] if si_hash['x_size']
startinfo[:dwYSize] = si_hash['y_size'] if si_hash['y_size']
startinfo[:dwXCountChars] = si_hash['x_count_chars'] if si_hash['x_count_chars']
startinfo[:dwYCountChars] = si_hash['y_count_chars'] if si_hash['y_count_chars']
startinfo[:dwFillAttribute] = si_hash['fill_attribute'] if si_hash['fill_attribute']
startinfo[:dwFlags] = si_hash['startf_flags'] if si_hash['startf_flags']
startinfo[:wShowWindow] = si_hash['sw_flags'] if si_hash['sw_flags']
startinfo[:cbReserved2] = 0
startinfo[:hStdInput] = si_hash['stdin'] if si_hash['stdin']
startinfo[:hStdOutput] = si_hash['stdout'] if si_hash['stdout']
startinfo[:hStdError] = si_hash['stderr'] if si_hash['stderr']
end
app = nil
cmd = nil
# Convert strings to wide character strings if present
if hash['app_name']
app = hash['app_name'].to_wide_string
end
if hash['command_line']
cmd = hash['command_line'].to_wide_string
end
if hash['cwd']
cwd = hash['cwd'].to_wide_string
end
inherit = hash['inherit'] ? 1 : 0
if hash['with_logon']
logon = hash['with_logon'].to_wide_string
if hash['password']
passwd = hash['password'].to_wide_string
else
raise ArgumentError, 'password must be specified if with_logon is used'
end
if hash['domain']
domain = hash['domain'].to_wide_string
end
hash['creation_flags'] |= CREATE_UNICODE_ENVIRONMENT
winsta_name = FFI::MemoryPointer.new(:char, 256)
return_size = FFI::MemoryPointer.new(:ulong)
bool = GetUserObjectInformationA(
GetProcessWindowStation(), # Window station handle
UOI_NAME, # Information to get
winsta_name, # Buffer to receive information
winsta_name.size, # Size of buffer
return_size # Size filled into buffer
)
unless bool
raise SystemCallError.new("GetUserObjectInformationA", FFI.errno)
end
winsta_name = winsta_name.read_string(return_size.read_ulong)
# If running in the service windows station must do a log on to get
# to the interactive desktop. Running process user account must have
# the 'Replace a process level token' permission. This is necessary as
# the logon (which happens with CreateProcessWithLogon) must have an
# interactive windows station to attach to, which is created with the
# LogonUser cann with the LOGON32_LOGON_INTERACTIVE flag.
if winsta_name =~ /^Service-0x0-.*$/i
token = FFI::MemoryPointer.new(:ulong)
bool = LogonUserW(
logon, # User
domain, # Domain
passwd, # Password
LOGON32_LOGON_INTERACTIVE, # Logon Type
LOGON32_PROVIDER_DEFAULT, # Logon Provider
token # User token handle
)
unless bool
raise SystemCallError.new("LogonUserW", FFI.errno)
end
token = token.read_ulong
begin
bool = CreateProcessAsUserW(
token, # User token handle
app, # App name
cmd, # Command line
process_security, # Process attributes
thread_security, # Thread attributes
inherit, # Inherit handles
hash['creation_flags'], # Creation Flags
env, # Environment
cwd, # Working directory
startinfo, # Startup Info
procinfo # Process Info
)
ensure
CloseHandle(token)
end
unless bool
raise SystemCallError.new("CreateProcessAsUserW (You must hold the 'Replace a process level token' permission)", FFI.errno)
end
else
bool = CreateProcessWithLogonW(
logon, # User
domain, # Domain
passwd, # Password
LOGON_WITH_PROFILE, # Logon flags
app, # App name
cmd, # Command line
hash['creation_flags'], # Creation flags
env, # Environment
cwd, # Working directory
startinfo, # Startup Info
procinfo # Process Info
)
unless bool
raise SystemCallError.new("CreateProcessWithLogonW", FFI.errno)
end
end
else
bool = CreateProcessW(
app, # App name
cmd, # Command line
process_security, # Process attributes
thread_security, # Thread attributes
inherit, # Inherit handles?
hash['creation_flags'], # Creation flags
env, # Environment
cwd, # Working directory
startinfo, # Startup Info
procinfo # Process Info
)
unless bool
raise SystemCallError.new("CreateProcessW", FFI.errno)
end
end
# Automatically close the process and thread handles in the
# PROCESS_INFORMATION struct unless explicitly told not to.
if hash['close_handles']
CloseHandle(procinfo[:hProcess])
CloseHandle(procinfo[:hThread])
# Clear these fields so callers don't attempt to close the handle
# which can result in the wrong handle being closed or an
# exception in some circumstances.
procinfo[:hProcess] = 0
procinfo[:hThread] = 0
end
ProcessInfo.new(
procinfo[:hProcess],
procinfo[:hThread],
procinfo[:dwProcessId],
procinfo[:dwThreadId]
)
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/openstack/models/baremetal/drivers.rb
|
require 'fog/core/collection'
require 'fog/openstack/models/baremetal/driver'
module Fog
module Baremetal
class OpenStack
class Drivers < Fog::Collection
model Fog::Baremetal::OpenStack::Driver
def all
load(service.list_drivers.body['drivers'])
end
def find_by_name(name)
new(service.get_driver(name).body)
end
alias_method :get, :find_by_name
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/win32ole/sample/ie.rb
|
<reponame>arnab0073/idea
require 'win32ole'
url = 'http://www.ruby-lang.org/'
ie = WIN32OLE.new('InternetExplorer.Application')
ie.visible = TRUE
ie.gohome
print "Now navigate Ruby home page... Please enter."
gets
ie.navigate(url)
print "Now quit Internet Explorer... Please enter."
gets
ie.Quit()
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/openstack/models/planning/roles.rb
|
require 'fog/core/collection'
require 'fog/openstack/models/planning/role'
module Fog
module Openstack
class Planning
class Roles < Fog::Collection
model Fog::Openstack::Planning::Role
def all
load(service.list_roles.body)
end
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/dl/extconf.rb
|
require 'mkmf'
if RbConfig::CONFIG['GCC'] == 'yes'
$CFLAGS << " -fno-defer-pop -fno-omit-frame-pointer"
end
$INSTALLFILES = [
["dl.h", "$(HDRDIR)"],
]
check = true
if( have_header("dlfcn.h") )
have_library("dl")
check &&= have_func("dlopen")
check &&= have_func("dlclose")
check &&= have_func("dlsym")
have_func("dlerror")
elsif( have_header("windows.h") )
check &&= have_func("LoadLibrary")
check &&= have_func("FreeLibrary")
check &&= have_func("GetProcAddress")
else
check = false
end
if check
$defs << %[-DRUBY_VERSION=\\"#{RUBY_VERSION}\\"]
create_makefile("dl")
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/bwidget/labelframe.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/bwidget/labelframe.rb
#
# tkextlib/bwidget/labelframe.rb
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tk/frame'
require 'tkextlib/bwidget.rb'
require 'tkextlib/bwidget/label'
module Tk
module BWidget
class LabelFrame < TkWindow
end
end
end
class Tk::BWidget::LabelFrame
TkCommandNames = ['LabelFrame'.freeze].freeze
WidgetClassName = 'LabelFrame'.freeze
WidgetClassNames[WidgetClassName] ||= self
def __strval_optkeys
super() << 'helptext'
end
private :__strval_optkeys
def __boolval_optkeys
super() << 'dragenabled' << 'dropenabled'
end
private :__boolval_optkeys
def __tkvariable_optkeys
super() << 'helpvar'
end
private :__tkvariable_optkeys
def self.align(*args)
tk_call('LabelFrame::align', *args)
end
def get_frame(&b)
win = window(tk_send_without_enc('getframe'))
if b
if TkCore::WITH_RUBY_VM ### Ruby 1.9 !!!!
win.instance_exec(self, &b)
else
win.instance_eval(&b)
end
end
win
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/test/test_utils.rb
|
<reponame>arnab0073/idea<gh_stars>100-1000
require File.expand_path('setup', File.dirname(__FILE__))
module TestLogging
class TestUtils < Test::Unit::TestCase
def test_string_shrink
str = 'this is the foobar string'
len = str.length
r = str.shrink(len + 1)
assert_same str, r
r = str.shrink(len)
assert_same str, r
r = str.shrink(len - 1)
assert_equal 'this is the...bar string', r
r = str.shrink(len - 10)
assert_equal 'this i...string', r
r = str.shrink(4)
assert_equal 't...', r
r = str.shrink(3)
assert_equal '...', r
r = str.shrink(0)
assert_equal '...', r
assert_raises(ArgumentError) { str.shrink(-1) }
r = str.shrink(len - 1, '##')
assert_equal 'this is the##obar string', r
r = str.shrink(len - 10, '##')
assert_equal 'this is##string', r
r = str.shrink(4, '##')
assert_equal 't##g', r
r = str.shrink(3, '##')
assert_equal 't##', r
r = str.shrink(0, '##')
assert_equal '##', r
end
def test_logger_name
assert_equal 'Array', Array.logger_name
# some lines are commented out for compatibility with ruby 1.9
c = Class.new(Array)
# assert_equal '', c.name
assert_equal 'Array', c.logger_name
meta = class << Array; self; end
# assert_equal '', meta.name
assert_equal 'Array', meta.logger_name
m = Module.new
# assert_equal '', m.name
assert_equal 'anonymous', m.logger_name
c = Class.new(::Logging::Logger)
# assert_equal '', c.name
assert_equal 'Logging::Logger', c.logger_name
meta = class << ::Logging::Logger; self; end
# assert_equal '', meta.name
assert_equal 'Logging::Logger', meta.logger_name
end
end # class TestUtils
end # module TestLogging
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/lib/ohai/plugins/darwin/filesystem.rb
|
<reponame>arnab0073/idea
#
# 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 "filesystem"
fs = Mash.new
block_size = 0
popen4("df") do |pid, stdin, stdout, stderr|
stdin.close
stdout.each do |line|
case line
when /^Filesystem\s+(\d+)-/
block_size = $1.to_i
next
when /^(.+?)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+\%)\s+(.+)$/
filesystem = $1
fs[filesystem] = Mash.new
fs[filesystem][:block_size] = block_size
fs[filesystem][:kb_size] = $2.to_i / (1024 / block_size)
fs[filesystem][:kb_used] = $3.to_i / (1024 / block_size)
fs[filesystem][:kb_available] = $4.to_i / (1024 / block_size)
fs[filesystem][:percent_used] = $5
fs[filesystem][:mount] = $6
end
end
end
popen4("mount") do |pid, stdin, stdout, stderr|
stdin.close
stdout.each do |line|
if line =~ /^(.+?) on (.+?) \((.+?), (.+?)\)$/
filesystem = $1
fs[filesystem] = Mash.new unless fs.has_key?(filesystem)
fs[filesystem][:mount] = $2
fs[filesystem][:fs_type] = $3
fs[filesystem][:mount_options] = $4.split(/,\s*/)
end
end
end
filesystem fs
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/lib/logging/filters/level.rb
|
require 'set'
module Logging
module Filters
# The `Level` filter class provides a simple level-based filtering mechanism
# that filters messages to only include those from an enumerated list of
# levels to log.
class Level < ::Logging::Filter
# Creates a new level filter that will only allow the given _levels_ to
# propagate through to the logging destination. The _levels_ should be
# given in symbolic form.
#
# Examples
# Logging::Filters::Level.new(:debug, :info)
#
def initialize( *levels )
levels = levels.map { |level| ::Logging::level_num(level) }
@levels = Set.new levels
end
def allow( event )
@levels.include?(event.level) ? event : nil
end
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/examples/simple.rb
|
# :stopdoc:
#
# Logging provides a simple, default logger configured in the same manner as
# the default Ruby Logger class -- i.e. the output of the two will be the
# same. All log messages at "warn" or higher are printed to STDOUT; any
# message below the "warn" level are discarded.
#
require 'logging'
log = Logging.logger(STDOUT)
log.level = :warn
log.debug "this debug message will not be output by the logger"
log.warn "this is your last warning"
# :startdoc:
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/lib/ohai/plugins/sigar/network.rb
|
<gh_stars>1-10
#
# 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.
#
#http://github.com/mdkent/ohai/commit/92f51aa18b6add9682510a87dcf94835ea72b04d
require "sigar"
sigar = Sigar.new
provides "network", "counters/network"
ninfo = sigar.net_info
network[:default_interface] = ninfo.default_gateway_interface
network[:default_gateway] = ninfo.default_gateway
def encaps_lookup(encap)
return "Loopback" if encap.eql?("Local Loopback")
return "PPP" if encap.eql?("Point-to-Point Protocol")
return "SLIP" if encap.eql?("Serial Line IP")
return "VJSLIP" if encap.eql?("VJ Serial Line IP")
return "IPIP" if encap.eql?("IPIP Tunnel")
return "6to4" if encap.eql?("IPv6-in-IPv4")
encap
end
iface = Mash.new
net_counters = Mash.new
sigar.net_interface_list.each do |cint|
iface[cint] = Mash.new
if cint =~ /^(\w+)(\d+.*)/
iface[cint][:type] = $1
iface[cint][:number] = $2
end
ifconfig = sigar.net_interface_config(cint)
iface[cint][:encapsulation] = encaps_lookup(ifconfig.type)
iface[cint][:addresses] = Mash.new
# Backwards compat: loopback has no hwaddr
if (ifconfig.flags & Sigar::IFF_LOOPBACK) == 0
iface[cint][:addresses][ifconfig.hwaddr] = { "family" => "lladdr" }
end
if ifconfig.address != "0.0.0.0"
iface[cint][:addresses][ifconfig.address] = { "family" => "inet" }
# Backwards compat: no broadcast on tunnel or loopback dev
if (((ifconfig.flags & Sigar::IFF_POINTOPOINT) == 0) &&
((ifconfig.flags & Sigar::IFF_LOOPBACK) == 0))
iface[cint][:addresses][ifconfig.address]["broadcast"] = ifconfig.broadcast
end
iface[cint][:addresses][ifconfig.address]["netmask"] = ifconfig.netmask
end
iface[cint][:flags] = Sigar.net_interface_flags_to_s(ifconfig.flags).split(' ')
iface[cint][:mtu] = ifconfig.mtu.to_s
iface[cint][:queuelen] = ifconfig.tx_queue_len.to_s
if ifconfig.prefix6_length != 0
iface[cint][:addresses][ifconfig.address6] = { "family" => "inet6" }
iface[cint][:addresses][ifconfig.address6]["prefixlen"] = ifconfig.prefix6_length.to_s
iface[cint][:addresses][ifconfig.address6]["scope"] = Sigar.net_scope_to_s(ifconfig.scope6)
end
net_counters[cint] = Mash.new unless net_counters[cint]
if (!cint.include?(":"))
ifstat = sigar.net_interface_stat(cint)
net_counters[cint][:rx] = { "packets" => ifstat.rx_packets.to_s, "errors" => ifstat.rx_errors.to_s,
"drop" => ifstat.rx_dropped.to_s, "overrun" => ifstat.rx_overruns.to_s,
"frame" => ifstat.rx_frame.to_s, "bytes" => ifstat.rx_bytes.to_s }
net_counters[cint][:tx] = { "packets" => ifstat.tx_packets.to_s, "errors" => ifstat.tx_errors.to_s,
"drop" => ifstat.tx_dropped.to_s, "overrun" => ifstat.tx_overruns.to_s,
"carrier" => ifstat.tx_carrier.to_s, "collisions" => ifstat.tx_collisions.to_s,
"bytes" => ifstat.tx_bytes.to_s }
end
end
begin
sigar.arp_list.each do |arp|
next unless iface[arp.ifname] # this should never happen
iface[arp.ifname][:arp] = Mash.new unless iface[arp.ifname][:arp]
iface[arp.ifname][:arp][arp.address] = arp.hwaddr
end
rescue
#64-bit AIX for example requires 64-bit caller
end
counters[:network][:interfaces] = net_counters
network["interfaces"] = iface
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/demos-en/menu84.rb
|
#
# menus widget demo (called by 'widget')
#
# toplevel widget
if defined?($menu84_demo) && $menu84_demo
$menu84_demo.destroy
$menu84_demo = nil
end
# demo toplevel widget
$menu84_demo = TkToplevel.new {|w|
title("File Selection Dialogs")
iconname("menu84")
positionWindow(w)
}
base_frame = TkFrame.new($menu84_demo).pack(:fill=>:both, :expand=>true)
begin
windowingsystem = Tk.windowingsystem()
rescue
windowingsystem = ""
end
# label
TkLabel.new(base_frame,'font'=>$font,'wraplength'=>'4i','justify'=>'left') {
if $tk_platform['platform'] == 'macintosh' ||
windowingsystem == "classic" || windowingsystem == "aqua"
text("This window contains a menubar with cascaded menus. You can invoke entries with an accelerator by typing Command+x, where \"x\" is the character next to the command key symbol. The rightmost menu can be torn off into a palette by dragging outside of its bounds and releasing the mouse.")
else
text("This window contains a menubar with cascaded menus. You can post a menu from the keyboard by typing Alt+x, where \"x\" is the character underlined on the menu. You can then traverse among the menus using the arrow keys. When a menu is posted, you can invoke the current entry by typing space, or you can invoke any entry by typing its underlined character. If a menu entry has an accelerator, you can invoke the entry without posting the menu just by typing the accelerator. The rightmost menu can be torn off into a palette by selecting the first item in the menu.")
end
}.pack('side'=>'top')
menustatus = TkVariable.new(" ")
TkFrame.new(base_frame) {|frame|
TkLabel.new(frame, 'textvariable'=>menustatus, 'relief'=>'sunken',
'bd'=>1, 'font'=>['Helvetica', '10'],
'anchor'=>'w').pack('side'=>'left', 'padx'=>2,
'expand'=>true, 'fill'=>'both')
pack('side'=>'bottom', 'fill'=>'x', 'pady'=>2)
}
# frame
TkFrame.new(base_frame) {|frame|
TkButton.new(frame) {
text 'Dismiss'
command proc{
tmppath = $menu84_demo
$menu84_demo = nil
tmppath.destroy
}
}.pack('side'=>'left', 'expand'=>'yes')
TkButton.new(frame) {
text 'Show Code'
command proc{showCode 'menu84'}
}.pack('side'=>'left', 'expand'=>'yes')
}.pack('side'=>'bottom', 'fill'=>'x', 'pady'=>'2m')
# create menu frame
$menu84_frame = TkMenu.new($menu84_demo, 'tearoff'=>false)
# menu
TkMenu.new($menu84_frame, 'tearoff'=>false) {|m|
$menu84_frame.add('cascade', 'label'=>'File', 'menu'=>m, 'underline'=>0)
add('command', 'label'=>'Open...', 'command'=>proc{fail 'this is just a demo: no action has been defined for the "Open..." entry'})
add('command', 'label'=>'New', 'command'=>proc{fail 'this is just a demo: no action has been defined for the "New" entry'})
add('command', 'label'=>'Save', 'command'=>proc{fail 'this is just a demo: no action has been defined for the "Save" entry'})
add('command', 'label'=>'Save As...', 'command'=>proc{fail 'this is just a demo: no action has been defined for the "Save As..." entry'})
add('separator')
add('command', 'label'=>'Print Setup...', 'command'=>proc{fail 'this is just a demo: no action has been defined for the "Print Setup..." entry'})
add('command', 'label'=>'Print...', 'command'=>proc{fail 'this is just a demo: no action has been defined for the "Print..." entry'})
add('separator')
add('command', 'label'=>'Dismiss Menus Demo', 'command'=>proc{$menu84_demo.destroy})
}
if $tk_platform['platform'] == 'macintosh' ||
windowingsystem = "classic" || windowingsystem = "aqua"
modifier = 'Command'
elsif $tk_platform['platform'] == 'windows'
modifier = 'Control'
else
modifier = 'Meta'
end
TkMenu.new($menu84_frame, 'tearoff'=>false) {|m|
$menu84_frame.add('cascade', 'label'=>'Basic', 'menu'=>m, 'underline'=>0)
add('command', 'label'=>'Long entry that does nothing')
['A','B','C','D','E','F','G'].each{|c|
add('command', 'label'=>"Print letter \"#{c}\"",
'underline'=>14, 'accelerator'=>"Meta+#{c}",
'command'=>proc{print c,"\n"}, 'accelerator'=>"#{modifier}+#{c}")
$menu84_demo.bind("#{modifier}-#{c.downcase}", proc{print c,"\n"})
}
}
TkMenu.new($menu84_frame, 'tearoff'=>false) {|m|
$menu84_frame.add('cascade', 'label'=>'Cascades', 'menu'=>m, 'underline'=>0)
add('command', 'label'=>'Print hello',
'command'=>proc{print "Hello\n"},
'accelerator'=>"#{modifier}+H", 'underline'=>6)
$menu84_demo.bind("#{modifier}-h", proc{print "Hello\n"})
add('command', 'label'=>'Print goodbye',
'command'=>proc{print "Goodbye\n"},
'accelerator'=>"#{modifier}+G", 'underline'=>6)
$menu84_demo.bind("#{modifier}-g", proc{print "Goodbye\n"})
TkMenu.new(m, 'tearoff'=>false) {|cascade_check|
m.add('cascade', 'label'=>'Check buttons',
'menu'=>cascade_check, 'underline'=>0)
oil = TkVariable.new(0)
add('check', 'label'=>'Oil checked', 'variable'=>oil)
trans = TkVariable.new(0)
add('check', 'label'=>'Transmission checked', 'variable'=>trans)
brakes = TkVariable.new(0)
add('check', 'label'=>'Brakes checked', 'variable'=>brakes)
lights = TkVariable.new(0)
add('check', 'label'=>'Lights checked', 'variable'=>lights)
add('separator')
add('command', 'label'=>'Show current values',
'command'=>proc{showVars($menu84_demo,
['oil', oil],
['trans', trans],
['brakes', brakes],
['lights', lights])} )
invoke 1
invoke 3
}
TkMenu.new(m, 'tearoff'=>false) {|cascade_radio|
m.add('cascade', 'label'=>'Radio buttons',
'menu'=>cascade_radio, 'underline'=>0)
pointSize = TkVariable.new
add('radio', 'label'=>'10 point', 'variable'=>pointSize, 'value'=>10)
add('radio', 'label'=>'14 point', 'variable'=>pointSize, 'value'=>14)
add('radio', 'label'=>'18 point', 'variable'=>pointSize, 'value'=>18)
add('radio', 'label'=>'24 point', 'variable'=>pointSize, 'value'=>24)
add('radio', 'label'=>'32 point', 'variable'=>pointSize, 'value'=>32)
add('separator')
style = TkVariable.new
add('radio', 'label'=>'Roman', 'variable'=>style, 'value'=>'roman')
add('radio', 'label'=>'Bold', 'variable'=>style, 'value'=>'bold')
add('radio', 'label'=>'Italic', 'variable'=>style, 'value'=>'italic')
add('separator')
add('command', 'label'=>'Show current values',
'command'=>proc{showVars($menu84_demo,
['pointSize', pointSize],
['style', style])} )
invoke 1
invoke 7
}
}
TkMenu.new($menu84_frame, 'tearoff'=>false) {|m|
$menu84_frame.add('cascade', 'label'=>'Icons', 'menu'=>m, 'underline'=>0)
add('command', 'hidemargin'=>1,
'bitmap'=>'@'+[$demo_dir,'..',
'images','pattern.xbm'].join(File::Separator),
'command'=>proc{TkDialog.new('title'=>'Bitmap Menu Entry',
'text'=>'The menu entry you invoked displays a bitmap rather than a text string. Other than this, it is just like any other menu entry.',
'bitmap'=>'', 'default'=>0,
'buttons'=>'Dismiss')} )
['info', 'questhead', 'error'].each{|icon|
add('command', 'bitmap'=>icon, 'hidemargin'=>1,
'command'=>proc{print "You invoked the #{icon} bitmap\n"})
}
entryconfigure(2, :columnbreak=>true)
}
TkMenu.new($menu84_frame, 'tearoff'=>false) {|m|
$menu84_frame.add('cascade', 'label'=>'More', 'menu'=>m, 'underline'=>0)
[ 'An entry','Another entry','Does nothing','Does almost nothing',
'Make life meaningful' ].each{|i|
add('command', 'label'=>i,
'command'=>proc{print "You invoked \"#{i}\"\n"})
}
m.entryconfigure('Does almost nothing',
'bitmap'=>'questhead', 'compound'=>'left',
'command'=>proc{
TkDialog.new('title'=>'Compound Menu Entry',
'message'=>'The menu entry you invoked'+
'displays both a bitmap and '+
'a text string. Other than '+
'this, it isjust like any '+
'other menu entry.',
'buttons'=>['OK'], 'bitmap'=>'')
})
}
TkMenu.new($menu84_frame) {|m|
$menu84_frame.add('cascade', 'label'=>'Colors', 'menu'=>m, 'underline'=>0)
['red', 'orange', 'yellow', 'green', 'blue'].each{|c|
add('command', 'label'=>c, 'background'=>c,
'command'=>proc{print "You invoked \"#{c}\"\n"})
}
}
$menu84_demo.menu($menu84_frame)
TkMenu.bind('<MenuSelect>', proc{|w|
begin
label = w.entrycget('active', 'label')
rescue
label = " "
end
menustatus.value = label
Tk.update(true)
}, '%W')
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/net-ssh-2.6.8/test/authentication/test_key_manager.rb
|
require 'common'
require 'net/ssh/authentication/key_manager'
module Authentication
class TestKeyManager < Test::Unit::TestCase
def test_key_files_and_known_identities_are_empty_by_default
assert manager.key_files.empty?
assert manager.known_identities.empty?
end
def test_assume_agent_is_available_by_default
assert manager.use_agent?
end
def test_add_ensures_list_is_unique
manager.add "/first"
manager.add "/second"
manager.add "/third"
manager.add "/second"
assert_true manager.key_files.length == 3
final_files = manager.key_files.map {|item| item.split('/').last}
assert_equal %w(first second third), final_files
end
def test_use_agent_should_be_set_to_false_if_agent_could_not_be_found
Net::SSH::Authentication::Agent.expects(:connect).raises(Net::SSH::Authentication::AgentNotAvailable)
assert manager.use_agent?
assert_nil manager.agent
assert !manager.use_agent?
end
def test_each_identity_should_load_from_key_files
manager.stubs(:agent).returns(nil)
first = File.expand_path("/first")
second = File.expand_path("/second")
stub_file_private_key first, rsa
stub_file_private_key second, dsa
identities = []
manager.each_identity { |identity| identities << identity }
assert_equal 2, identities.length
assert_equal rsa.to_blob, identities.first.to_blob
assert_equal dsa.to_blob, identities.last.to_blob
assert_equal({:from => :file, :file => first, :key => rsa}, manager.known_identities[rsa])
assert_equal({:from => :file, :file => second, :key => dsa}, manager.known_identities[dsa])
end
def test_identities_should_load_from_agent
manager.stubs(:agent).returns(agent)
identities = []
manager.each_identity { |identity| identities << identity }
assert_equal 2, identities.length
assert_equal rsa.to_blob, identities.first.to_blob
assert_equal dsa.to_blob, identities.last.to_blob
assert_equal({:from => :agent}, manager.known_identities[rsa])
assert_equal({:from => :agent}, manager.known_identities[dsa])
end
if defined?(OpenSSL::PKey::EC)
def test_identities_with_ecdsa_should_load_from_agent
manager.stubs(:agent).returns(agent_with_ecdsa_keys)
identities = []
manager.each_identity { |identity| identities << identity }
assert_equal 5, identities.length
assert_equal rsa.to_blob, identities[0].to_blob
assert_equal dsa.to_blob, identities[1].to_blob
assert_equal ecdsa_sha2_nistp256.to_blob, identities[2].to_blob
assert_equal ecdsa_sha2_nistp384.to_blob, identities[3].to_blob
assert_equal ecdsa_sha2_nistp521.to_blob, identities[4].to_blob
assert_equal({:from => :agent}, manager.known_identities[rsa])
assert_equal({:from => :agent}, manager.known_identities[dsa])
assert_equal({:from => :agent}, manager.known_identities[ecdsa_sha2_nistp256])
assert_equal({:from => :agent}, manager.known_identities[ecdsa_sha2_nistp384])
assert_equal({:from => :agent}, manager.known_identities[ecdsa_sha2_nistp521])
end
end
def test_only_identities_with_key_files_should_load_from_agent_of_keys_only_set
manager(:keys_only => true).stubs(:agent).returns(agent)
first = File.expand_path("/first")
stub_file_private_key first, rsa
identities = []
manager.each_identity { |identity| identities << identity }
assert_equal 1, identities.length
assert_equal rsa.to_blob, identities.first.to_blob
assert_equal({:from => :agent}, manager.known_identities[rsa])
end
def test_identities_without_public_key_files_should_not_be_touched_if_identity_loaded_from_agent
manager.stubs(:agent).returns(agent)
first = File.expand_path("/first")
stub_file_public_key first, rsa
second = File.expand_path("/second")
stub_file_private_key second, dsa, :passphrase => :should_not_be_asked
identities = []
manager.each_identity do |identity|
identities << identity
break if manager.known_identities[identity][:from] == :agent
end
assert_equal 1, identities.length
assert_equal rsa.to_blob, identities.first.to_blob
end
def test_sign_with_agent_originated_key_should_request_signature_from_agent
manager.stubs(:agent).returns(agent)
manager.each_identity { |identity| } # preload the known_identities
agent.expects(:sign).with(rsa, "hello, world").returns("abcxyz123")
assert_equal "abcxyz123", manager.sign(rsa, "hello, world")
end
def test_sign_with_file_originated_key_should_load_private_key_and_sign_with_it
manager.stubs(:agent).returns(nil)
first = File.expand_path("/first")
stub_file_private_key first, rsa(512)
rsa.expects(:ssh_do_sign).with("hello, world").returns("<KEY>")
manager.each_identity { |identity| } # preload the known_identities
assert_equal "\0\0\0\assh-rsa\0\0\0\011abcxyz123", manager.sign(rsa, "hello, world")
end
def test_sign_with_file_originated_key_should_raise_key_manager_error_if_unloadable
manager.known_identities[rsa] = { :from => :file, :file => "/first" }
Net::SSH::KeyFactory.expects(:load_private_key).raises(OpenSSL::PKey::RSAError)
assert_raises Net::SSH::Authentication::KeyManagerError do
manager.sign(rsa, "hello, world")
end
end
private
def stub_file_private_key(name, key, options = {})
manager.add(name)
File.stubs(:readable?).with(name).returns(true)
File.stubs(:readable?).with(name + ".pub").returns(false)
case options.fetch(:passphrase, :indifferently)
when :should_be_asked
Net::SSH::KeyFactory.expects(:load_private_key).with(name, nil, false).raises(OpenSSL::PKey::RSAError).at_least_once
Net::SSH::KeyFactory.expects(:load_private_key).with(name, nil, true).returns(key).at_least_once
when :should_not_be_asked
Net::SSH::KeyFactory.expects(:load_private_key).with(name, nil, false).raises(OpenSSL::PKey::RSAError).at_least_once
Net::SSH::KeyFactory.expects(:load_private_key).with(name, nil, true).never
else # :indifferently
Net::SSH::KeyFactory.expects(:load_private_key).with(name, nil, any_of(true, false)).returns(key).at_least_once
end
# do not override OpenSSL::PKey::EC#public_key
# (it will be called in transport/openssl.rb.)
unless defined?(OpenSSL::PKey::EC) && key.public_key.kind_of?(OpenSSL::PKey::EC::Point)
key.stubs(:public_key).returns(key)
end
end
def stub_file_public_key(name, key)
manager.add(name)
File.stubs(:readable?).with(name).returns(false)
File.stubs(:readable?).with(name + ".pub").returns(true)
Net::SSH::KeyFactory.expects(:load_public_key).with(name + ".pub").returns(key).at_least_once
end
def rsa(size=512)
@rsa ||= OpenSSL::PKey::RSA.new(size)
end
def dsa
@dsa ||= OpenSSL::PKey::DSA.new(512)
end
if defined?(OpenSSL::PKey::EC)
def ecdsa_sha2_nistp256
@ecdsa_sha2_nistp256 ||= OpenSSL::PKey::EC.new("prime256v1").generate_key
end
def ecdsa_sha2_nistp384
@ecdsa_sha2_nistp384 ||= OpenSSL::PKey::EC.new("secp384r1").generate_key
end
def ecdsa_sha2_nistp521
@ecdsa_sha2_nistp521 ||= OpenSSL::PKey::EC.new("secp521r1").generate_key
end
end
def agent
@agent ||= stub("agent", :identities => [rsa, dsa])
end
def agent_with_ecdsa_keys
@agent ||= stub("agent", :identities => [rsa, dsa,
ecdsa_sha2_nistp256,
ecdsa_sha2_nistp384,
ecdsa_sha2_nistp521])
end
def manager(options = {})
@manager ||= Net::SSH::Authentication::KeyManager.new(nil, options)
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/winrm-1.8.1/lib/winrm/command_executor.rb
|
# -*- encoding: utf-8 -*-
#
# Copyright 2015 <NAME> <<EMAIL>>
# Copyright 2015 <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
# Object which can execute multiple commands and Powershell scripts in
# one shared remote shell session. The maximum number of commands per
# shell is determined by interrogating the remote host when the session
# is opened and the remote shell is automatically recycled before the
# threshold is reached.
#
# @author <NAME> <<EMAIL>>
# @author <NAME> <<EMAIL>>
# @author <NAME> <<EMAIL>>
class CommandExecutor
# Closes an open remote shell session left open
# after a command executor is garbage collecyted.
#
# @param shell_id [String] the remote shell identifier
# @param service [WinRM::WinRMWebService] a winrm web service object
def self.finalize(shell_id, service)
proc { service.close_shell(shell_id) }
end
# @return [WinRM::WinRMWebService] a WinRM web service object
attr_reader :service
# @return [String,nil] the identifier for the current open remote
# shell session, or `nil` if the session is not open
attr_reader :shell
# Creates a CommandExecutor given a `WinRM::WinRMWebService` object.
#
# @param service [WinRM::WinRMWebService] a winrm web service object
# responds to `#debug` and `#info` (default: `nil`)
def initialize(service)
@service = service
@command_count = 0
end
# Closes the open remote shell session. This method can be called
# multiple times, even if there is no open session.
def close
return if shell.nil?
service.close_shell(shell)
remove_finalizer
@shell = nil
end
# Opens a remote shell session for reuse. The maxiumum
# command-per-shell threshold is also determined the first time this
# method is invoked and cached for later invocations.
#
# @return [String] the remote shell session indentifier
def open
close
retryable(service.retry_limit, service.retry_delay) do
@shell = service.open_shell(codepage: code_page)
end
add_finalizer(shell)
@command_count = 0
shell
end
# Runs a CMD command.
#
# @param command [String] the command to run on the remote system
# @param arguments [Array<String>] arguments to the command
# @yield [stdout, stderr] yields more live access the standard
# output and standard error streams as they are returns, if
# streaming behavior is desired
# @return [WinRM::Output] output object with stdout, stderr, and
# exit code
def run_cmd(command, arguments = [], &block)
tries ||= 2
reset if command_count > max_commands
ensure_open_shell!
@command_count += 1
result = nil
service.run_command(shell, command, arguments) do |command_id|
result = service.get_command_output(shell, command_id, &block)
end
result
rescue WinRMWSManFault => e
# Fault code 2150858843 may be raised if the shell id that the command is sent on
# has been closed. One might see this on a target windows machine that has just
# been provisioned and restarted the winrm service at the end of its provisioning
# routine. If this hapens, we should give the command one more try.
# Fault code 2147943418 may be raised if the shell is installing an msi and for
# some reason it tries to read a registry key that has been deleted. This sometimes
# happens for 2008r2 when installing the Chef omnibus msi.
if %w(2150858843 2147943418).include?(e.fault_code) && (tries -= 1) > 0
service.logger.debug('[WinRM] opening new shell since the current one failed')
@shell = nil
open
retry
else
raise
end
end
# Run a Powershell script that resides on the local box.
#
# @param script_file [IO,String] an IO reference for reading the
# Powershell script or the actual file contents
# @yield [stdout, stderr] yields more live access the standard
# output and standard error streams as they are returns, if
# streaming behavior is desired
# @return [WinRM::Output] output object with stdout, stderr, and
# exit code
def run_powershell_script(script_file, &block)
# this code looks overly compact in an attempt to limit local
# variable assignments that may contain large strings and
# consequently bloat the Ruby VM
run_cmd(
'powershell',
[
'-encodedCommand',
::WinRM::PowershellScript.new(
script_file.is_a?(IO) ? script_file.read : script_file
).encoded
],
&block
)
end
# Code page appropriate to os version. utf-8 (65001) is buggy pre win7/2k8r2
# So send MS-DOS (437) for earlier versions
#
# @return [Integer] code page in use
def code_page
@code_page ||= os_version < Gem::Version.new('6.1') ? 437 : 65_001
end
# @return [Integer] the safe maximum number of commands that can
# be executed in one remote shell session
def max_commands
@max_commands ||= (os_version < Gem::Version.new('6.2') ? 15 : 1500) - 2
end
private
# @return [Integer] the number of executed commands on the remote
# shell session
# @api private
attr_accessor :command_count
# Creates a finalizer for this connection which will close the open
# remote shell session when the object is garabage collected or on
# Ruby VM shutdown.
#
# @param shell_id [String] the remote shell identifier
# @api private
def add_finalizer(shell_id)
ObjectSpace.define_finalizer(self, self.class.finalize(shell_id, service))
end
# Ensures that there is an open remote shell session.
#
# @raise [WinRM::WinRMError] if there is no open shell
# @api private
def ensure_open_shell!
fail ::WinRM::WinRMError, "#{self.class}#open must be called " \
'before any run methods are invoked' if shell.nil?
end
# Fetches the OS build bersion of the remote endpoint
#
# @api private
def os_version
@os_version ||= begin
version = nil
wql = service.run_wql('select version from Win32_OperatingSystem')
if wql[:xml_fragment]
version = wql[:xml_fragment].first[:version] if wql[:xml_fragment].first[:version]
end
fail ::WinRM::WinRMError, 'Unable to determine endpoint os version' if version.nil?
Gem::Version.new(version)
end
end
# Removes any finalizers for this connection.
#
# @api private
def remove_finalizer
ObjectSpace.undefine_finalizer(self)
end
# Closes the remote shell session and opens a new one.
#
# @api private
def reset
service.logger.debug("Resetting WinRM shell (Max command limit is #{max_commands})")
open
end
# Yields to a block and reties the block if certain rescuable
# exceptions are raised.
#
# @param retries [Integer] the number of times to retry before failing
# @option delay [Float] the number of seconds to wait until
# attempting a retry
# @api private
def retryable(retries, delay)
yield
rescue *RESCUE_EXCEPTIONS_ON_ESTABLISH.call => e
if (retries -= 1) > 0
service.logger.info("[WinRM] connection failed. retrying in #{delay} seconds: #{e.inspect}")
sleep(delay)
retry
else
service.logger.warn("[WinRM] connection failed, terminating (#{e.inspect})")
raise
end
end
RESCUE_EXCEPTIONS_ON_ESTABLISH = lambda do
[
Errno::EACCES, Errno::EADDRINUSE, Errno::ECONNREFUSED, Errno::ETIMEDOUT,
Errno::ECONNRESET, Errno::ENETUNREACH, Errno::EHOSTUNREACH,
::WinRM::WinRMHTTPTransportError, ::WinRM::WinRMAuthorizationError,
HTTPClient::KeepAliveDisconnected, HTTPClient::ConnectTimeoutError
].freeze
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/test/appenders/test_string_io.rb
|
<gh_stars>1000+
require File.expand_path('../setup', File.dirname(__FILE__))
module TestLogging
module TestAppenders
class TestStringIO < Test::Unit::TestCase
include LoggingTestCase
def setup
super
@appender = Logging.appenders.string_io('test_appender')
@sio = @appender.sio
@levels = Logging::LEVELS
end
def teardown
@appender.close
@appender = nil
super
end
def test_reopen
assert_equal @sio.object_id, @appender.sio.object_id
@appender.reopen
assert @sio.closed?, 'StringIO instance is closed'
assert_not_equal @sio.object_id, @appender.sio.object_id
end
end # class TestStringIO
end # module TestAppenders
end # module TestLogging
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/rubyntlm-0.6.0/spec/lib/net/ntlm/string_spec.rb
|
require 'spec_helper'
describe Net::NTLM::String do
it_behaves_like 'a field', 'Foo', false
let(:active) {
Net::NTLM::String.new({
:value => 'Test',
:active => true,
:size => 4
})
}
let(:inactive) {
Net::NTLM::String.new({
:value => 'Test',
:active => false,
:size => 4
})
}
context '#serialize' do
it 'should return the value when active' do
expect(active.serialize).to eq('Test')
end
it 'should return an empty string when inactive' do
expect(inactive.serialize).to eq('')
end
it 'should coerce non-string values into strings' do
active.value = 15
expect(active.serialize).to eq('15')
end
it 'should return empty string on a nil' do
active.value = nil
expect(active.serialize).to eq('')
end
end
context '#value=' do
it 'should set active to false if it empty' do
active.value = ''
expect(active.active).to eq(false)
end
it 'should adjust the size based on the value set' do
expect(active.size).to eq(4)
active.value = 'Foobar'
expect(active.size).to eq(6)
end
end
context '#parse' do
it 'should read in a string of the proper size' do
expect(active.parse('tseT')).to eq(4)
expect(active.value).to eq('tseT')
end
it 'should not read in a string that is too small' do
expect(active.parse('B')).to eq(0)
expect(active.value).to eq('Test')
end
it 'should be able to read from an offset and only for the given size' do
expect(active.parse('FooBarBaz',3)).to eq(4)
expect(active.value).to eq('BarB')
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/mixlib-authentication-1.4.1/mixlib-authentication.gemspec
|
<filename>.rvm/gems/ruby-2.3.0/gems/mixlib-authentication-1.4.1/mixlib-authentication.gemspec<gh_stars>0
$:.unshift(File.dirname(__FILE__) + "/lib")
require "mixlib/authentication/version"
Gem::Specification.new do |s|
s.name = "mixlib-authentication"
s.version = Mixlib::Authentication::VERSION
s.platform = Gem::Platform::RUBY
s.summary = "Mixes in simple per-request authentication"
s.description = s.summary
s.license = "Apache-2.0"
s.author = "Chef Software, Inc."
s.email = "<EMAIL>"
s.homepage = "https://www.chef.io"
# Uncomment this to add a dependency
s.add_dependency "mixlib-log"
s.require_path = "lib"
s.files = %w{LICENSE README.md Gemfile Rakefile NOTICE} + Dir.glob("*.gemspec") +
Dir.glob("{lib,spec}/**/*", File::FNM_DOTMATCH).reject { |f| File.directory?(f) }
%w{rspec-core rspec-expectations rspec-mocks}.each { |gem| s.add_development_dependency gem, "~> 3.2" }
s.add_development_dependency "chefstyle"
s.add_development_dependency "rake", "~> 10.4"
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/iwidgets/hyperhelp.rb
|
#
# tkextlib/iwidgets/hyperhelp.rb
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tkextlib/iwidgets.rb'
module Tk
module Iwidgets
class Hyperhelp < Tk::Iwidgets::Shell
end
end
end
class Tk::Iwidgets::Hyperhelp
TkCommandNames = ['::iwidgets::hyperhelp'.freeze].freeze
WidgetClassName = 'Hyperhelp'.freeze
WidgetClassNames[WidgetClassName] ||= self
def __strval_optkeys
super() << 'helpdir'
end
private :__strval_optkeys
def __listval_optkeys
super() << 'topics'
end
private :__listval_optkeys
def show_topic(topic)
tk_call(@path, 'showtopic', topic)
self
end
def follow_link(href)
tk_call(@path, 'followlink', href)
self
end
def forward
tk_call(@path, 'forward')
self
end
def back
tk_call(@path, 'back')
self
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/rubyntlm-0.6.0/spec/lib/net/ntlm/version_spec.rb
|
<filename>.rvm/gems/ruby-2.3.0/gems/rubyntlm-0.6.0/spec/lib/net/ntlm/version_spec.rb
require 'spec_helper'
require File.expand_path("#{File.dirname(__FILE__)}/../../../../lib/net/ntlm/version")
describe Net::NTLM::VERSION do
it 'should contain an integer value for Major Version' do
expect(Net::NTLM::VERSION::MAJOR).to be_an Integer
end
it 'should contain an integer value for Minor Version' do
expect(Net::NTLM::VERSION::MINOR).to be_an Integer
end
it 'should contain an integer value for Patch Version' do
expect(Net::NTLM::VERSION::TINY).to be_an Integer
end
it 'should contain an aggregate version string' do
string = [
Net::NTLM::VERSION::MAJOR,
Net::NTLM::VERSION::MINOR,
Net::NTLM::VERSION::TINY
].join('.')
expect(Net::NTLM::VERSION::STRING).to be_a String
expect(Net::NTLM::VERSION::STRING).to eq(string)
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/tkutil/extconf.rb
|
begin
has_tk = compiled?('tk')
rescue NoMethodError
# Probably, called manually (NOT from 'extmk.rb'). Force to make Makefile.
has_tk = true
end
if has_tk
require 'mkmf'
have_func("rb_obj_instance_exec", "ruby.h")
have_func("rb_obj_untrust", "ruby.h")
have_func("rb_obj_taint", "ruby.h")
have_func("rb_sym_to_s", "ruby.h")
have_func("strndup", "string.h")
create_makefile('tkutil')
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/vu.rb
|
#
# The vu widget set support
# by <NAME> (<EMAIL>)
#
require 'tk'
# call setup script for general 'tkextlib' libraries
require 'tkextlib/setup.rb'
# call setup script
require 'tkextlib/vu/setup.rb'
# load package
# TkPackage.require('vu', '2.1')
TkPackage.require('vu')
# autoload
module Tk
module Vu
TkComm::TkExtlibAutoloadModule.unshift(self)
PACKAGE_NAME = 'vu'.freeze
def self.package_name
PACKAGE_NAME
end
def self.package_version
begin
TkPackage.require('vu')
rescue
''
end
end
##########################################
autoload :Dial, 'tkextlib/vu/dial'
autoload :Pie, 'tkextlib/vu/pie'
autoload :PieSlice, 'tkextlib/vu/pie'
autoload :NamedPieSlice, 'tkextlib/vu/pie'
autoload :Spinbox, 'tkextlib/vu/spinbox'
autoload :Bargraph, 'tkextlib/vu/bargraph'
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/gems/did_you_mean-1.0.0/test/edit_distance/jaro_winkler_test.rb
|
<reponame>arnab0073/idea
# -*- coding: utf-8 -*-
require 'test_helper'
class JaroWinklerTest < Minitest::Test
def test_jaro_winkler_distance
assert_distance 0.9667, 'henka', 'henkan'
assert_distance 1.0, 'al', 'al'
assert_distance 0.9611, 'martha', 'marhta'
assert_distance 0.8324, 'jones', 'johnson'
assert_distance 0.9167, 'abcvwxyz', 'zabcvwxy'
assert_distance 0.9583, 'abcvwxyz', 'cabvwxyz'
assert_distance 0.84, 'dwayne', 'duane'
assert_distance 0.8133, 'dixon', 'dicksonx'
assert_distance 0.0, 'fvie', 'ten'
assert_distance 0.9067, 'does_exist', 'doesnt_exist'
assert_distance 1.0, 'x', 'x'
end
def test_jarowinkler_distance_with_utf8_strings
assert_distance 0.9818, '變形金剛4:絕跡重生', '變形金剛4: 絕跡重生'
assert_distance 0.8222, '連勝文', '連勝丼'
assert_distance 0.8222, '馬英九', '馬英丸'
assert_distance 0.6667, '良い', 'いい'
end
private
def assert_distance(score, str1, str2)
assert_equal score, DidYouMean::JaroWinkler.distance(str1, str2).round(4)
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkscrollbox.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkscrollbox.rb<gh_stars>10-100
#
# tkscrollbox.rb - load tk/scrollbox.rb
#
require 'tk/scrollbox'
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/bootstraptest/test_io.rb
|
assert_finish 5, %q{
r, w = IO.pipe
t1 = Thread.new { r.sysread(1) }
t2 = Thread.new { r.sysread(1) }
sleep 0.01 until t1.stop? and t2.stop?
w.write "a"
w.write "a"
}, '[ruby-dev:31866]'
assert_finish 10, %q{
begin
require "io/nonblock"
require "timeout"
timeout(3) do
r, w = IO.pipe
w.nonblock?
w.nonblock = true
w.write_nonblock("a" * 100000)
w.nonblock = false
t1 = Thread.new { w.write("b" * 4096) }
t2 = Thread.new { w.write("c" * 4096) }
sleep 0.5
r.sysread(4096).length
sleep 0.5
r.sysread(4096).length
t1.join
t2.join
end
rescue LoadError, Timeout::Error, NotImplementedError
end
}, '[ruby-dev:32566]'
assert_finish 1, %q{
r, w = IO.pipe
Thread.new {
w << "ab"
sleep 0.01
w << "ab"
}
r.gets("abab")
}
assert_equal 'ok', %q{
require 'tmpdir'
begin
tmpname = "#{Dir.tmpdir}/ruby-btest-#{$$}-#{rand(0x100000000).to_s(36)}"
rw = File.open(tmpname, File::RDWR|File::CREAT|File::EXCL)
rescue Errno::EEXIST
retry
end
save = STDIN.dup
STDIN.reopen(rw)
STDIN.reopen(save)
rw.close
File.unlink(tmpname) unless RUBY_PLATFORM['nacl']
:ok
}
assert_equal 'ok', %q{
require 'tmpdir'
begin
tmpname = "#{Dir.tmpdir}/ruby-btest-#{$$}-#{rand(0x100000000).to_s(36)}"
rw = File.open(tmpname, File::RDWR|File::CREAT|File::EXCL)
rescue Errno::EEXIST
retry
end
save = STDIN.dup
STDIN.reopen(rw)
STDIN.print "a"
STDIN.reopen(save)
rw.close
File.unlink(tmpname) unless RUBY_PLATFORM['nacl']
:ok
}
assert_equal 'ok', %q{
dup = STDIN.dup
dupfd = dup.fileno
dupfd == STDIN.dup.fileno ? :ng : :ok
}, '[ruby-dev:46834]'
assert_normal_exit %q{
ARGF.set_encoding "foo"
}
10.times do
assert_normal_exit %q{
at_exit { p :foo }
megacontent = "abc" * 12345678
#File.open("megasrc", "w") {|f| f << megacontent }
t0 = Thread.main
Thread.new { sleep 0.001 until t0.stop?; Process.kill(:INT, $$) }
r1, w1 = IO.pipe
r2, w2 = IO.pipe
t1 = Thread.new { w1 << megacontent; w1.close }
t2 = Thread.new { r2.read; r2.close }
IO.copy_stream(r1, w2) rescue nil
w2.close
r1.close
t1.join
t2.join
}, 'megacontent-copy_stream', ["INT"], :timeout => 10 or break
end
assert_normal_exit %q{
r, w = IO.pipe
STDOUT.reopen(w)
STDOUT.reopen(__FILE__, "r")
}, '[ruby-dev:38131]'
|
arnab0073/idea
|
.rvm/rubies/ruby-1.9.3-p551/lib/ruby/gems/1.9.1/specifications/bigdecimal-1.1.0.gemspec
|
Gem::Specification.new do |s|
s.name = "bigdecimal"
s.version = "1.1.0"
s.summary = "This bigdecimal is bundled with Ruby"
s.executables = []
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/spec/unit/plugins/fail_spec.rb
|
<filename>.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/spec/unit/plugins/fail_spec.rb
#
# Author:: <NAME> (<EMAIL>>)
# Copyright:: Copyright (c) 2011 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.
#
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '/spec_helper.rb'))
tmp = ENV['TMPDIR'] || ENV['TMP'] || ENV['TEMP'] || '/tmp'
describe Ohai::System, "plugin fail" do
before(:all) do
begin
Dir.mkdir("#{tmp}/plugins")
rescue Errno::EEXIST
# Ignore it
end
fail_plugin=File.open("#{tmp}/plugins/fail.rb","w+")
fail_plugin.write("provides \"fail\"require 'thiswillblowupinyourface'\nk=MissingClassName.new\nfail \"ohnoes\"")
fail_plugin.close
real_plugin=File.open("#{tmp}/plugins/real.rb","w+")
real_plugin.write("provides \"real\"\nreal \"useful\"\n")
real_plugin.close
@plugin_path=Ohai::Config[:plugin_path]
end
before(:each) do
Ohai::Config[:plugin_path]=["#{tmp}/plugins"]
@ohai=Ohai::System.new
end
after(:all) do
File.delete("#{tmp}/plugins/fail.rb")
File.delete("#{tmp}/plugins/real.rb")
begin
Dir.delete("#{tmp}/plugins")
rescue
# Don't care if it fails
end
Ohai::Config[:plugin_path]=@plugin_path
end
it "should continue gracefully if plugin loading fails" do
@ohai.require_plugin("fail")
@ohai.require_plugin("real")
@ohai.data[:real].should eql("useful")
@ohai.data.should_not have_key("fail")
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/specifications/mixlib-log-1.6.0.gemspec
|
# -*- encoding: utf-8 -*-
# stub: mixlib-log 1.6.0 ruby lib
Gem::Specification.new do |s|
s.name = "mixlib-log"
s.version = "1.6.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib"]
s.authors = ["Opscode, Inc."]
s.date = "2013-04-02"
s.email = "<EMAIL>"
s.extra_rdoc_files = ["README.rdoc", "LICENSE", "NOTICE"]
s.files = ["LICENSE", "NOTICE", "README.rdoc"]
s.homepage = "http://www.opscode.com"
s.rubygems_version = "2.5.1"
s.summary = "A gem that provides a simple mixin for log functionality"
s.installed_by_version = "2.5.1" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<rake>, [">= 0"])
s.add_development_dependency(%q<rspec>, ["~> 2.10"])
s.add_development_dependency(%q<cucumber>, [">= 0"])
else
s.add_dependency(%q<rake>, [">= 0"])
s.add_dependency(%q<rspec>, ["~> 2.10"])
s.add_dependency(%q<cucumber>, [">= 0"])
end
else
s.add_dependency(%q<rake>, [">= 0"])
s.add_dependency(%q<rspec>, ["~> 2.10"])
s.add_dependency(%q<cucumber>, [">= 0"])
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/rubyntlm-0.6.0/examples/imap.rb
|
# $Id: imap.rb,v 1.1 2006/10/05 01:36:52 koheik Exp $
require "net/imap"
$:.unshift(File.dirname(__FILE__) + '/../lib')
require "net/ntlm"
Net::IMAP::debug = true
$host = "localhost"
$port = 143
$ssl = false
$user = nil
$passwd = <PASSWORD>
module Net
class IMAP
class NtlmAuthenticator
def process(data)
case @state
when 1
@state = 2
t1 = Net::NTLM::Message::Type1.new()
return t1.serialize
when 2
@state = 3
t2 = Net::NTLM::Message.parse(data)
t3 = t2.response({:user => @user, :password => <PASSWORD>}, {:ntlmv2 => (@ntlm_type == "ntlmv2")})
return t3.serialize
end
end
private
def initialize(user, password, ntlm_type = "ntlmv2")
@user = user
@password = password
@ntlm_type = @ntlm_type
@state = 1
end
end
add_authenticator "NTLM", NtlmAuthenticator
class ResponseParser
def continue_req
match(T_PLUS)
if lookahead.symbol == T_CRLF # means empty message
return ContinuationRequest.new(ResponseText.new(nil, ""), @str)
end
match(T_SPACE)
return ContinuationRequest.new(resp_text, @str)
end
end
end
end
unless $user and $passwd
print "User name: "
($user = $stdin.readline).chomp!
print "Password: "
($passwd = $stdin.readline).chomp!
end
imap = Net::IMAP.new($host, $port, $ssl)
imap.authenticate("NTLM", $user, $passwd)
imap.examine("Inbox")
# imap.search(["RECENT"]).each do |message_id|
# envelope = imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"]
# from = envelope.from.nil? ? "" : envelope.from[0].name
# subject = envelope.subject
# puts "#{message_id} #{from}: \t#{subject}"
# end
imap.logout
# imap.disconnect
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/ruby/test_iseq.rb
|
require 'test/unit'
class TestISeq < Test::Unit::TestCase
ISeq = RubyVM::InstructionSequence
def test_no_linenum
bug5894 = '[ruby-dev:45130]'
assert_normal_exit('p RubyVM::InstructionSequence.compile("1", "mac", "", 0).to_a', bug5894)
end
def compile(src, line = nil, opt = nil)
RubyVM::InstructionSequence.new(src, __FILE__, __FILE__, line, opt)
end
def lines src
body = compile(src).to_a[13]
body.find_all{|e| e.kind_of? Fixnum}
end
def test_to_a_lines
src = <<-EOS
p __LINE__ # 1
p __LINE__ # 2
# 3
p __LINE__ # 4
EOS
assert_equal [1, 2, 4], lines(src)
src = <<-EOS
# 1
p __LINE__ # 2
# 3
p __LINE__ # 4
# 5
EOS
assert_equal [2, 4], lines(src)
src = <<-EOS
1 # should be optimized out
2 # should be optimized out
p __LINE__ # 3
p __LINE__ # 4
5 # should be optimized out
6 # should be optimized out
p __LINE__ # 7
8 # should be optimized out
9
EOS
assert_equal [3, 4, 7, 9], lines(src)
end
def test_unsupport_type
ary = RubyVM::InstructionSequence.compile("p").to_a
ary[9] = :foobar
assert_raise_with_message(TypeError, /:foobar/) {RubyVM::InstructionSequence.load(ary)}
end if defined?(RubyVM::InstructionSequence.load)
def test_loaded_cdhash_mark
iseq = compile(<<-'end;', __LINE__+1)
def bug(kw)
case kw
when "false" then false
when "true" then true
when "nil" then nil
else raise("unhandled argument: #{kw.inspect}")
end
end
end;
assert_separately([], <<-"end;")
iseq = #{iseq.to_a.inspect}
RubyVM::InstructionSequence.load(iseq).eval
assert_equal(false, bug("false"))
GC.start
assert_equal(false, bug("false"))
end;
end if defined?(RubyVM::InstructionSequence.load)
def test_disasm_encoding
src = "\u{3042} = 1; \u{3042}; \u{3043}"
asm = compile(src).disasm
assert_equal(src.encoding, asm.encoding)
assert_predicate(asm, :valid_encoding?)
src.encode!(Encoding::Shift_JIS)
asm = compile(src).disasm
assert_equal(src.encoding, asm.encoding)
assert_predicate(asm, :valid_encoding?)
end
LINE_BEFORE_METHOD = __LINE__
def method_test_line_trace
a = 1
b = 2
end
def test_line_trace
iseq = ISeq.compile \
%q{ a = 1
b = 2
c = 3
# d = 4
e = 5
# f = 6
g = 7
}
assert_equal([1, 2, 3, 5, 7], iseq.line_trace_all)
iseq.line_trace_specify(1, true) # line 2
iseq.line_trace_specify(3, true) # line 5
result = []
TracePoint.new(:specified_line){|tp|
result << tp.lineno
}.enable{
iseq.eval
}
assert_equal([2, 5], result)
iseq = ISeq.of(self.class.instance_method(:method_test_line_trace))
assert_equal([LINE_BEFORE_METHOD + 3, LINE_BEFORE_METHOD + 5], iseq.line_trace_all)
end if false # TODO: now, it is only for C APIs.
LINE_OF_HERE = __LINE__
def test_location
iseq = ISeq.of(method(:test_location))
assert_equal(__FILE__, iseq.path)
assert_match(/#{__FILE__}/, iseq.absolute_path)
assert_equal("test_location", iseq.label)
assert_equal("test_location", iseq.base_label)
assert_equal(LINE_OF_HERE+1, iseq.first_lineno)
line = __LINE__
iseq = ISeq.of(Proc.new{})
assert_equal(__FILE__, iseq.path)
assert_match(/#{__FILE__}/, iseq.absolute_path)
assert_equal("test_location", iseq.base_label)
assert_equal("block in test_location", iseq.label)
assert_equal(line+1, iseq.first_lineno)
end
def test_label_fstring
c = Class.new{ def foobar() end }
a, b = eval("# encoding: us-ascii\n'foobar'.freeze"),
ISeq.of(c.instance_method(:foobar)).label
assert_same a, b
end
def test_disable_opt
src = "a['foo'] = a['bar']; 'a'.freeze"
body= compile(src, __LINE__, false).to_a[13]
body.each{|insn|
next unless Array === insn
op = insn.first
assert(!op.to_s.match(/^opt_/), "#{op}")
}
end
def test_invalid_source
bug11159 = '[ruby-core:69219] [Bug #11159]'
assert_raise(TypeError, bug11159) {ISeq.compile(nil)}
assert_raise(TypeError, bug11159) {ISeq.compile(:foo)}
assert_raise(TypeError, bug11159) {ISeq.compile(1)}
end
def test_frozen_string_literal_compile_option
$f = 'f'
line = __LINE__ + 2
code = <<-'EOS'
['foo', 'foo', "#{$f}foo", "#{'foo'}"]
EOS
s1, s2, s3, s4 = compile(code, line, {frozen_string_literal: true}).eval
assert_predicate(s1, :frozen?)
assert_predicate(s2, :frozen?)
assert_predicate(s3, :frozen?)
assert_predicate(s4, :frozen?)
end
def test_safe_call_chain
src = "a&.a&.a&.a&.a&.a"
body = compile(src, __LINE__, {peephole_optimization: true}).to_a[13]
labels = body.select {|op, arg| op == :branchnil}.map {|op, arg| arg}
assert_equal(1, labels.uniq.size)
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/lib/ohai/plugins/linux/network.rb
|
#
# Author:: <NAME> (<<EMAIL>>)
# Copyright:: Copyright (c) 2008 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.
#
require 'ipaddr'
provides "network", "counters/network"
def encaps_lookup(encap)
return "Loopback" if encap.eql?("Local Loopback") || encap.eql?("loopback")
return "PPP" if encap.eql?("Point-to-Point Protocol")
return "SLIP" if encap.eql?("Serial Line IP")
return "VJSLIP" if encap.eql?("VJ Serial Line IP")
return "IPIP" if encap.eql?("IPIP Tunnel")
return "6to4" if encap.eql?("IPv6-in-IPv4")
return "Ethernet" if encap.eql?("ether")
encap
end
iface = Mash.new
net_counters = Mash.new
# Match the lead line for an interface from iproute2
# 3: eth0.11@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP
# The '@eth0:' portion doesn't exist on primary interfaces and thus is optional in the regex
IPROUTE_INT_REGEX = /^(\d+): ([0-9a-zA-Z@:\.\-_]*?)(@[0-9a-zA-Z]+|):\s/
if File.exist?("/sbin/ip")
# families to get default routes from
families = [
{
:name => "inet",
:default_route => "0.0.0.0/0",
:default_prefix => :default,
:neighbour_attribute => :arp
},
{
:name => "inet6",
:default_route => "::/0",
:default_prefix => :default_inet6,
:neighbour_attribute => :neighbour_inet6
}
]
popen4("ip addr") do |pid, stdin, stdout, stderr|
stdin.close
cint = nil
stdout.each do |line|
if line =~ IPROUTE_INT_REGEX
cint = $2
iface[cint] = Mash.new
if cint =~ /^(\w+)(\d+.*)/
iface[cint][:type] = $1
iface[cint][:number] = $2
end
if line =~ /mtu (\d+)/
iface[cint][:mtu] = $1
end
flags = line.scan(/(UP|BROADCAST|DEBUG|LOOPBACK|POINTTOPOINT|NOTRAILERS|LOWER_UP|NOARP|PROMISC|ALLMULTI|SLAVE|MASTER|MULTICAST|DYNAMIC)/)
if flags.length > 1
iface[cint][:flags] = flags.flatten.uniq
end
end
if line =~ /link\/(\w+) ([\da-f\:]+) /
iface[cint][:encapsulation] = encaps_lookup($1)
unless $2 == "00:00:00:00:00:00"
iface[cint][:addresses] = Mash.new unless iface[cint][:addresses]
iface[cint][:addresses][$2.upcase] = { "family" => "lladdr" }
end
end
if line =~ /inet (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(\/(\d{1,2}))?/
tmp_addr, tmp_prefix = $1, $3
tmp_prefix ||= "32"
original_int = nil
# Are we a formerly aliased interface?
if line =~ /#{cint}:(\d+)$/
sub_int = $1
alias_int = "#{cint}:#{sub_int}"
original_int = cint
cint = alias_int
end
iface[cint] = Mash.new unless iface[cint] # Create the fake alias interface if needed
iface[cint][:addresses] = Mash.new unless iface[cint][:addresses]
iface[cint][:addresses][tmp_addr] = { "family" => "inet", "prefixlen" => tmp_prefix }
iface[cint][:addresses][tmp_addr][:netmask] = IPAddr.new("255.255.255.255").mask(tmp_prefix.to_i).to_s
if line =~ /peer (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/
iface[cint][:addresses][tmp_addr][:peer] = $1
end
if line =~ /brd (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/
iface[cint][:addresses][tmp_addr][:broadcast] = $1
end
if line =~ /scope (\w+)/
iface[cint][:addresses][tmp_addr][:scope] = ($1.eql?("host") ? "Node" : $1.capitalize)
end
# If we found we were an an alias interface, restore cint to its original value
cint = original_int unless original_int.nil?
end
if line =~ /inet6 ([a-f0-9\:]+)\/(\d+) scope (\w+)/
iface[cint][:addresses] = Mash.new unless iface[cint][:addresses]
tmp_addr = $1
iface[cint][:addresses][tmp_addr] = { "family" => "inet6", "prefixlen" => $2, "scope" => ($3.eql?("host") ? "Node" : $3.capitalize) }
end
end
end
popen4("ip -d -s link") do |pid, stdin, stdout, stderr|
stdin.close
tmp_int = nil
on_rx = true
stdout.each do |line|
if line =~ IPROUTE_INT_REGEX
tmp_int = $2
net_counters[tmp_int] = Mash.new unless net_counters[tmp_int]
end
if line =~ /(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/
int = on_rx ? :rx : :tx
net_counters[tmp_int][int] = Mash.new unless net_counters[tmp_int][int]
net_counters[tmp_int][int][:bytes] = $1
net_counters[tmp_int][int][:packets] = $2
net_counters[tmp_int][int][:errors] = $3
net_counters[tmp_int][int][:drop] = $4
if(int == :rx)
net_counters[tmp_int][int][:overrun] = $5
else
net_counters[tmp_int][int][:carrier] = $5
net_counters[tmp_int][int][:collisions] = $6
end
on_rx = !on_rx
end
if line =~ /qlen (\d+)/
net_counters[tmp_int][:tx] = Mash.new unless net_counters[tmp_int][:tx]
net_counters[tmp_int][:tx][:queuelen] = $1
end
if line =~ /vlan id (\d+)/
tmp_id = $1
iface[tmp_int][:vlan] = Mash.new unless iface[tmp_int][:vlan]
iface[tmp_int][:vlan][:id] = tmp_id
vlan_flags = line.scan(/(REORDER_HDR|GVRP|LOOSE_BINDING)/)
if vlan_flags.length > 0
iface[tmp_int][:vlan][:flags] = vlan_flags.flatten.uniq
end
end
if line =~ /state (\w+)/
iface[tmp_int]['state'] = $1.downcase
end
end
end
families.each do |family|
neigh_attr = family[:neighbour_attribute]
default_prefix = family[:default_prefix]
popen4("ip -f #{family[:name]} neigh show") do |pid, stdin, stdout, stderr|
stdin.close
stdout.each do |line|
if line =~ /^([a-f0-9\:\.]+)\s+dev\s+([^\s]+)\s+lladdr\s+([a-fA-F0-9\:]+)/
unless iface[$2]
Ohai::Log.warn("neighbour list has entries for unknown interface #{iface[$2]}")
next
end
iface[$2][neigh_attr] = Mash.new unless iface[$2][neigh_attr]
iface[$2][neigh_attr][$1] = $3.downcase
end
end
end
# checking the routing tables
# why ?
# 1) to set the default gateway and default interfaces attributes
# 2) on some occasions, the best way to select node[:ipaddress] is to look at
# the routing table source field.
# 3) and since we're at it, let's populate some :routes attributes
# (going to do that for both inet and inet6 addresses)
popen4("ip -f #{family[:name]} route show") do |pid, stdin, stdout, stderr|
stdin.close
stdout.each do |line|
if line =~ /^([^\s]+)\s(.*)$/
route_dest = $1
route_ending = $2
#
if route_ending =~ /\bdev\s+([^\s]+)\b/
route_int = $1
else
Ohai::Log.debug("Skipping route entry without a device: '#{line}'")
next
end
unless iface[route_int]
Ohai::Log.debug("Skipping previously unseen interface from 'ip route show': #{route_int}")
next
end
route_entry = Mash.new( :destination => route_dest,
:family => family[:name] )
%w[via scope metric proto src].each do |k|
route_entry[k] = $1 if route_ending =~ /\b#{k}\s+([^\s]+)\b/
end
# a sanity check, especially for Linux-VServer, OpenVZ and LXC:
# don't report the route entry if the src address isn't set on the node
next if route_entry[:src] and not iface[route_int][:addresses].has_key? route_entry[:src]
iface[route_int][:routes] = Array.new unless iface[route_int][:routes]
iface[route_int][:routes] << route_entry
end
end
end
# now looking at the routes to set the default attributes
# for information, default routes can be of this form :
# - default via 10.0.2.4 dev br0
# - default dev br0 scope link
# - default via 10.0.3.1 dev eth1 src 10.0.3.2 metric 10
# - default via 10.0.4.1 dev eth2 src 10.0.4.2 metric 20
# using a temporary var to hold routes and their interface name
routes = iface.collect do |i,iv|
iv[:routes].collect do |r|
r.merge(:dev=>i) if r[:family] == family[:name]
end.compact if iv[:routes]
end.compact.flatten
# using a temporary var to hold the default route
# in case there are more than 1 default route, sort it by its metric
# and return the first one
# (metric value when unspecified is 0)
default_route = routes.select do |r|
r[:destination] == "default"
end.sort do |x,y|
(x[:metric].nil? ? 0 : x[:metric].to_i) <=> (y[:metric].nil? ? 0 : y[:metric].to_i)
end.first
if default_route.nil? or default_route.empty?
Ohai::Log.debug("Unable to determine default #{family[:name]} interface")
else
network["#{default_prefix}_interface"] = default_route[:dev]
Ohai::Log.debug("#{default_prefix}_interface set to #{default_route[:dev]}")
# setting gateway to 0.0.0.0 or :: if the default route is a link level one
network["#{default_prefix}_gateway"] = default_route[:via] ? default_route[:via] : family[:default_route].chomp("/0")
Ohai::Log.debug("#{default_prefix}_gateway set to #{network["#{default_prefix}_gateway"]}")
# since we're at it, let's populate {ip,mac,ip6}address with the best values
# using the source field when it's specified :
# 1) in the default route
# 2) in the route entry used to reach the default gateway
route = routes.select do |r|
# selecting routes
r[:src] and # it has a src field
iface[r[:dev]] and # the iface exists
iface[r[:dev]][:addresses].has_key? r[:src] and # the src ip is set on the node
iface[r[:dev]][:addresses][r[:src]][:scope].downcase != "link" and # this isn't a link level addresse
( r[:destination] == "default" or
( default_route[:via] and # the default route has a gateway
IPAddress(r[:destination]).include? IPAddress(default_route[:via]) # the route matches the gateway
)
)
end.sort_by do |r|
# sorting the selected routes:
# - getting default routes first
# - then sort by metric
# - then by prefixlen
[
r[:destination] == "default" ? 0 : 1,
r[:metric].nil? ? 0 : r[:metric].to_i,
# for some reason IPAddress doesn't accept "::/0", it doesn't like prefix==0
# just a quick workaround: use 0 if IPAddress fails
begin
IPAddress( r[:destination] == "default" ? family[:default_route] : r[:destination] ).prefix
rescue
0
end
]
end.first
unless route.nil? or route.empty?
if family[:name] == "inet"
ipaddress route[:src]
macaddress iface[route[:dev]][:addresses].select{|k,v| v["family"]=="lladdr"}.first.first unless iface[route[:dev]][:flags].include? "NOARP"
else
ip6address route[:src]
end
end
end
end
else
begin
route_result = from("route -n \| grep -m 1 ^0.0.0.0").split(/[ \t]+/)
network[:default_gateway], network[:default_interface] = route_result.values_at(1,7)
rescue Ohai::Exceptions::Exec
Ohai::Log.debug("Unable to determine default interface")
end
popen4("ifconfig -a") do |pid, stdin, stdout, stderr|
stdin.close
cint = nil
stdout.each do |line|
tmp_addr = nil
# dev_valid_name in the kernel only excludes slashes, nulls, spaces
# http://git.kernel.org/?p=linux/kernel/git/stable/linux-stable.git;a=blob;f=net/core/dev.c#l851
if line =~ /^([0-9a-zA-Z@\.\:\-_]+)\s+/
cint = $1
iface[cint] = Mash.new
if cint =~ /^(\w+)(\d+.*)/
iface[cint][:type] = $1
iface[cint][:number] = $2
end
end
if line =~ /Link encap:(Local Loopback)/ || line =~ /Link encap:(.+?)\s/
iface[cint][:encapsulation] = encaps_lookup($1)
end
if line =~ /HWaddr (.+?)\s/
iface[cint][:addresses] = Mash.new unless iface[cint][:addresses]
iface[cint][:addresses][$1] = { "family" => "lladdr" }
end
if line =~ /inet addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/
iface[cint][:addresses] = Mash.new unless iface[cint][:addresses]
iface[cint][:addresses][$1] = { "family" => "inet" }
tmp_addr = $1
end
if line =~ /inet6 addr: ([a-f0-9\:]+)\/(\d+) Scope:(\w+)/
iface[cint][:addresses] = Mash.new unless iface[cint][:addresses]
iface[cint][:addresses][$1] = { "family" => "inet6", "prefixlen" => $2, "scope" => ($3.eql?("Host") ? "Node" : $3) }
end
if line =~ /Bcast:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/
iface[cint][:addresses][tmp_addr]["broadcast"] = $1
end
if line =~ /Mask:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/
iface[cint][:addresses][tmp_addr]["netmask"] = $1
end
flags = line.scan(/(UP|BROADCAST|DEBUG|LOOPBACK|POINTTOPOINT|NOTRAILERS|RUNNING|NOARP|PROMISC|ALLMULTI|SLAVE|MASTER|MULTICAST|DYNAMIC)\s/)
if flags.length > 1
iface[cint][:flags] = flags.flatten
end
if line =~ /MTU:(\d+)/
iface[cint][:mtu] = $1
end
if line =~ /P-t-P:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/
iface[cint][:peer] = $1
end
if line =~ /RX packets:(\d+) errors:(\d+) dropped:(\d+) overruns:(\d+) frame:(\d+)/
net_counters[cint] = Mash.new unless net_counters[cint]
net_counters[cint][:rx] = { "packets" => $1, "errors" => $2, "drop" => $3, "overrun" => $4, "frame" => $5 }
end
if line =~ /TX packets:(\d+) errors:(\d+) dropped:(\d+) overruns:(\d+) carrier:(\d+)/
net_counters[cint][:tx] = { "packets" => $1, "errors" => $2, "drop" => $3, "overrun" => $4, "carrier" => $5 }
end
if line =~ /collisions:(\d+)/
net_counters[cint][:tx]["collisions"] = $1
end
if line =~ /txqueuelen:(\d+)/
net_counters[cint][:tx]["queuelen"] = $1
end
if line =~ /RX bytes:(\d+) \((\d+?\.\d+ .+?)\)/
net_counters[cint][:rx]["bytes"] = $1
end
if line =~ /TX bytes:(\d+) \((\d+?\.\d+ .+?)\)/
net_counters[cint][:tx]["bytes"] = $1
end
end
end
popen4("arp -an") do |pid, stdin, stdout, stderr|
stdin.close
stdout.each do |line|
if line =~ /^\S+ \((\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\) at ([a-fA-F0-9\:]+) \[(\w+)\] on ([0-9a-zA-Z\.\:\-]+)/
next unless iface[$4] # this should never happen
iface[$4][:arp] = Mash.new unless iface[$4][:arp]
iface[$4][:arp][$1] = $2.downcase
end
end
end
end
counters[:network][:interfaces] = net_counters
network["interfaces"] = iface
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/knife-windows-1.4.1/lib/chef/knife/winrm_knife_base.rb
|
#
# Author:: <NAME> (<<EMAIL>)
# Copyright:: Copyright (c) 2015-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 'chef/knife'
require 'chef/knife/winrm_base'
require 'chef/knife/winrm_shared_options'
require 'chef/knife/knife_windows_base'
class Chef
class Knife
module WinrmCommandSharedFunctions
FAILED_BASIC_HINT ||= "Hint: Please check winrm configuration 'winrm get winrm/config/service' AllowUnencrypted flag on remote server."
FAILED_NOT_BASIC_HINT ||= <<-eos.gsub /^\s+/, ""
Hint: Make sure to prefix domain usernames with the correct domain name.
Hint: Local user names should be prefixed with computer name or IP address.
EXAMPLE: my_domain\\user_namer
eos
def self.included(includer)
includer.class_eval do
@@ssl_warning_given = false
include Chef::Knife::WinrmBase
include Chef::Knife::WinrmSharedOptions
include Chef::Knife::KnifeWindowsBase
def validate_winrm_options!
winrm_auth_protocol = locate_config_value(:winrm_authentication_protocol)
if ! Chef::Knife::WinrmBase::WINRM_AUTH_PROTOCOL_LIST.include?(winrm_auth_protocol)
ui.error "Invalid value '#{winrm_auth_protocol}' for --winrm-authentication-protocol option."
ui.info "Valid values are #{Chef::Knife::WinrmBase::WINRM_AUTH_PROTOCOL_LIST.join(",")}."
exit 1
end
warn_no_ssl_peer_verification if resolve_no_ssl_peer_verification
end
#Overrides Chef::Knife#configure_session, as that code is tied to the SSH implementation
#Tracked by Issue # 3042 / https://github.com/chef/chef/issues/3042
def configure_session
validate_winrm_options!
resolve_session_options
resolve_target_nodes
session_from_list
end
def resolve_target_nodes
@list = case config[:manual]
when true
@name_args[0].split(" ")
when false
r = Array.new
q = Chef::Search::Query.new
@action_nodes = q.search(:node, @name_args[0])[0]
@action_nodes.each do |item|
i = extract_nested_value(item, config[:attribute])
r.push(i) unless i.nil?
end
r
end
if @list.length == 0
if @action_nodes.length == 0
ui.fatal("No nodes returned from search!")
else
ui.fatal("#{@action_nodes.length} #{@action_nodes.length > 1 ? "nodes":"node"} found, " +
"but does not have the required attribute (#{config[:attribute]}) to establish the connection. " +
"Try setting another attribute to open the connection using --attribute.")
end
exit 10
end
end
# TODO: Copied from Knife::Core:GenericPresenter. Should be extracted
def extract_nested_value(data, nested_value_spec)
nested_value_spec.split(".").each do |attr|
if data.nil?
nil # don't get no method error on nil
elsif data.respond_to?(attr.to_sym)
data = data.send(attr.to_sym)
elsif data.respond_to?(:[])
data = data[attr]
else
data = begin
data.send(attr.to_sym)
rescue NoMethodError
nil
end
end
end
( !data.kind_of?(Array) && data.respond_to?(:to_hash) ) ? data.to_hash : data
end
def run_command(command = '')
relay_winrm_command(command)
check_for_errors!
# Knife seems to ignore the return value of this method,
# so we exit to force the process exit code for this
# subcommand if returns is set
exit @exit_code if @exit_code && @exit_code != 0
0
end
def relay_winrm_command(command)
Chef::Log.debug(command)
session_results = []
@winrm_sessions.each do |s|
begin
session_results << s.relay_command(command)
rescue WinRM::WinRMHTTPTransportError, WinRM::WinRMAuthorizationError => e
if authorization_error?(e)
if ! config[:suppress_auth_failure]
# Display errors if the caller hasn't opted to retry
ui.error "Failed to authenticate to #{s.host} as #{locate_config_value(:winrm_user)}"
ui.info "Response: #{e.message}"
ui.info get_failed_authentication_hint
raise e
end
@exit_code = 401
else
raise e
end
end
end
session_results
end
private
def get_failed_authentication_hint
if @session_opts[:basic_auth_only]
FAILED_BASIC_HINT
else
FAILED_NOT_BASIC_HINT
end
end
def authorization_error?(exception)
exception.is_a?(WinRM::WinRMAuthorizationError) ||
exception.message =~ /401/
end
def check_for_errors!
@winrm_sessions.each do |session|
session_exit_code = session.exit_code
unless success_return_codes.include? session_exit_code.to_i
@exit_code = session_exit_code.to_i
ui.error "Failed to execute command on #{session.host} return code #{session_exit_code}"
end
end
end
def success_return_codes
#Redundant if the CLI options parsing occurs
return [0] unless config[:returns]
return @success_return_codes ||= config[:returns].split(',').collect {|item| item.to_i}
end
def session_from_list
@list.each do |item|
Chef::Log.debug("Adding #{item}")
@session_opts[:host] = item
create_winrm_session(@session_opts)
end
end
def create_winrm_session(options={})
session = Chef::Knife::WinrmSession.new(options)
@winrm_sessions ||= []
@winrm_sessions.push(session)
end
def resolve_session_options
@session_opts = {
user: resolve_winrm_user,
password: locate_config_value(:winrm_password),
port: locate_config_value(:winrm_port),
operation_timeout: resolve_winrm_session_timeout,
basic_auth_only: resolve_winrm_basic_auth,
disable_sspi: resolve_winrm_disable_sspi,
transport: resolve_winrm_transport,
no_ssl_peer_verification: resolve_no_ssl_peer_verification,
ssl_peer_fingerprint: resolve_ssl_peer_fingerprint
}
if @session_opts[:user] and (not @session_opts[:password])
@session_opts[:password] = Chef::Config[:knife][:winrm_password] = config[:winrm_password] = get_password
end
if @session_opts[:transport] == :kerberos
@session_opts.merge!(resolve_winrm_kerberos_options)
end
@session_opts[:ca_trust_path] = locate_config_value(:ca_trust_file) if locate_config_value(:ca_trust_file)
end
def resolve_winrm_user
user = locate_config_value(:winrm_user)
# Prefixing with '.\' when using negotiate
# to auth user against local machine domain
if resolve_winrm_basic_auth ||
resolve_winrm_transport == :kerberos ||
user.include?("\\") ||
user.include?("@")
user
else
".\\#{user}"
end
end
def resolve_winrm_session_timeout
#30 min (Default) OperationTimeout for long bootstraps fix for KNIFE_WINDOWS-8
locate_config_value(:session_timeout).to_i * 60 if locate_config_value(:session_timeout)
end
def resolve_winrm_basic_auth
locate_config_value(:winrm_authentication_protocol) == "basic"
end
def resolve_winrm_kerberos_options
kerberos_opts = {}
kerberos_opts[:keytab] = locate_config_value(:kerberos_keytab_file) if locate_config_value(:kerberos_keytab_file)
kerberos_opts[:realm] = locate_config_value(:kerberos_realm) if locate_config_value(:kerberos_realm)
kerberos_opts[:service] = locate_config_value(:kerberos_service) if locate_config_value(:kerberos_service)
kerberos_opts
end
def resolve_winrm_transport
transport = locate_config_value(:winrm_transport).to_sym
if config.any? {|k,v| k.to_s =~ /kerberos/ && !v.nil? }
transport = :kerberos
elsif transport != :ssl && negotiate_auth?
transport = :negotiate
end
transport
end
def resolve_no_ssl_peer_verification
locate_config_value(:ca_trust_file).nil? && config[:winrm_ssl_verify_mode] == :verify_none && resolve_winrm_transport == :ssl
end
def resolve_ssl_peer_fingerprint
locate_config_value(:ssl_peer_fingerprint)
end
def resolve_winrm_disable_sspi
resolve_winrm_transport != :negotiate
end
def get_password
@password ||= ui.ask("Enter your password: ") { |q| q.echo = false }
end
def negotiate_auth?
locate_config_value(:winrm_authentication_protocol) == "negotiate"
end
def warn_no_ssl_peer_verification
if ! @@ssl_warning_given
@@ssl_warning_given = true
ui.warn(<<-WARN)
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
SSL validation of HTTPS requests for the WinRM transport is disabled. HTTPS WinRM
connections are still encrypted, but knife is not able to detect forged replies
or spoofing attacks.
To fix this issue add an entry like this to your knife configuration file:
```
# Verify all WinRM HTTPS connections (default, recommended)
knife[:winrm_ssl_verify_mode] = :verify_peer
```
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
WARN
end
end
end
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/win32ole/sample/ieconst.rb
|
require 'win32ole'
ie = WIN32OLE.new('InternetExplorer.Application')
=begin
WIN32OLE.const_load(ie)
WIN32OLE.constants.sort.each do |c|
puts "#{c} = #{WIN32OLE.const_get(c)}"
end
=end
module IE_CONST
end
WIN32OLE.const_load(ie, IE_CONST)
IE_CONST.constants.sort.each do |c|
puts "#{c} = #{IE_CONST.const_get(c)}"
end
#------------------------------------------------------------
# Remark!!! CONSTANTS has not tested enoughly!!!
# CONSTANTS is alpha release.
# If there are constants which first letter is not [a-zA-Z],
# like a '_Foo', then maybe you can access the value by
# using CONSTANTS['_Foo']
#------------------------------------------------------------
IE_CONST::CONSTANTS.each do |k, v|
puts "#{k} = #{v}"
end
puts WIN32OLE::VERSION
ie.quit
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.