repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/rubyntlm-0.6.0/spec/lib/net/ntlm/message/type3_spec.rb
<filename>.rvm/gems/ruby-2.3.0/gems/rubyntlm-0.6.0/spec/lib/net/ntlm/message/type3_spec.rb require 'spec_helper' describe Net::NTLM::Message::Type3 do fields = [ { :name => :sign, :class => Net::NTLM::String, :value => Net::NTLM::SSP_SIGN, :active => true }, { :name => :type, :class => Net::NTLM::Int32LE, :value => 3, :active => true }, { :name => :lm_response, :class => Net::NTLM::SecurityBuffer, :value => '', :active => true }, { :name => :ntlm_response, :class => Net::NTLM::SecurityBuffer, :value => '', :active => true }, { :name => :domain, :class => Net::NTLM::SecurityBuffer, :value => '', :active => true }, { :name => :user, :class => Net::NTLM::SecurityBuffer, :value => '', :active => true }, { :name => :workstation, :class => Net::NTLM::SecurityBuffer, :value => '', :active => true }, { :name => :session_key, :class => Net::NTLM::SecurityBuffer, :value => '', :active => false }, { :name => :flag, :class => Net::NTLM::Int32LE, :value => 0, :active => false }, ] flags = [] it_behaves_like 'a fieldset', fields it_behaves_like 'a message', flags describe '.parse' do subject(:message) { described_class.parse(data) } context 'with NTLMv2 data' do let(:data) do # Captured NTLMSSP blob from smbclient with username 'administrator' # and a blank password, i.e.: # smbclient -U 'administrator%' -L //192.168.100.140/ [ '4e544c4d53535000030000001800180040000000c400c4005800000012001200' \ '1c0100001a001a002e0100001a001a0048010000100010006201000015820860' \ 'ced203d860b80c7350050754b238202a8c1c63134f0ae0f086a3fb147e8b2f9f' \ 'de3ef1b1b43c83dc010100000000000080512dba020ed0011c5bc2c8339fd29a' \ '0000000002001e00570049004e002d00420035004a004e003300520048004700' \ '46003300310001001e00570049004e002d00420035004a004e00330052004800' \ '470046003300310004001e00570049004e002d00420035004a004e0033005200' \ '4800470046003300310003001e00570049004e002d00420035004a004e003300' \ '52004800470046003300310007000800a209e5ba020ed0010000000057004f00' \ '52004b00470052004f0055005000610064006d0069006e006900730074007200' \ '610074006f0072004100550053002d004c004500450054002d00310030003300' \ '31007036615cd6d9b19a685ded4312311cd7' ].pack('H*') end let(:server_challenge) { ['f588469dc96fe809'].pack('H*') } it 'should set the magic' do expect(message.sign).to eql(Net::NTLM::SSP_SIGN) end it 'should set the type' do expect(message.type).to eq(3) end it 'should set the LM response' do lm_response = ['ced203d860b80c7350050754b238202a8c1c63134f0ae0f0'].pack('H*') expect(message.lm_response).to eq(lm_response) end it 'should set the NTLM response' do ntlm_response = [ '86a3fb147e8b2f9fde3ef1b1b43c83dc010100000000000080512dba020ed001' \ '1c5bc2c8339fd29a0000000002001e00570049004e002d00420035004a004e00' \ '330052004800470046003300310001001e00570049004e002d00420035004a00' \ '4e00330052004800470046003300310004001e00570049004e002d0042003500' \ '4a004e00330052004800470046003300310003001e00570049004e002d004200' \ '35004a004e00330052004800470046003300310007000800a209e5ba020ed001' \ '00000000' ].pack('H*') expect(message.ntlm_response).to eq(ntlm_response) end it 'should set the user' do # administrator user = ['610064006d0069006e006900730074007200610074006f007200'].pack('H*') expect(message.user).to eq(user) end it 'should set the domain' do # WORKGROUP domain = ['57004f0052004b00470052004f0055005000'].pack('H*') expect(message.domain).to eq(domain) end it 'should set the workstation' do # AUS-LEET-1031 workstation = ['4100550053002d004c004500450054002d003100300033003100'].pack('H*') expect(message.workstation).to eq(workstation) end it 'should set the session key' do session_key = ['7036615cd6d9b19a685ded4312311cd7'].pack('H*') expect(message.session_key).to eq(session_key) end it 'should set the flags' do expect(message.flag).to eq(0x60088215) end it 'should NOT set the OS version structure' do expect(message.os_version).to be_nil end describe '#blank_password?' do it 'should be true' do expect(message.blank_password?(server_challenge)).to be true end end describe '#ntlm_version' do let(:ver) { message.ntlm_version } it 'should be :ntlmv2' do expect(ver).to eq(:ntlmv2) end end end # http://davenport.sourceforge.net/ntlm.html#appendixC7 context 'NTLM2 Session Response Authentication; NTLM2 Signing and Sealing Using the 128-bit NTLM2 Session Response User Session Key With Key Exchange Negotiated' do let(:data) do [ '4e544c4d5353500003000000180018006000000018001800780000000c000c00' \ '40000000080008004c0000000c000c00540000001000100090000000358288e0' \ '54004500530054004e00540074006500730074004d0045004d00420045005200' \ '404d1b6f6915258000000000000000000000000000000000ea8cc49f24da157f' \ '13436637f77693d8b992d619e584c7ee727a5240822ec7af4e9100c43e6fee7f' ].pack('H*') end it 'should set the LM response' do lm_response = ['404d1b6f6915258000000000000000000000000000000000'].pack('H*') expect(message.lm_response).to eq(lm_response) end it 'should set the NTLM response' do ntlm_response = [ 'ea8cc49f24da157f13436637f77693d8b992d619e584c7ee' ].pack('H*') expect(message.ntlm_response).to eq(ntlm_response) end it 'should set the domain' do # TESTNT domain = ['54004500530054004e005400'].pack('H*') expect(message.domain).to eq(domain) end it 'should set the user' do # test user = ['7400650073007400'].pack('H*') expect(message.user).to eq(user) end it 'should set the workstation' do # MEMBER workstation = ['4d0045004d00420045005200'].pack('H*') expect(message.workstation).to eq(workstation) end it 'should set the session key' do session_key = ['727a5240822ec7af4e9100c43e6fee7f'].pack('H*') expect(message.session_key).to eq(session_key) end let(:server_challenge) { ['677f1c557a5ee96c'].pack('H*') } describe '#password?' do it 'should be true for "test1234"' do expect(message.password?('<PASSWORD>', server_challenge)).to be true end end describe '#blank_password?' do it 'should be false' do expect(message.blank_password?(server_challenge)).to be false end end describe '#ntlm_version' do let(:ver) { message.ntlm_version } it 'should be :ntlm2_session' do expect(ver).to eq(:ntlm2_session) end end end # http://davenport.sourceforge.net/ntlm.html#appendixC9 context 'NTLMv2 Authentication; NTLM1 Signing and Sealing Using the 40-bit NTLMv2 User Session Key' do let(:data) do [ '4e544c4d5353500003000000180018006000000076007600780000000c000c00' \ '40000000080008004c0000000c000c005400000000000000ee00000035828000' \ '54004500530054004e00540074006500730074004d0045004d00420045005200' \ '5d55a02b60a40526ac9a1e4d15fa45a0f2e6329726c598e8f77c67dad00b9321' \ '6242b197fe6addfa0101000000000000502db638677bc301f2e6329726c598e8' \ '0000000002000c0054004500530054004e00540001000c004d0045004d004200' \ '4500520003001e006d0065006d006200650072002e0074006500730074002e00' \ '63006f006d000000000000000000' ].pack 'H*' end it 'should set the NTLM response' do ntlm_response = [ 'f77c67dad00b93216242b197fe6addfa0101000000000000502db638677bc301' \ 'f2e6329726c598e80000000002000c0054004500530054004e00540001000c00' \ '4d0045004d0042004500520003001e006d0065006d006200650072002e007400' \ '6500730074002e0063006f006d000000000000000000' ].pack 'H*' expect(message.ntlm_response).to eq(ntlm_response) end it 'should set the domain' do # TESTNT domain = ['54004500530054004e005400'].pack('H*') expect(message.domain).to eq(domain) end it 'should set the user' do # test user = ['7400650073007400'].pack('H*') expect(message.user).to eq(user) end it 'should set the workstation' do # MEMBER workstation = ['4d0045004d00420045005200'].pack('H*') expect(message.workstation).to eq(workstation) end describe '#ntlm_version' do let(:ver) { message.ntlm_version } it 'should be :ntlmv2' do expect(ver).to eq(:ntlmv2) end end end end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/test/layouts/test_basic.rb
<reponame>arnab0073/idea require File.expand_path('../setup', File.dirname(__FILE__)) module TestLogging module TestLayouts class TestBasic < Test::Unit::TestCase include LoggingTestCase def setup super @layout = Logging.layouts.basic({}) @levels = Logging::LEVELS end def test_format event = Logging::LogEvent.new( 'ArrayLogger', @levels['info'], 'log message', false) assert_equal " INFO ArrayLogger : log message\n", @layout.format(event) event.data = [1, 2, 3, 4] assert_equal(" INFO ArrayLogger : <Array> #{[1,2,3,4]}\n", @layout.format(event)) event.level = @levels['debug'] event.data = 'and another message' log = "DEBUG ArrayLogger : and another message\n" assert_equal log, @layout.format(event) event.logger = 'Test' event.level = @levels['fatal'] event.data = Exception.new log = "FATAL Test : <Exception> Exception\n" assert_equal log, @layout.format(event) end end # class TestBasic end # module TestLayouts end # module TestLogging
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/bigdecimal/sample/linear.rb
#!/usr/local/bin/ruby # # linear.rb # # Solves linear equation system(A*x = b) by LU decomposition method. # where A is a coefficient matrix,x is an answer vector,b is a constant vector. # # USAGE: # ruby linear.rb [input file solved] # require "bigdecimal" require "bigdecimal/ludcmp" # # NOTE: # Change following BigDecimal::limit() if needed. BigDecimal::limit(100) # include LUSolve def rd_order(na) printf("Number of equations ?") if(na <= 0) n = ARGF.gets().to_i end na = ARGV.size zero = BigDecimal::new("0.0") one = BigDecimal::new("1.0") while (n=rd_order(na))>0 a = [] as= [] b = [] if na <= 0 # Read data from console. printf("\nEnter coefficient matrix element A[i,j]\n"); for i in 0...n do for j in 0...n do printf("A[%d,%d]? ",i,j); s = ARGF.gets a << BigDecimal::new(s); as << BigDecimal::new(s); end printf("Contatant vector element b[%d] ? ",i); b << BigDecimal::new(ARGF.gets); end else # Read data from specified file. printf("Coefficient matrix and constant vector.\n"); for i in 0...n do s = ARGF.gets printf("%d) %s",i,s) s = s.split for j in 0...n do a << BigDecimal::new(s[j]); as << BigDecimal::new(s[j]); end b << BigDecimal::new(s[n]); end end x = lusolve(a,b,ludecomp(a,n,zero,one),zero) printf("Answer(x[i] & (A*x-b)[i]) follows\n") for i in 0...n do printf("x[%d]=%s ",i,x[i].to_s) s = zero for j in 0...n do s = s + as[i*n+j]*x[j] end printf(" & %s\n",(s-b[i]).to_s) end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/lib/logging/filters.rb
module Logging module Filters ; end require libpath('logging/filters/level') end
arnab0073/idea
.rvm/src/ruby-2.3.0/test/webrick/test_httprequest.rb
# frozen_string_literal: false require "webrick" require "stringio" require "test/unit" class TestWEBrickHTTPRequest < Test::Unit::TestCase def test_simple_request msg = <<-_end_of_message_ GET / _end_of_message_ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(msg)) assert(req.meta_vars) # fails if @header was not initialized and iteration is attempted on the nil reference end def test_parse_09 msg = <<-_end_of_message_ GET / foobar # HTTP/0.9 request don't have header nor entity body. _end_of_message_ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(msg.gsub(/^ {6}/, ""))) assert_equal("GET", req.request_method) assert_equal("/", req.unparsed_uri) assert_equal(WEBrick::HTTPVersion.new("0.9"), req.http_version) assert_equal(WEBrick::Config::HTTP[:ServerName], req.host) assert_equal(80, req.port) assert_equal(false, req.keep_alive?) assert_equal(nil, req.body) assert(req.query.empty?) end def test_parse_10 msg = <<-_end_of_message_ GET / HTTP/1.0 _end_of_message_ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(msg.gsub(/^ {6}/, ""))) assert_equal("GET", req.request_method) assert_equal("/", req.unparsed_uri) assert_equal(WEBrick::HTTPVersion.new("1.0"), req.http_version) assert_equal(WEBrick::Config::HTTP[:ServerName], req.host) assert_equal(80, req.port) assert_equal(false, req.keep_alive?) assert_equal(nil, req.body) assert(req.query.empty?) end def test_parse_11 msg = <<-_end_of_message_ GET /path HTTP/1.1 _end_of_message_ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(msg.gsub(/^ {6}/, ""))) assert_equal("GET", req.request_method) assert_equal("/path", req.unparsed_uri) assert_equal("", req.script_name) assert_equal("/path", req.path_info) assert_equal(WEBrick::HTTPVersion.new("1.1"), req.http_version) assert_equal(WEBrick::Config::HTTP[:ServerName], req.host) assert_equal(80, req.port) assert_equal(true, req.keep_alive?) assert_equal(nil, req.body) assert(req.query.empty?) end def test_request_uri_too_large msg = <<-_end_of_message_ GET /#{"a"*2084} HTTP/1.1 _end_of_message_ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) assert_raise(WEBrick::HTTPStatus::RequestURITooLarge){ req.parse(StringIO.new(msg.gsub(/^ {6}/, ""))) } end def test_parse_headers msg = <<-_end_of_message_ GET /path HTTP/1.1 Host: test.ruby-lang.org:8080 Connection: close Accept: text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5 Accept-Encoding: compress;q=0.5 Accept-Encoding: gzip;q=1.0, identity; q=0.4, *;q=0 Accept-Language: en;q=0.5, *; q=0 Accept-Language: ja Content-Type: text/plain Content-Length: 7 X-Empty-Header: foobar _end_of_message_ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(msg.gsub(/^ {6}/, ""))) assert_equal( URI.parse("http://test.ruby-lang.org:8080/path"), req.request_uri) assert_equal("test.ruby-lang.org", req.host) assert_equal(8080, req.port) assert_equal(false, req.keep_alive?) assert_equal( %w(text/html;level=1 text/html */* text/html;level=2 text/*), req.accept) assert_equal(%w(gzip compress identity *), req.accept_encoding) assert_equal(%w(ja en *), req.accept_language) assert_equal(7, req.content_length) assert_equal("text/plain", req.content_type) assert_equal("foobar\n", req.body) assert_equal("", req["x-empty-header"]) assert_equal(nil, req["x-no-header"]) assert(req.query.empty?) end def test_parse_header2() msg = <<-_end_of_message_ POST /foo/bar/../baz?q=a HTTP/1.0 Content-Length: 9 User-Agent: FOO BAR BAZ hogehoge _end_of_message_ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(msg.gsub(/^ {6}/, ""))) assert_equal("POST", req.request_method) assert_equal("/foo/baz", req.path) assert_equal("", req.script_name) assert_equal("/foo/baz", req.path_info) assert_equal("9", req['content-length']) assert_equal("FOO BAR BAZ", req['user-agent']) assert_equal("hogehoge\n", req.body) end def test_parse_headers3 msg = <<-_end_of_message_ GET /path HTTP/1.1 Host: test.ruby-lang.org _end_of_message_ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(msg.gsub(/^ {6}/, ""))) assert_equal(URI.parse("http://test.ruby-lang.org/path"), req.request_uri) assert_equal("test.ruby-lang.org", req.host) assert_equal(80, req.port) msg = <<-_end_of_message_ GET /path HTTP/1.1 Host: 192.168.1.1 _end_of_message_ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(msg.gsub(/^ {6}/, ""))) assert_equal(URI.parse("http://192.168.1.1/path"), req.request_uri) assert_equal("192.168.1.1", req.host) assert_equal(80, req.port) msg = <<-_end_of_message_ GET /path HTTP/1.1 Host: [fe80::208:dff:feef:98c7] _end_of_message_ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(msg.gsub(/^ {6}/, ""))) assert_equal(URI.parse("http://[fe80::208:dff:feef:98c7]/path"), req.request_uri) assert_equal("[fefdf8:f53e:61e4::18:dff:feef:98c7]", req.host) assert_equal(80, req.port) msg = <<-_end_of_message_ GET /path HTTP/1.1 Host: 192.168.1.1:8080 _end_of_message_ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(msg.gsub(/^ {6}/, ""))) assert_equal(URI.parse("http://192.168.1.1:8080/path"), req.request_uri) assert_equal("192.168.1.1", req.host) assert_equal(8080, req.port) msg = <<-_end_of_message_ GET /path HTTP/1.1 Host: [fe80::208:dff:feef:98c7]:8080 _end_of_message_ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(msg.gsub(/^ {6}/, ""))) assert_equal(URI.parse("http://[fe80::208:dff:feef:98c7]:8080/path"), req.request_uri) assert_equal("[fe80::208:dff:feef:98c7]", req.host) assert_equal(8080, req.port) end def test_parse_get_params param = "foo=1;foo=2;foo=3;bar=x" msg = <<-_end_of_message_ GET /path?#{param} HTTP/1.1 Host: test.ruby-lang.org:8080 _end_of_message_ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(msg.gsub(/^ {6}/, ""))) query = req.query assert_equal("1", query["foo"]) assert_equal(["1", "2", "3"], query["foo"].to_ary) assert_equal(["1", "2", "3"], query["foo"].list) assert_equal("x", query["bar"]) assert_equal(["x"], query["bar"].list) end def test_parse_post_params param = "foo=1;foo=2;foo=3;bar=x" msg = <<-_end_of_message_ POST /path?foo=x;foo=y;foo=z;bar=1 HTTP/1.1 Host: test.ruby-lang.org:8080 Content-Length: #{param.size} Content-Type: application/x-www-form-urlencoded #{param} _end_of_message_ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(msg.gsub(/^ {6}/, ""))) query = req.query assert_equal("1", query["foo"]) assert_equal(["1", "2", "3"], query["foo"].to_ary) assert_equal(["1", "2", "3"], query["foo"].list) assert_equal("x", query["bar"]) assert_equal(["x"], query["bar"].list) end def test_chunked crlf = "\x0d\x0a" msg = <<-_end_of_message_ POST /path HTTP/1.1 Host: test.ruby-lang.org:8080 Transfer-Encoding: chunked _end_of_message_ msg.gsub!(/^ {6}/, "") open(__FILE__){|io| while chunk = io.read(100) msg << chunk.size.to_s(16) << crlf msg << chunk << crlf end } msg << "0" << crlf req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(msg)) assert_equal(File.read(__FILE__), req.body) end def test_forwarded msg = <<-_end_of_message_ GET /foo HTTP/1.1 Host: localhost:10080 User-Agent: w3m/0.5.2 X-Forwarded-For: 192.168.127.12 X-Forwarded-Host: forward.example.com X-Forwarded-Server: server.example.com Connection: Keep-Alive _end_of_message_ msg.gsub!(/^ {6}/, "") req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(msg)) assert_equal("server.example.com", req.server_name) assert_equal("http://forward.example.com/foo", req.request_uri.to_s) assert_equal("forward.example.com", req.host) assert_equal(80, req.port) assert_equal("192.168.127.12", req.remote_ip) assert(!req.ssl?) msg = <<-_end_of_message_ GET /foo HTTP/1.1 Host: localhost:10080 User-Agent: w3m/0.5.2 X-Forwarded-For: 192.168.1.10, 172.16.1.1, 192.168.127.12 X-Forwarded-Host: forward.example.com:8080 X-Forwarded-Server: server.example.com Connection: Keep-Alive _end_of_message_ msg.gsub!(/^ {6}/, "") req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(msg)) assert_equal("server.example.com", req.server_name) assert_equal("http://forward.example.com:8080/foo", req.request_uri.to_s) assert_equal("forward.example.com", req.host) assert_equal(8080, req.port) assert_equal("192.168.127.12", req.remote_ip) assert(!req.ssl?) msg = <<-_end_of_message_ GET /foo HTTP/1.1 Host: localhost:10080 Client-IP: 192.168.127.12 X-Forwarded-Proto: https X-Forwarded-For: 192.168.1.10, 10.0.0.1, 192.168.127.12 X-Forwarded-Host: forward.example.com X-Forwarded-Server: server.example.com X-Requested-With: XMLHttpRequest Connection: Keep-Alive _end_of_message_ msg.gsub!(/^ {6}/, "") req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(msg)) assert_equal("server.example.com", req.server_name) assert_equal("https://forward.example.com/foo", req.request_uri.to_s) assert_equal("forward.example.com", req.host) assert_equal(443, req.port) assert_equal("192.168.127.12", req.remote_ip) assert(req.ssl?) msg = <<-_end_of_message_ GET /foo HTTP/1.1 Host: localhost:10080 Client-IP: 192.168.127.12 X-Forwarded-Proto: https X-Forwarded-For: 192.168.1.10 X-Forwarded-Host: forward1.example.com:1234, forward2.example.com:5678 X-Forwarded-Server: server1.example.com, server2.example.com X-Requested-With: XMLHttpRequest Connection: Keep-Alive _end_of_message_ msg.gsub!(/^ {6}/, "") req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(msg)) assert_equal("server1.example.com", req.server_name) assert_equal("https://forward1.example.com:1234/foo", req.request_uri.to_s) assert_equal("forward1.example.com", req.host) assert_equal(1234, req.port) assert_equal("192.168.127.12", req.remote_ip) assert(req.ssl?) end def test_continue_sent msg = <<-_end_of_message_ POST /path HTTP/1.1 Expect: 100-continue _end_of_message_ msg.gsub!(/^ {6}/, "") req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(msg)) assert req['expect'] l = msg.size req.continue assert_not_equal l, msg.size assert_match(/HTTP\/1.1 100 continue\r\n\r\n\z/, msg) assert !req['expect'] end def test_continue_not_sent msg = <<-_end_of_message_ POST /path HTTP/1.1 _end_of_message_ msg.gsub!(/^ {6}/, "") req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(msg)) assert !req['expect'] l = msg.size req.continue assert_equal l, msg.size end def test_bad_messages param = "foo=1;foo=2;foo=3;bar=x" msg = <<-_end_of_message_ POST /path?foo=x;foo=y;foo=z;bar=1 HTTP/1.1 Host: test.ruby-lang.org:8080 Content-Type: application/x-www-form-urlencoded #{param} _end_of_message_ assert_raise(WEBrick::HTTPStatus::LengthRequired){ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(msg.gsub(/^ {6}/, ""))) req.body } msg = <<-_end_of_message_ POST /path?foo=x;foo=y;foo=z;bar=1 HTTP/1.1 Host: test.ruby-lang.org:8080 Content-Length: 100000 body is too short. _end_of_message_ assert_raise(WEBrick::HTTPStatus::BadRequest){ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(msg.gsub(/^ {6}/, ""))) req.body } msg = <<-_end_of_message_ POST /path?foo=x;foo=y;foo=z;bar=1 HTTP/1.1 Host: test.ruby-lang.org:8080 Transfer-Encoding: foobar body is too short. _end_of_message_ assert_raise(WEBrick::HTTPStatus::NotImplemented){ req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(msg.gsub(/^ {6}/, ""))) req.body } end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/excon-0.49.0/lib/excon/response.rb
module Excon class Response attr_accessor :data # backwards compatability reader/writers def body=(new_body) @data[:body] = new_body end def body @data[:body] end def headers=(new_headers) @data[:headers] = new_headers end def headers @data[:headers] end def host @data[:host] end def local_address @data[:local_address] end def local_port @data[:local_port] end def path @data[:path] end def port @data[:port] end def reason_phrase=(new_reason_phrase) @data[:reason_phrase] = new_reason_phrase end def reason_phrase @data[:reason_phrase] end def remote_ip=(new_remote_ip) @data[:remote_ip] = new_remote_ip end def remote_ip @data[:remote_ip] end def status=(new_status) @data[:status] = new_status end def status @data[:status] end def status_line @data[:status_line] end def status_line=(new_status_line) @data[:status_line] = new_status_line end def self.parse(socket, datum) # this will discard any trailing lines from the previous response if any. begin line = socket.readline end until status = line[9, 3].to_i reason_phrase = line[13..-3] # -3 strips the trailing "\r\n" datum[:response] = { :body => '', :cookies => [], :host => datum[:host], :headers => Excon::Headers.new, :path => datum[:path], :port => datum[:port], :status => status, :status_line => line, :reason_phrase => reason_phrase } unix_proxy = datum[:proxy] ? datum[:proxy][:scheme] == UNIX : false unless datum[:scheme] == UNIX || unix_proxy datum[:response].merge!( :remote_ip => socket.remote_ip, :local_port => socket.local_port, :local_address => socket.local_address ) end parse_headers(socket, datum) unless (['HEAD', 'CONNECT'].include?(datum[:method].to_s.upcase)) || NO_ENTITY.include?(datum[:response][:status]) if key = datum[:response][:headers].keys.detect {|k| k.casecmp('Transfer-Encoding') == 0 } encodings = Utils.split_header_value(datum[:response][:headers][key]) if (encoding = encodings.last) && encoding.casecmp('chunked') == 0 transfer_encoding_chunked = true if encodings.length == 1 datum[:response][:headers].delete(key) else datum[:response][:headers][key] = encodings[0...-1].join(', ') end end end # use :response_block unless :expects would fail if response_block = datum[:response_block] if datum[:middlewares].include?(Excon::Middleware::Expects) && datum[:expects] && !Array(datum[:expects]).include?(datum[:response][:status]) response_block = nil end end if transfer_encoding_chunked if response_block while (chunk_size = socket.readline.chomp!.to_i(16)) > 0 while chunk_size > 0 chunk = socket.read(chunk_size) || raise(EOFError) chunk_size -= chunk.bytesize response_block.call(chunk, nil, nil) end new_line_size = 2 # 2 == "\r\n".length while new_line_size > 0 chunk = socket.read(new_line_size) || raise(EOFError) new_line_size -= chunk.length end end else while (chunk_size = socket.readline.chomp!.to_i(16)) > 0 while chunk_size > 0 chunk = socket.read(chunk_size) || raise(EOFError) chunk_size -= chunk.bytesize datum[:response][:body] << chunk end new_line_size = 2 # 2 == "\r\n".length while new_line_size > 0 chunk = socket.read(new_line_size) || raise(EOFError) new_line_size -= chunk.length end end end parse_headers(socket, datum) # merge trailers into headers else if key = datum[:response][:headers].keys.detect {|k| k.casecmp('Content-Length') == 0 } content_length = datum[:response][:headers][key].to_i end if remaining = content_length if response_block while remaining > 0 chunk = socket.read([datum[:chunk_size], remaining].min) || raise(EOFError) response_block.call(chunk, [remaining - chunk.bytesize, 0].max, content_length) remaining -= chunk.bytesize end else while remaining > 0 chunk = socket.read([datum[:chunk_size], remaining].min) || raise(EOFError) datum[:response][:body] << chunk remaining -= chunk.bytesize end end else if response_block while chunk = socket.read(datum[:chunk_size]) response_block.call(chunk, nil, nil) end else while chunk = socket.read(datum[:chunk_size]) datum[:response][:body] << chunk end end end end end datum end def self.parse_headers(socket, datum) last_key = nil until (data = socket.readline.chomp).empty? if !data.lstrip!.nil? raise Excon::Errors::ResponseParseError, 'malformed header' unless last_key # append to last_key's last value datum[:response][:headers][last_key] << ' ' << data.rstrip else key, value = data.split(':', 2) raise Excon::Errors::ResponseParseError, 'malformed header' unless value # add key/value or append value to existing values datum[:response][:headers][key] = ([datum[:response][:headers][key]] << value.strip).compact.join(', ') if key.casecmp('Set-Cookie') == 0 datum[:response][:cookies] << value.strip end last_key = key end end end def initialize(params={}) @data = { :body => '' }.merge(params) @data[:headers] = Excon::Headers.new.merge!(params[:headers] || {}) @body = @data[:body] @headers = @data[:headers] @status = @data[:status] @remote_ip = @data[:remote_ip] @local_port = @data[:local_port] @local_address = @data[:local_address] end def [](key) @data[key] end def params Excon.display_warning('Excon::Response#params is deprecated use Excon::Response#data instead.') data end def pp Excon::PrettyPrinter.pp($stdout, @data) end # Retrieve a specific header value. Header names are treated case-insensitively. # @param [String] name Header name def get_header(name) headers[name] end end # class Response end # module Excon
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/test/ruby/test_method.rb
<filename>.rvm/src/ruby-1.9.3-p551/test/ruby/test_method.rb require 'test/unit' require_relative 'envutil' class TestMethod < Test::Unit::TestCase def setup @verbose = $VERBOSE $VERBOSE = nil end def teardown $VERBOSE = @verbose end def m0() end def m1(a) end def m2(a, b) end def mo1(a = nil, &b) end def mo2(a, b = nil) end def mo3(*a) end def mo4(a, *b, &c) end def mo5(a, *b, c) end def mo6(a, *b, c, &d) end def mo7(a, b = nil, *c, d, &e) end def ma1((a), &b) end class Base def foo() :base end end class Derived < Base def foo() :derived end end class T def initialize; end def normal_method; end end module M def func; end module_function :func def meth; end end def mv1() end def mv2() end private :mv2 def mv3() end protected :mv3 class Visibility def mv1() end def mv2() end private :mv2 def mv3() end protected :mv3 end def test_arity assert_equal(0, method(:m0).arity) assert_equal(1, method(:m1).arity) assert_equal(2, method(:m2).arity) assert_equal(-1, method(:mo1).arity) assert_equal(-2, method(:mo2).arity) assert_equal(-1, method(:mo3).arity) assert_equal(-2, method(:mo4).arity) assert_equal(-3, method(:mo5).arity) assert_equal(-3, method(:mo6).arity) end def test_arity_special assert_equal(-1, method(:__send__).arity) end def test_unbind assert_equal(:derived, Derived.new.foo) um = Derived.new.method(:foo).unbind assert_instance_of(UnboundMethod, um) Derived.class_eval do def foo() :changed end end assert_equal(:changed, Derived.new.foo) assert_equal(:derived, um.bind(Derived.new).call) assert_raise(TypeError) do um.bind(Base.new) end end def test_callee assert_equal(:test_callee, __method__) assert_equal(:m, Class.new {def m; __method__; end}.new.m) assert_equal(:m, Class.new {def m; tap{return __method__}; end}.new.m) assert_equal(:m, Class.new {define_method(:m) {__method__}}.new.m) assert_equal(:m, Class.new {define_method(:m) {tap{return __method__}}}.new.m) assert_nil(eval("class TestCallee; __method__; end")) end def test_method_in_define_method_block bug4606 = '[ruby-core:35386]' c = Class.new do [:m1, :m2].each do |m| define_method(m) do __method__ end end end assert_equal(:m1, c.new.m1, bug4606) assert_equal(:m2, c.new.m2, bug4606) end def test_method_in_block_in_define_method_block bug4606 = '[ruby-core:35386]' c = Class.new do [:m1, :m2].each do |m| define_method(m) do tap { return __method__ } end end end assert_equal(:m1, c.new.m1, bug4606) assert_equal(:m2, c.new.m2, bug4606) end def test_body o = Object.new def o.foo; end assert_nothing_raised { RubyVM::InstructionSequence.disasm(o.method(:foo)) } assert_nothing_raised { RubyVM::InstructionSequence.disasm("x".method(:upcase)) } assert_nothing_raised { RubyVM::InstructionSequence.disasm(method(:to_s).to_proc) } end def test_new c1 = Class.new c1.class_eval { def foo; :foo; end } c2 = Class.new(c1) c2.class_eval { private :foo } o = c2.new o.extend(Module.new) assert_raise(NameError) { o.method(:bar) } assert_raise(NameError) { o.public_method(:foo) } assert_equal(:foo, o.method(:foo).call) end def test_eq o = Object.new class << o def foo; end alias bar foo def baz; end end assert_not_equal(o.method(:foo), nil) m = o.method(:foo) def m.foo; end assert_not_equal(o.method(:foo), m) assert_equal(o.method(:foo), o.method(:foo)) assert_equal(o.method(:foo), o.method(:bar)) assert_not_equal(o.method(:foo), o.method(:baz)) end def test_hash o = Object.new def o.foo; end assert_kind_of(Integer, o.method(:foo).hash) end def test_receiver_name_owner o = Object.new def o.foo; end m = o.method(:foo) assert_equal(o, m.receiver) assert_equal(:foo, m.name) assert_equal(class << o; self; end, m.owner) assert_equal(:foo, m.unbind.name) assert_equal(class << o; self; end, m.unbind.owner) end def test_instance_method c = Class.new c.class_eval do def foo; :foo; end private :foo end o = c.new o.method(:foo).unbind assert_raise(NoMethodError) { o.foo } c.instance_method(:foo).bind(o) assert_equal(:foo, o.instance_eval { foo }) assert_raise(NameError) { c.public_instance_method(:foo) } def o.bar; end m = o.method(:bar).unbind assert_raise(TypeError) { m.bind(Object.new) } end def test_define_method c = Class.new c.class_eval { def foo; :foo; end } o = c.new def o.bar; :bar; end assert_raise(TypeError) do c.class_eval { define_method(:foo, :foo) } end assert_raise(ArgumentError) do c.class_eval { define_method } end c2 = Class.new(c) c2.class_eval { define_method(:baz, o.method(:foo)) } assert_equal(:foo, c2.new.baz) assert_raise(TypeError) do Class.new.class_eval { define_method(:foo, o.method(:foo)) } end assert_raise(TypeError) do Class.new.class_eval { define_method(:bar, o.method(:bar)) } end o = Object.new def o.foo(c) c.class_eval { define_method(:foo) } end c = Class.new o.foo(c) { :foo } assert_equal(:foo, c.new.foo) o = Object.new o.instance_eval { define_singleton_method(:foo) { :foo } } assert_equal(:foo, o.foo) assert_raise(TypeError) do Class.new.class_eval { define_method(:foo, Object.new) } end assert_raise(TypeError) do Module.new.module_eval {define_method(:foo, Base.instance_method(:foo))} end assert_raise(TypeError) do Class.new.class_eval {define_method(:meth, M.instance_method(:meth))} end end def test_super_in_proc_from_define_method c1 = Class.new { def m :m1 end } c2 = Class.new(c1) { define_method(:m) { Proc.new { super() } } } # c2.new.m.call should return :m1, but currently it raise NoMethodError. # see [Bug #4881] and [Bug #3136] assert_raise(NoMethodError) { c2.new.m.call } end def test_clone o = Object.new def o.foo; :foo; end m = o.method(:foo) def m.bar; :bar; end assert_equal(:foo, m.clone.call) assert_equal(:bar, m.clone.bar) end def test_call o = Object.new def o.foo; p 1; end def o.bar(x); x; end m = o.method(:foo) m.taint assert_raise(SecurityError) { m.call } end def test_inspect o = Object.new def o.foo; end m = o.method(:foo) assert_equal("#<Method: #{ o.inspect }.foo>", m.inspect) m = o.method(:foo) assert_equal("#<UnboundMethod: #{ class << o; self; end.inspect }#foo>", m.unbind.inspect) c = Class.new c.class_eval { def foo; end; } m = c.new.method(:foo) assert_equal("#<Method: #{ c.inspect }#foo>", m.inspect) m = c.instance_method(:foo) assert_equal("#<UnboundMethod: #{ c.inspect }#foo>", m.inspect) c2 = Class.new(c) c2.class_eval { private :foo } m2 = c2.new.method(:foo) assert_equal("#<Method: #{ c2.inspect }(#{ c.inspect })#foo>", m2.inspect) end def test_callee_top_level assert_in_out_err([], "p __callee__", %w(nil), []) end def test_caller_top_level assert_in_out_err([], "p caller", %w([]), []) end def test_caller_negative_level assert_raise(ArgumentError) { caller(-1) } end def test_attrset_ivar c = Class.new c.class_eval { attr_accessor :foo } o = c.new o.method(:foo=).call(42) assert_equal(42, o.foo) assert_raise(ArgumentError) { o.method(:foo=).call(1, 2, 3) } assert_raise(ArgumentError) { o.method(:foo).call(1) } end def test_default_accessibility assert T.public_instance_methods.include?(:normal_method), 'normal methods are public by default' assert !T.public_instance_methods.include?(:initialize), '#initialize is private' assert !M.public_instance_methods.include?(:func), 'module methods are private by default' assert M.public_instance_methods.include?(:meth), 'normal methods are public by default' end define_method(:pm0) {||} define_method(:pm1) {|a|} define_method(:pm2) {|a, b|} define_method(:pmo1) {|a = nil, &b|} define_method(:pmo2) {|a, b = nil|} define_method(:pmo3) {|*a|} define_method(:pmo4) {|a, *b, &c|} define_method(:pmo5) {|a, *b, c|} define_method(:pmo6) {|a, *b, c, &d|} define_method(:pmo7) {|a, b = nil, *c, d, &e|} define_method(:pma1) {|(a), &b|} def test_bound_parameters assert_equal([], method(:m0).parameters) assert_equal([[:req, :a]], method(:m1).parameters) assert_equal([[:req, :a], [:req, :b]], method(:m2).parameters) assert_equal([[:opt, :a], [:block, :b]], method(:mo1).parameters) assert_equal([[:req, :a], [:opt, :b]], method(:mo2).parameters) assert_equal([[:rest, :a]], method(:mo3).parameters) assert_equal([[:req, :a], [:rest, :b], [:block, :c]], method(:mo4).parameters) assert_equal([[:req, :a], [:rest, :b], [:req, :c]], method(:mo5).parameters) assert_equal([[:req, :a], [:rest, :b], [:req, :c], [:block, :d]], method(:mo6).parameters) assert_equal([[:req, :a], [:opt, :b], [:rest, :c], [:req, :d], [:block, :e]], method(:mo7).parameters) assert_equal([[:req], [:block, :b]], method(:ma1).parameters) end def test_unbound_parameters assert_equal([], self.class.instance_method(:m0).parameters) assert_equal([[:req, :a]], self.class.instance_method(:m1).parameters) assert_equal([[:req, :a], [:req, :b]], self.class.instance_method(:m2).parameters) assert_equal([[:opt, :a], [:block, :b]], self.class.instance_method(:mo1).parameters) assert_equal([[:req, :a], [:opt, :b]], self.class.instance_method(:mo2).parameters) assert_equal([[:rest, :a]], self.class.instance_method(:mo3).parameters) assert_equal([[:req, :a], [:rest, :b], [:block, :c]], self.class.instance_method(:mo4).parameters) assert_equal([[:req, :a], [:rest, :b], [:req, :c]], self.class.instance_method(:mo5).parameters) assert_equal([[:req, :a], [:rest, :b], [:req, :c], [:block, :d]], self.class.instance_method(:mo6).parameters) assert_equal([[:req, :a], [:opt, :b], [:rest, :c], [:req, :d], [:block, :e]], self.class.instance_method(:mo7).parameters) assert_equal([[:req], [:block, :b]], self.class.instance_method(:ma1).parameters) end def test_bmethod_bound_parameters assert_equal([], method(:pm0).parameters) assert_equal([[:req, :a]], method(:pm1).parameters) assert_equal([[:req, :a], [:req, :b]], method(:pm2).parameters) assert_equal([[:opt, :a], [:block, :b]], method(:pmo1).parameters) assert_equal([[:req, :a], [:opt, :b]], method(:pmo2).parameters) assert_equal([[:rest, :a]], method(:pmo3).parameters) assert_equal([[:req, :a], [:rest, :b], [:block, :c]], method(:pmo4).parameters) assert_equal([[:req, :a], [:rest, :b], [:req, :c]], method(:pmo5).parameters) assert_equal([[:req, :a], [:rest, :b], [:req, :c], [:block, :d]], method(:pmo6).parameters) assert_equal([[:req, :a], [:opt, :b], [:rest, :c], [:req, :d], [:block, :e]], method(:pmo7).parameters) assert_equal([[:req], [:block, :b]], method(:pma1).parameters) end def test_bmethod_unbound_parameters assert_equal([], self.class.instance_method(:pm0).parameters) assert_equal([[:req, :a]], self.class.instance_method(:pm1).parameters) assert_equal([[:req, :a], [:req, :b]], self.class.instance_method(:pm2).parameters) assert_equal([[:opt, :a], [:block, :b]], self.class.instance_method(:pmo1).parameters) assert_equal([[:req, :a], [:opt, :b]], self.class.instance_method(:pmo2).parameters) assert_equal([[:rest, :a]], self.class.instance_method(:pmo3).parameters) assert_equal([[:req, :a], [:rest, :b], [:block, :c]], self.class.instance_method(:pmo4).parameters) assert_equal([[:req, :a], [:rest, :b], [:req, :c]], self.class.instance_method(:pmo5).parameters) assert_equal([[:req, :a], [:rest, :b], [:req, :c], [:block, :d]], self.class.instance_method(:pmo6).parameters) assert_equal([[:req, :a], [:opt, :b], [:rest, :c], [:req, :d], [:block, :e]], self.class.instance_method(:pmo7).parameters) assert_equal([[:req], [:block, :b]], self.class.instance_method(:pma1).parameters) end def test_public_method_with_zsuper_method c = Class.new c.class_eval do def foo :ok end private :foo end d = Class.new(c) d.class_eval do public :foo end assert_equal(:ok, d.new.public_method(:foo).call) end def test_public_methods_with_extended m = Module.new do def m1; end end a = Class.new do def a; end end bug = '[ruby-dev:41553]' obj = a.new assert_equal([:a], obj.public_methods(false), bug) obj.extend(m) assert_equal([:m1, :a], obj.public_methods(false), bug) end def test_visibility assert_equal('method', defined?(mv1)) assert_equal('method', defined?(mv2)) assert_equal('method', defined?(mv3)) assert_equal('method', defined?(self.mv1)) assert_equal(nil, defined?(self.mv2)) assert_equal('method', defined?(self.mv3)) assert_equal(true, respond_to?(:mv1)) assert_equal(false, respond_to?(:mv2)) assert_equal(true, respond_to?(:mv3)) assert_equal(true, respond_to?(:mv1, true)) assert_equal(true, respond_to?(:mv2, true)) assert_equal(true, respond_to?(:mv3, true)) assert_nothing_raised { mv1 } assert_nothing_raised { mv2 } assert_nothing_raised { mv3 } assert_nothing_raised { self.mv1 } assert_raise(NoMethodError) { self.mv2 } assert_nothing_raised { self.mv3 } v = Visibility.new assert_equal('method', defined?(v.mv1)) assert_equal(nil, defined?(v.mv2)) assert_equal(nil, defined?(v.mv3)) assert_equal(true, v.respond_to?(:mv1)) assert_equal(false, v.respond_to?(:mv2)) assert_equal(true, v.respond_to?(:mv3)) assert_equal(true, v.respond_to?(:mv1, true)) assert_equal(true, v.respond_to?(:mv2, true)) assert_equal(true, v.respond_to?(:mv3, true)) assert_nothing_raised { v.mv1 } assert_raise(NoMethodError) { v.mv2 } assert_raise(NoMethodError) { v.mv3 } assert_nothing_raised { v.__send__(:mv1) } assert_nothing_raised { v.__send__(:mv2) } assert_nothing_raised { v.__send__(:mv3) } assert_nothing_raised { v.instance_eval { mv1 } } assert_nothing_raised { v.instance_eval { mv2 } } assert_nothing_raised { v.instance_eval { mv3 } } end def test_bound_method_entry bug6171 = '[ruby-core:43383]' assert_ruby_status([], <<-EOC, bug6171) class Bug6171 def initialize(target) define_singleton_method(:reverse, target.method(:reverse).to_proc) end end 1000.times {p = Bug6171.new('test'); 10000.times {p.reverse}} EOC end def test_gced_bmethod assert_normal_exit %q{ require 'irb' IRB::Irb.module_eval do define_method(:eval_input) do IRB::Irb.module_eval { alias_method :eval_input, :to_s } GC.start Kernel end end IRB.start }, '[Bug #7825]' end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/lib/xmlrpc/create.rb
<reponame>arnab0073/idea<gh_stars>0 # # Creates XML-RPC call/response documents # # Copyright (C) 2001, 2002, 2003 by <NAME> (<EMAIL>) # # $Id: create.rb 31321 2011-04-22 13:35:43Z naruse $ # require "date" require "xmlrpc/base64" module XMLRPC module XMLWriter class Abstract def ele(name, *children) element(name, nil, *children) end def tag(name, txt) element(name, nil, text(txt)) end end class Simple < Abstract def document_to_str(doc) doc end def document(*params) params.join("") end def pi(name, *params) "<?#{name} " + params.join(" ") + " ?>" end def element(name, attrs, *children) raise "attributes not yet implemented" unless attrs.nil? if children.empty? "<#{name}/>" else "<#{name}>" + children.join("") + "</#{name}>" end end def text(txt) cleaned = txt.dup cleaned.gsub!(/&/, '&amp;') cleaned.gsub!(/</, '&lt;') cleaned.gsub!(/>/, '&gt;') cleaned end end # class Simple class XMLParser < Abstract def initialize require "xmltreebuilder" end def document_to_str(doc) doc.to_s end def document(*params) XML::SimpleTree::Document.new(*params) end def pi(name, *params) XML::SimpleTree::ProcessingInstruction.new(name, *params) end def element(name, attrs, *children) XML::SimpleTree::Element.new(name, attrs, *children) end def text(txt) XML::SimpleTree::Text.new(txt) end end # class XMLParser Classes = [Simple, XMLParser] # yields an instance of each installed XML writer def self.each_installed_writer XMLRPC::XMLWriter::Classes.each do |klass| begin yield klass.new rescue LoadError end end end end # module XMLWriter class Create def initialize(xml_writer = nil) @writer = xml_writer || Config::DEFAULT_WRITER.new end def methodCall(name, *params) name = name.to_s if name !~ /[a-zA-Z0-9_.:\/]+/ raise ArgumentError, "Wrong XML-RPC method-name" end parameter = params.collect do |param| @writer.ele("param", conv2value(param)) end tree = @writer.document( @writer.pi("xml", 'version="1.0"'), @writer.ele("methodCall", @writer.tag("methodName", name), @writer.ele("params", *parameter) ) ) @writer.document_to_str(tree) + "\n" end # # generates a XML-RPC methodResponse document # # if is_ret == false then the params array must # contain only one element, which is a structure # of a fault return-value. # # if is_ret == true then a normal # return-value of all the given params is created. # def methodResponse(is_ret, *params) if is_ret resp = params.collect do |param| @writer.ele("param", conv2value(param)) end resp = [@writer.ele("params", *resp)] else if params.size != 1 or params[0] === XMLRPC::FaultException raise ArgumentError, "no valid fault-structure given" end resp = @writer.ele("fault", conv2value(params[0].to_h)) end tree = @writer.document( @writer.pi("xml", 'version="1.0"'), @writer.ele("methodResponse", resp) ) @writer.document_to_str(tree) + "\n" end ##################################### private ##################################### # # converts a Ruby object into # a XML-RPC <value> tag # def conv2value(param) val = case param when Fixnum, Bignum # XML-RPC's int is 32bit int, and Fixnum also may be beyond 32bit if Config::ENABLE_BIGINT @writer.tag("i4", param.to_s) else if param >= -(2**31) and param <= (2**31-1) @writer.tag("i4", param.to_s) else raise "Bignum is too big! Must be signed 32-bit integer!" end end when TrueClass, FalseClass @writer.tag("boolean", param ? "1" : "0") when Symbol @writer.tag("string", param.to_s) when String @writer.tag("string", param) when NilClass if Config::ENABLE_NIL_CREATE @writer.ele("nil") else raise "Wrong type NilClass. Not allowed!" end when Float raise "Wrong value #{param}. Not allowed!" unless param.finite? @writer.tag("double", param.to_s) when Struct h = param.members.collect do |key| value = param[key] @writer.ele("member", @writer.tag("name", key.to_s), conv2value(value) ) end @writer.ele("struct", *h) when Hash # TODO: can a Hash be empty? h = param.collect do |key, value| @writer.ele("member", @writer.tag("name", key.to_s), conv2value(value) ) end @writer.ele("struct", *h) when Array # TODO: can an Array be empty? a = param.collect {|v| conv2value(v) } @writer.ele("array", @writer.ele("data", *a) ) when Time, Date, ::DateTime @writer.tag("dateTime.iso8601", param.strftime("%Y%m%dT%H:%M:%S")) when XMLRPC::DateTime @writer.tag("dateTime.iso8601", format("%.4d%02d%02dT%02d:%02d:%02d", *param.to_a)) when XMLRPC::Base64 @writer.tag("base64", param.encoded) else if Config::ENABLE_MARSHALLING and param.class.included_modules.include? XMLRPC::Marshallable # convert Ruby object into Hash ret = {"___class___" => param.class.name} param.instance_variables.each {|v| name = v[1..-1] val = param.instance_variable_get(v) if val.nil? ret[name] = val if Config::ENABLE_NIL_CREATE else ret[name] = val end } return conv2value(ret) else ok, pa = wrong_type(param) if ok return conv2value(pa) else raise "Wrong type!" end end end @writer.ele("value", val) end def wrong_type(value) false end end # class Create end # module XMLRPC
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/mixlib-authentication-1.4.1/spec/mixlib/authentication/http_authentication_request_spec.rb
<filename>.rvm/gems/ruby-2.3.0/gems/mixlib-authentication-1.4.1/spec/mixlib/authentication/http_authentication_request_spec.rb # Author:: <NAME> (<<EMAIL>>) # Copyright:: Copyright (c) 2010 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")) require "mixlib/authentication" require "mixlib/authentication/http_authentication_request" require "ostruct" require "pp" describe Mixlib::Authentication::HTTPAuthenticationRequest do before do request = Struct.new(:env, :method, :path) @timestamp_iso8601 = "2009-01-01T12:00:00Z" @x_ops_content_hash = "DFteJZPVv6WKdQmMqZUQUumUyRs=" @user_id = "spec-user" @http_x_ops_lines = [ "jVHrNniWzpbez/eGWjFnO6lINRIuKOg40ZTIQudcFe47Z9e/HvrszfVXlKG4", "NMzYZgyooSvU85qkIUmKuCqgG2AIlvYa2Q/2ctrMhoaHhLOCWWoqYNMaEqPc", "3tKHE+CfvP+WuPdWk4jv4wpIkAz6ZLxToxcGhXmZbXpk56YTmqgBW2cbbw4O", "IWPZDHSiPcw//AYNgW1CCDptt+UFuaFYbtqZegcBd2n/jzcWODA7zL4KWEUy", "9q4rlh/+1tBReg60QdsmDRsw/cdO1GZrKtuCwbuD4+nbRdVBKv72rqHX9cu0", "utju9jzczCyB+sSAQWrxSsXB/b8vV2qs0l4VD2ML+w=="] @merb_headers = { # These are used by signatureverification. An arbitrary sampling of non-HTTP_* # headers are in here to exercise that code path. "HTTP_HOST" => "127.0.0.1", "HTTP_X_OPS_SIGN" => "version=1.0", "HTTP_X_OPS_REQUESTID" => "127.0.0.1 1258566194.85386", "HTTP_X_OPS_TIMESTAMP" => @timestamp_iso8601, "HTTP_X_OPS_CONTENT_HASH" => @x_ops_content_hash, "HTTP_X_OPS_USERID" => @user_id, "HTTP_X_OPS_AUTHORIZATION_1" => @http_x_ops_lines[0], "HTTP_X_OPS_AUTHORIZATION_2" => @http_x_ops_lines[1], "HTTP_X_OPS_AUTHORIZATION_3" => @http_x_ops_lines[2], "HTTP_X_OPS_AUTHORIZATION_4" => @http_x_ops_lines[3], "HTTP_X_OPS_AUTHORIZATION_5" => @http_x_ops_lines[4], "HTTP_X_OPS_AUTHORIZATION_6" => @http_x_ops_lines[5], # Random sampling "REMOTE_ADDR" => "127.0.0.1", "PATH_INFO" => "/organizations/local-test-org/cookbooks", "REQUEST_PATH" => "/organizations/local-test-org/cookbooks", "CONTENT_TYPE" => "multipart/form-data; boundary=----RubyMultipartClient6792ZZZZZ", "CONTENT_LENGTH" => "394", } @request = request.new(@merb_headers, "POST", "/nodes") @http_authentication_request = Mixlib::Authentication::HTTPAuthenticationRequest.new(@request) end it "normalizes the headers to lowercase symbols" do expected = { :host => "127.0.0.1", :x_ops_sign => "version=1.0", :x_ops_requestid => "127.0.0.1 1258566194.85386", :x_ops_timestamp => "2009-01-01T12:00:00Z", :x_ops_content_hash => "DFteJZPVv6WKdQmMqZUQUumUyRs=", :x_ops_userid => "spec-user", :x_ops_authorization_1 => "<KEY>", :x_ops_authorization_2 => "<KEY>", :x_ops_authorization_3 => "<KEY>", :x_ops_authorization_4 => "<KEY>", :x_ops_authorization_5 => "<KEY>", :x_ops_authorization_6 => "<KEY> } expect(@http_authentication_request.headers).to eq(expected) end it "raises an error when not all required headers are given" do @merb_headers.delete("HTTP_X_OPS_SIGN") exception = Mixlib::Authentication::MissingAuthenticationHeader expect { Mixlib::Authentication::HTTPAuthenticationRequest.new(@request) }.to raise_error(exception) end it "extracts the path from the request" do expect(@http_authentication_request.path).to eq("/nodes") end it "extracts the request method from the request" do expect(@http_authentication_request.http_method).to eq("POST") end it "extracts the signing description from the request headers" do expect(@http_authentication_request.signing_description).to eq("version=1.0") end it "extracts the user_id from the request headers" do expect(@http_authentication_request.user_id).to eq("spec-user") end it "extracts the timestamp from the request headers" do expect(@http_authentication_request.timestamp).to eq("2009-01-01T12:00:00Z") end it "extracts the host from the request headers" do expect(@http_authentication_request.host).to eq("127.0.0.1") end it "extracts the content hash from the request headers" do expect(@http_authentication_request.content_hash).to eq("DFteJZPVv6WKdQmMqZUQUumUyRs=") end it "rebuilds the request signature from the headers" do expected = <<-SIG jVHrNniWzpbez/eGWjFnO6lINRIuKOg40ZTIQudcFe47Z9e/HvrszfVXlKG4 N<KEY> SIG expect(@http_authentication_request.request_signature).to eq(expected.chomp) end it "defaults to server api version 0" do expect(@http_authentication_request.server_api_version).to eq("0") end end
arnab0073/idea
.rvm/src/ruby-2.3.0/test/rubygems/good_rake.rb
# frozen_string_literal: false exit 0
arnab0073/idea
.rvm/src/ruby-2.3.0/test/rdoc/test_rdoc_rd.rb
<reponame>arnab0073/idea # frozen_string_literal: false require 'rdoc/test_case' class TestRDocRd < RDoc::TestCase def test_class_parse expected = @RM::Document.new( @RM::Paragraph.new('hello')) assert_equal expected, RDoc::RD.parse("hello") end def test_class_parse_begin_end expected = @RM::Document.new( @RM::Paragraph.new('hello')) assert_equal expected, RDoc::RD.parse("=begin\nhello\n=end\n") end def test_class_parse_newline expected = @RM::Document.new( @RM::Paragraph.new('hello')) assert_equal expected, RDoc::RD.parse("hello\n") end end
arnab0073/idea
.rvm/src/ruby-2.3.0/ext/date/extconf.rb
<filename>.rvm/src/ruby-2.3.0/ext/date/extconf.rb # frozen_string_literal: false require 'mkmf' config_string("strict_warnflags") {|w| $warnflags += " #{w}"} create_makefile('date_core')
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/menubar3.rb
<gh_stars>0 # # menubar sample 3 : vertical layout menubar; use frame and menubuttons # require 'tk' radio_var = TkVariable.new('y') menu_spec = [ [['&File', true], # when underline option is ture, '&' index is the position {:label=>'Open', :command=>proc{puts('Open clicked')}, :underline=>0}, '---', ['Check_A', TkVariable.new(true), 6], {:type=>'checkbutton', :label=>'Check_B', :variable=>TkVariable.new, :underline=>6}, '---', ['Radio_X', [radio_var, 'x'], /[XYZ]/, '', {:foreground=>'black'}], ['Radio_Y', [radio_var, 'y'], /[XYZ]/], ['Radio_Z', [radio_var, 'z'], /[XYZ]/], # use Regexp for underline position '---', ['cascade', [ ['sss', proc{p 'sss'}, 0], ['ttt', proc{p 'ttt'}, 0], ['uuu', proc{p 'uuu'}, 0], ['vvv', proc{p 'vvv'}, 0], ], 0, '', {:font=>'Courier 16 italic', :menu_config=>{:font=>'Times -18 bold', :foreground=>'black'}}], '---', ['Quit', proc{exit}, 0]], [['Edit', 0], ['Cut', proc{puts('Cut clicked')}, 2], ['Copy', proc{puts('Copy clicked')}, 0], ['Paste', proc{puts('Paste clicked')}, 0]], [['Help', 0, {:menu_name=>'help'}], ['About This', proc{puts('Ruby/Tk menubar sample 3')}, "This"]] # use string index for underline position ] layout_proc = 'vertical' # The following procedure is same to 'layout_proc'=>'vertical' =begin layout_proc = proc{|parent, mbtn| mbtn.direction :right mbtn.pack(:side=>:top, :fill=>:x) menu = mbtn.menu cmd = proc{|m, dir| Tk::Menu::TkInternalFunction.next_menu(m, dir) rescue nil # ignore error when the internal function doesn't exist } menu.bind('Tab', cmd, :widget, 'forward') menu.bind('Alt-Tab', cmd, :widget, 'backward') } =end menubar = TkMenubar.new(nil, menu_spec, 'layout_proc'=>layout_proc, 'tearoff'=>false, 'foreground'=>'grey40', 'activeforeground'=>'red', 'font'=>'Helvetia 12 bold') menubar.pack('side'=>'left', 'fill'=>'y') TkText.new(:wrap=>'word').pack.insert('1.0', 'This sample script generates "Menu Sidebar". If "::tk::MenuNextMenuon" function is available your Tcl/Tk library, you will be able to move to the next menu by Tab key on the posted menu, or the previous menu by Alt + Tab key. Please read the sample source, and check how to override default configure options of menu entries on a menu_spec. Maybe, on windows, this menubar does not work properly about keyboard shortcuts. Then, please use "menu" option of root/toplevel widget (see sample/menubar3.rb).') Tk.mainloop
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/net-ssh-multi-1.2.0/test/session_actions_test.rb
require 'common' require 'net/ssh/multi/server' require 'net/ssh/multi/session_actions' class SessionActionsTest < Test::Unit::TestCase class SessionActionsContainer include Net::SSH::Multi::SessionActions attr_reader :servers def initialize @servers = [] end def default_user "user" end def use(h, o={}) server = Net::SSH::Multi::Server.new(self, h, o) servers << server server end end def setup @session = SessionActionsContainer.new end def test_busy_should_be_true_if_any_server_is_busy srv1, srv2, srv3 = @session.use('h1'), @session.use('h2'), @session.use('h3') srv1.stubs(:busy?).returns(false) srv2.stubs(:busy?).returns(false) srv3.stubs(:busy?).returns(true) assert @session.busy? end def test_busy_should_be_false_if_all_servers_are_not_busy srv1, srv2, srv3 = @session.use('h1'), @session.use('h2'), @session.use('h3') srv1.stubs(:busy?).returns(false) srv2.stubs(:busy?).returns(false) srv3.stubs(:busy?).returns(false) assert !@session.busy? end def test_send_global_request_should_delegate_to_sessions s1 = mock('ssh') s2 = mock('ssh') s1.expects(:send_global_request).with("a", "b", "c").yields s2.expects(:send_global_request).with("a", "b", "c").yields @session.expects(:sessions).returns([s1, s2]) calls = 0 @session.send_global_request("a", "b", "c") { calls += 1 } assert_equal 2, calls end def test_open_channel_should_delegate_to_sessions_and_set_accessors_on_each_channel_and_return_multi_channel srv1 = @session.use('h1') srv2 = @session.use('h2') s1 = { :server => srv1 } s2 = { :server => srv2 } c1 = { :stub => :value } c2 = {} c1.stubs(:connection).returns(s1) c2.stubs(:connection).returns(s2) @session.expects(:sessions).returns([s1, s2]) s1.expects(:open_channel).with("session").yields(c1).returns(c1) s2.expects(:open_channel).with("session").yields(c2).returns(c2) results = [] channel = @session.open_channel do |c| results << c end assert_equal [c1, c2], results assert_equal "h1", c1[:host] assert_equal "h2", c2[:host] assert_equal srv1, c1[:server] assert_equal srv2, c2[:server] assert_instance_of Net::SSH::Multi::Channel, channel assert_equal [c1, c2], channel.channels end def test_exec_should_raise_exception_if_channel_cannot_exec_command c = { :host => "host" } @session.expects(:open_channel).yields(c).returns(c) c.expects(:exec).with('something').yields(c, false) assert_raises(RuntimeError) { @session.exec("something") } end def test_exec_with_block_should_pass_data_and_extended_data_to_block c = { :host => "host" } @session.expects(:open_channel).yields(c).returns(c) c.expects(:exec).with('something').yields(c, true) c.expects(:on_data).yields(c, "stdout") c.expects(:on_extended_data).yields(c, 1, "stderr") c.expects(:on_request) results = {} @session.exec("something") do |c, stream, data| results[stream] = data end assert_equal({:stdout => "stdout", :stderr => "stderr"}, results) end def test_exec_without_block_should_write_data_and_extended_data_lines_to_stdout_and_stderr c = { :host => "host" } @session.expects(:open_channel).yields(c).returns(c) c.expects(:exec).with('something').yields(c, true) c.expects(:on_data).yields(c, "stdout 1\nstdout 2\n") c.expects(:on_extended_data).yields(c, 1, "stderr 1\nstderr 2\n") c.expects(:on_request) $stdout.expects(:puts).with("[host] stdout 1\n") $stdout.expects(:puts).with("[host] stdout 2") $stderr.expects(:puts).with("[host] stderr 1\n") $stderr.expects(:puts).with("[host] stderr 2") @session.exec("something") end def test_exec_should_capture_exit_status_of_process c = { :host => "host" } @session.expects(:open_channel).yields(c).returns(c) c.expects(:exec).with('something').yields(c, true) c.expects(:on_data) c.expects(:on_extended_data) c.expects(:on_request).with("exit-status").yields(c, Net::SSH::Buffer.from(:long, 127)) @session.exec("something") assert_equal 127, c[:exit_status] end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/xenserver/requests/compute/destroy_network.rb
<gh_stars>1-10 module Fog module Compute class XenServer class Real # # Destroy a Network # # @see http://docs.vmd.citrix.com/XenServer/6.0.0/1.0/en_gb/api/?c=network # def destroy_network( ref ) Fog::Logger.deprecation( 'This method is deprecated. Use #destroy_record instead.' ) @connection.request( { :parser => Fog::Parsers::XenServer::Base.new, :method => 'network.destroy' }, ref ) end end class Mock def destroy_network( ref ) Fog::Mock.not_implemented end end end end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/lib/irb.rb
<reponame>arnab0073/idea<gh_stars>0 # # irb.rb - irb main module # $Release Version: 0.9.6 $ # $Revision: 31641 $ # by <NAME>(<EMAIL>) # # -- # # # require "e2mmap" require "irb/init" require "irb/context" require "irb/extend-command" #require "irb/workspace" require "irb/ruby-lex" require "irb/input-method" require "irb/locale" STDOUT.sync = true module IRB @RCS_ID='-$Id: irb.rb 31641 2011-05-19 00:07:25Z nobu $-' class Abort < Exception;end # @CONF = {} def IRB.conf @CONF end # IRB version method def IRB.version if v = @CONF[:VERSION] then return v end require "irb/version" rv = @RELEASE_VERSION.sub(/\.0/, "") @CONF[:VERSION] = format("irb %s(%s)", rv, @LAST_UPDATE_DATE) end def IRB.CurrentContext IRB.conf[:MAIN_CONTEXT] end # initialize IRB and start TOP_LEVEL irb def IRB.start(ap_path = nil) $0 = File::basename(ap_path, ".rb") if ap_path IRB.setup(ap_path) if @CONF[:SCRIPT] irb = Irb.new(nil, @CONF[:SCRIPT]) else irb = Irb.new end @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] @CONF[:MAIN_CONTEXT] = irb.context trap("SIGINT") do irb.signal_handle end begin catch(:IRB_EXIT) do irb.eval_input end ensure irb_at_exit end # print "\n" end def IRB.irb_at_exit @CONF[:AT_EXIT].each{|hook| hook.call} end def IRB.irb_exit(irb, ret) throw :IRB_EXIT, ret end def IRB.irb_abort(irb, exception = Abort) if defined? Thread irb.context.thread.raise exception, "abort then interrupt!" else raise exception, "abort then interrupt!" end end # # irb interpreter main routine # class Irb def initialize(workspace = nil, input_method = nil, output_method = nil) @context = Context.new(self, workspace, input_method, output_method) @context.main.extend ExtendCommandBundle @signal_status = :IN_IRB @scanner = RubyLex.new @scanner.exception_on_syntax_error = false end attr_reader :context attr_accessor :scanner def eval_input @scanner.set_prompt do |ltype, indent, continue, line_no| if ltype f = @context.prompt_s elsif continue f = @context.prompt_c elsif indent > 0 f = @context.prompt_n else f = @context.prompt_i end f = "" unless f if @context.prompting? @context.io.prompt = p = prompt(f, ltype, indent, line_no) else @context.io.prompt = p = "" end if @context.auto_indent_mode unless ltype ind = prompt(@context.prompt_i, ltype, indent, line_no)[/.*\z/].size + indent * 2 - p.size ind += 2 if continue @context.io.prompt = p + " " * ind if ind > 0 end end end @scanner.set_input(@context.io) do signal_status(:IN_INPUT) do if l = @context.io.gets print l if @context.verbose? else if @context.ignore_eof? and @context.io.readable_atfer_eof? l = "\n" if @context.verbose? printf "Use \"exit\" to leave %s\n", @context.ap_name end else print "\n" end end l end end @scanner.each_top_level_statement do |line, line_no| signal_status(:IN_EVAL) do begin line.untaint @context.evaluate(line, line_no) output_value if @context.echo? exc = nil rescue Interrupt => exc rescue SystemExit, SignalException raise rescue Exception => exc end if exc print exc.class, ": ", exc, "\n" if exc.backtrace[0] =~ /irb(2)?(\/.*|-.*|\.rb)?:/ && exc.class.to_s !~ /^IRB/ && !(SyntaxError === exc) irb_bug = true else irb_bug = false end messages = [] lasts = [] levels = 0 for m in exc.backtrace m = @context.workspace.filter_backtrace(m) unless irb_bug if m if messages.size < @context.back_trace_limit messages.push "\tfrom "+m else lasts.push "\tfrom "+m if lasts.size > @context.back_trace_limit lasts.shift levels += 1 end end end end print messages.join("\n"), "\n" unless lasts.empty? printf "... %d levels...\n", levels if levels > 0 print lasts.join("\n") end print "Maybe IRB bug!\n" if irb_bug end if $SAFE > 2 abort "Error: irb does not work for $SAFE level higher than 2" end end end end def suspend_name(path = nil, name = nil) @context.irb_path, back_path = path, @context.irb_path if path @context.irb_name, back_name = name, @context.irb_name if name begin yield back_path, back_name ensure @context.irb_path = back_path if path @context.irb_name = back_name if name end end def suspend_workspace(workspace) @context.workspace, back_workspace = workspace, @context.workspace begin yield back_workspace ensure @context.workspace = back_workspace end end def suspend_input_method(input_method) back_io = @context.io @context.instance_eval{@io = input_method} begin yield back_io ensure @context.instance_eval{@io = back_io} end end def suspend_context(context) @context, back_context = context, @context begin yield back_context ensure @context = back_context end end def signal_handle unless @context.ignore_sigint? print "\nabort!\n" if @context.verbose? exit end case @signal_status when :IN_INPUT print "^C\n" raise RubyLex::TerminateLineInput when :IN_EVAL IRB.irb_abort(self) when :IN_LOAD IRB.irb_abort(self, LoadAbort) when :IN_IRB # ignore else # ignore other cases as well end end def signal_status(status) return yield if @signal_status == :IN_LOAD signal_status_back = @signal_status @signal_status = status begin yield ensure @signal_status = signal_status_back end end def prompt(prompt, ltype, indent, line_no) p = prompt.dup p.gsub!(/%([0-9]+)?([a-zA-Z])/) do case $2 when "N" @context.irb_name when "m" @context.main.to_s when "M" @context.main.inspect when "l" ltype when "i" if $1 format("%" + $1 + "d", indent) else indent.to_s end when "n" if $1 format("%" + $1 + "d", line_no) else line_no.to_s end when "%" "%" end end p end def output_value printf @context.return_format, @context.inspect_last_value end def inspect ary = [] for iv in instance_variables case (iv = iv.to_s) when "@signal_status" ary.push format("%s=:%s", iv, @signal_status.id2name) when "@context" ary.push format("%s=%s", iv, eval(iv).__to_s__) else ary.push format("%s=%s", iv, eval(iv)) end end format("#<%s: %s>", self.class, ary.join(", ")) end end # Singleton method def @CONF.inspect IRB.version unless self[:VERSION] array = [] for k, v in sort{|a1, a2| a1[0].id2name <=> a2[0].id2name} case k when :MAIN_CONTEXT, :__TMP__EHV__ array.push format("CONF[:%s]=...myself...", k.id2name) when :PROMPT s = v.collect{ |kk, vv| ss = vv.collect{|kkk, vvv| ":#{kkk.id2name}=>#{vvv.inspect}"} format(":%s=>{%s}", kk.id2name, ss.join(", ")) } array.push format("CONF[:%s]={%s}", k.id2name, s.join(", ")) else array.push format("CONF[:%s]=%s", k.id2name, v.inspect) end end array.join("\n") end end
arnab0073/idea
.rvm/src/ruby-2.3.0/test/nkf/test_kconv.rb
# frozen_string_literal: false require 'test/unit' require 'kconv' class TestKconv < Test::Unit::TestCase def setup @euc_str = "\ \xa5\xaa\xa5\xd6\xa5\xb8\xa5\xa7\xa5\xaf\xa5\xc8\xbb\xd8\xb8\xfe\ \xa5\xd7\xa5\xed\xa5\xb0\xa5\xe9\xa5\xdf\xa5\xf3\xa5\xb0\xb8\xc0\xb8\xec \x52\x75\x62\x79".force_encoding('EUC-JP') @utf8_str = "\ \xe3\x82\xaa\xe3\x83\x96\xe3\x82\xb8\xe3\x82\xa7\ \xe3\x82\xaf\xe3\x83\x88\xe6\x8c\x87\xe5\x90\x91\ \xe3\x83\x97\xe3\x83\xad\xe3\x82\xb0\xe3\x83\xa9\xe3\x83\x9f\ \xe3\x83\xb3\xe3\x82\xb0\xe8\xa8\x80\xe8\xaa\x9e \x52\x75\x62\x79".force_encoding('UTF-8') @sjis_str = "\ \x83\x49\x83\x75\x83\x57\x83\x46\x83\x4e\x83\x67\x8e\x77\x8c\xfc\ \x83\x76\x83\x8d\x83\x4f\x83\x89\x83\x7e\x83\x93\x83\x4f\x8c\xbe\x8c\xea \x52\x75\x62\x79".force_encoding('Shift_JIS') @jis_str = "\ \x1b\x24\x42\x25\x2a\x25\x56\x25\x38\x25\x27\x25\x2f\x25\x48\x3b\x58\x38\x7e\ \x25\x57\x25\x6d\x25\x30\x25\x69\x25\x5f\x25\x73\x25\x30\x38\x40\x38\x6c\x1b\x28\x42 \x52\x75\x62\x79".force_encoding('ISO-2022-JP') end def test_eucjp assert(@euc_str.iseuc) assert_equal(::Kconv::EUC, Kconv.guess(@euc_str)) assert_equal(@euc_str, @euc_str.toeuc) assert_equal(@euc_str, @sjis_str.toeuc) assert_equal(@euc_str, @utf8_str.toeuc) assert_equal(@euc_str, @jis_str.toeuc) assert_equal(@euc_str, @euc_str.kconv(::NKF::EUC)) assert_equal(@euc_str, @sjis_str.kconv(::NKF::EUC)) assert_equal(@euc_str, @utf8_str.kconv(::NKF::EUC)) assert_equal(@euc_str, @jis_str.kconv(::NKF::EUC)) end def test_shiftjis assert(@sjis_str.issjis) assert_equal(::Kconv::SJIS, Kconv.guess(@sjis_str)) assert_equal(@sjis_str, @euc_str.tosjis) assert_equal(@sjis_str, @sjis_str.tosjis) assert_equal(@sjis_str, @utf8_str.tosjis) assert_equal(@sjis_str, @jis_str.tosjis) assert_equal(@sjis_str, @euc_str.kconv(::NKF::SJIS)) assert_equal(@sjis_str, @sjis_str.kconv(::NKF::SJIS)) assert_equal(@sjis_str, @utf8_str.kconv(::NKF::SJIS)) assert_equal(@sjis_str, @jis_str.kconv(::NKF::SJIS)) end def test_utf8 assert(@utf8_str.isutf8) assert_equal(::Kconv::UTF8, Kconv.guess(@utf8_str)) assert_equal(@utf8_str, @euc_str.toutf8) assert_equal(@utf8_str, @sjis_str.toutf8) assert_equal(@utf8_str, @utf8_str.toutf8) assert_equal(@utf8_str, @jis_str.toutf8) assert_equal(@utf8_str, @euc_str.kconv(::NKF::UTF8)) assert_equal(@utf8_str, @sjis_str.kconv(::NKF::UTF8)) assert_equal(@utf8_str, @utf8_str.kconv(::NKF::UTF8)) assert_equal(@utf8_str, @jis_str.kconv(::NKF::UTF8)) end def test_jis assert_equal(::Kconv::JIS, Kconv.guess(@jis_str)) assert_equal(@jis_str, @euc_str.tojis) assert_equal(@jis_str, @sjis_str.tojis) assert_equal(@jis_str, @utf8_str.tojis) assert_equal(@jis_str, @jis_str.tojis) assert_equal(@jis_str, @euc_str.kconv(::NKF::JIS)) assert_equal(@jis_str, @sjis_str.kconv(::NKF::JIS)) assert_equal(@jis_str, @utf8_str.kconv(::NKF::JIS)) assert_equal(@jis_str, @jis_str.kconv(::NKF::JIS)) end def test_kconv str = "\xc2\xa1" %w/UTF-8 EUC-JP/.each do |enc| s = str.dup.force_encoding(enc) assert_equal(s, s.kconv(enc)) end end end
arnab0073/idea
.rvm/src/ruby-2.3.0/test/rdoc/test_rdoc_markup_to_ansi.rb
# frozen_string_literal: false require 'rdoc/test_case' class TestRDocMarkupToAnsi < RDoc::Markup::TextFormatterTestCase add_visitor_tests add_text_tests def setup super @to = RDoc::Markup::ToAnsi.new end def accept_blank_line assert_equal "\e[0m\n", @to.res.join end def accept_block_quote assert_equal "\e[0m> quote\n", @to.res.join end def accept_document assert_equal "\e[0mhello\n", @to.res.join end def accept_heading assert_equal "\e[0mHello\n", @to.res.join end def accept_list_end_bullet assert_empty @to.list_index assert_empty @to.list_type assert_empty @to.list_width end def accept_list_end_label assert_empty @to.list_index assert_empty @to.list_type assert_empty @to.list_width end def accept_list_end_lalpha assert_empty @to.list_index assert_empty @to.list_type assert_empty @to.list_width end def accept_list_end_note assert_empty @to.list_index assert_empty @to.list_type assert_empty @to.list_width end def accept_list_end_number assert_empty @to.list_index assert_empty @to.list_type assert_empty @to.list_width end def accept_list_end_ualpha assert_empty @to.list_index assert_empty @to.list_type assert_empty @to.list_width end def accept_list_item_end_bullet assert_equal 0, @to.indent, 'indent' end def accept_list_item_end_label assert_equal "\e[0mcat:\n", @to.res.join assert_equal 0, @to.indent, 'indent' end def accept_list_item_end_lalpha assert_equal 0, @to.indent, 'indent' assert_equal 'b', @to.list_index.last end def accept_list_item_end_note assert_equal "\e[0mcat:\n", @to.res.join assert_equal 0, @to.indent, 'indent' end def accept_list_item_end_number assert_equal 0, @to.indent, 'indent' assert_equal 2, @to.list_index.last end def accept_list_item_end_ualpha assert_equal 0, @to.indent, 'indent' assert_equal 'B', @to.list_index.last end def accept_list_item_start_bullet assert_equal %W"\e[0m", @to.res assert_equal '* ', @to.prefix end def accept_list_item_start_label assert_equal %W"\e[0m", @to.res assert_equal "cat:\n ", @to.prefix assert_equal 2, @to.indent end def accept_list_item_start_lalpha assert_equal %W"\e[0m", @to.res assert_equal 'a. ', @to.prefix assert_equal 'a', @to.list_index.last assert_equal 3, @to.indent end def accept_list_item_start_note assert_equal %W"\e[0m", @to.res assert_equal "cat:\n ", @to.prefix assert_equal 2, @to.indent end def accept_list_item_start_number assert_equal %W"\e[0m", @to.res assert_equal '1. ', @to.prefix assert_equal 1, @to.list_index.last assert_equal 3, @to.indent end def accept_list_item_start_ualpha assert_equal %W"\e[0m", @to.res assert_equal 'A. ', @to.prefix assert_equal 'A', @to.list_index.last assert_equal 3, @to.indent end def accept_list_start_bullet assert_equal "\e[0m", @to.res.join assert_equal [nil], @to.list_index assert_equal [:BULLET], @to.list_type assert_equal [1], @to.list_width end def accept_list_start_label assert_equal "\e[0m", @to.res.join assert_equal [nil], @to.list_index assert_equal [:LABEL], @to.list_type assert_equal [2], @to.list_width end def accept_list_start_lalpha assert_equal "\e[0m", @to.res.join assert_equal ['a'], @to.list_index assert_equal [:LALPHA], @to.list_type assert_equal [1], @to.list_width end def accept_list_start_note assert_equal "\e[0m", @to.res.join assert_equal [nil], @to.list_index assert_equal [:NOTE], @to.list_type assert_equal [2], @to.list_width end def accept_list_start_number assert_equal "\e[0m", @to.res.join assert_equal [1], @to.list_index assert_equal [:NUMBER], @to.list_type assert_equal [1], @to.list_width end def accept_list_start_ualpha assert_equal "\e[0m", @to.res.join assert_equal ['A'], @to.list_index assert_equal [:UALPHA], @to.list_type assert_equal [1], @to.list_width end def accept_paragraph assert_equal "\e[0mhi\n", @to.res.join end def accept_raw raw = <<-RAW.rstrip \e[0m<table> <tr><th>Name<th>Count <tr><td>a<td>1 <tr><td>b<td>2 </table> RAW assert_equal raw, @to.res.join end def accept_rule assert_equal "\e[0m#{'-' * 78}\n", @to.res.join end def accept_verbatim assert_equal "\e[0m hi\n world\n\n", @to.res.join end def end_accepting assert_equal "\e[0mhi", @to.end_accepting end def start_accepting assert_equal 0, @to.indent assert_equal %W"\e[0m", @to.res assert_empty @to.list_index assert_empty @to.list_type assert_empty @to.list_width end def accept_heading_1 assert_equal "\e[0m\e[1;32mHello\e[m\n", @to.end_accepting end def accept_heading_2 assert_equal "\e[0m\e[4;32mHello\e[m\n", @to.end_accepting end def accept_heading_3 assert_equal "\e[0m\e[32mHello\e[m\n", @to.end_accepting end def accept_heading_4 assert_equal "\e[0mHello\n", @to.end_accepting end def accept_heading_indent assert_equal "\e[0m \e[1;32mHello\e[m\n", @to.end_accepting end def accept_heading_b assert_equal "\e[0m\e[1;32m\e[1mHello\e[m\e[m\n", @to.end_accepting end def accept_heading_suppressed_crossref assert_equal "\e[0m\e[1;32mHello\e[m\n", @to.end_accepting end def accept_list_item_start_note_2 assert_equal "\e[0m\e[7mteletype\e[m:\n teletype description\n\n", @to.res.join end def accept_list_item_start_note_multi_description assert_equal "\e[0mlabel:\n description one\n\n description two\n\n", @to.res.join end def accept_list_item_start_note_multi_label assert_equal "\e[0mone\ntwo:\n two headers\n\n", @to.res.join end def accept_paragraph_b assert_equal "\e[0mreg \e[1mbold words\e[m reg\n", @to.end_accepting end def accept_paragraph_br assert_equal "\e[0mone\ntwo\n", @to.end_accepting end def accept_paragraph_break assert_equal "\e[0mhello\nworld\n", @to.end_accepting end def accept_paragraph_i assert_equal "\e[0mreg \e[4mitalic words\e[m reg\n", @to.end_accepting end def accept_paragraph_indent expected = <<-EXPECTED \e[0m words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words EXPECTED assert_equal expected, @to.end_accepting end def accept_paragraph_plus assert_equal "\e[0mreg \e[7mteletype\e[m reg\n", @to.end_accepting end def accept_paragraph_star assert_equal "\e[0mreg \e[1mbold\e[m reg\n", @to.end_accepting end def accept_paragraph_underscore assert_equal "\e[0mreg \e[4mitalic\e[m reg\n", @to.end_accepting end def accept_paragraph_wrap expected = <<-EXPECTED \e[0mwords words words words words words words words words words words words words words words words words words words words words words words words words words words words words words EXPECTED assert_equal expected, @to.end_accepting end def accept_rule_indent assert_equal "\e[0m #{'-' * 75}\n", @to.end_accepting end def accept_verbatim_indent assert_equal "\e[0m hi\n world\n\n", @to.end_accepting end def accept_verbatim_big_indent assert_equal "\e[0m hi\n world\n\n", @to.end_accepting end def list_nested expected = <<-EXPECTED \e[0m* l1 * l1.1 * l2 EXPECTED assert_equal expected, @to.end_accepting end def list_verbatim expected = <<-EXPECTED # HACK overblown \e[0m* list stuff * list with second 1. indented 2. numbered third * second EXPECTED assert_equal expected, @to.end_accepting end # functional test def test_convert_list_note note_list = <<-NOTE_LIST foo :: bar :: hi NOTE_LIST expected = <<-EXPECTED \e[0mfoo bar: hi EXPECTED assert_equal expected, @to.convert(note_list) end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/iwidgets/disjointlistbox.rb
# # tkextlib/iwidgets/disjointlistbox.rb # by <NAME> (<EMAIL>) # require 'tk' require 'tkextlib/iwidgets.rb' module Tk module Iwidgets class Disjointlistbox < Tk::Itk::Widget end end end class Tk::Iwidgets::Disjointlistbox TkCommandNames = ['::iwidgets::disjointlistbox'.freeze].freeze WidgetClassName = 'Disjointlistbox'.freeze WidgetClassNames[WidgetClassName] ||= self def __strval_optkeys super() << 'lhslabeltext' << 'rhslabeltext' << 'lhsbuttonlabel' << 'rhsbuttonlabel' end private :__strval_optkeys def set_lhs(*items) tk_call(@path, 'setlhs', items) self end def set_rhs(*items) tk_call(@path, 'setrhs', items) self end def get_lhs simplelist(tk_call(@path, 'getlhs')) end def get_rhs simplelist(tk_call(@path, 'getrhs')) end def insert_lhs(*items) tk_call(@path, 'insertlhs', items) self end def insert_rhs(*items) tk_call(@path, 'insertrhs', items) self end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/excon-0.49.0/lib/excon/middlewares/instrumentor.rb
module Excon module Middleware class Instrumentor < Excon::Middleware::Base def error_call(datum) if datum.has_key?(:instrumentor) datum[:instrumentor].instrument("#{datum[:instrumentor_name]}.error", :error => datum[:error]) do @stack.error_call(datum) end else @stack.error_call(datum) end end def request_call(datum) if datum.has_key?(:instrumentor) if datum[:retries_remaining] < datum[:retry_limit] event_name = "#{datum[:instrumentor_name]}.retry" else event_name = "#{datum[:instrumentor_name]}.request" end datum[:instrumentor].instrument(event_name, datum) do @stack.request_call(datum) end else @stack.request_call(datum) end end def response_call(datum) if datum.has_key?(:instrumentor) datum[:instrumentor].instrument("#{datum[:instrumentor_name]}.response", datum[:response]) do @stack.response_call(datum) end else @stack.response_call(datum) end end end end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/demos-en/style.rb
<reponame>arnab0073/idea # style.rb # # This demonstration script creates a text widget that illustrates the # various display styles that may be set for tags. # # text (display styles) widget demo (called by 'widget') # # toplevel widget if defined?($style_demo) && $style_demo $style_demo.destroy $style_demo = nil end # demo toplevel widget $style_demo = TkToplevel.new {|w| title("Text Demonstration - Display Styles") iconname("style") positionWindow(w) } base_frame = TkFrame.new($style_demo).pack(:fill=>:both, :expand=>true) # frame TkFrame.new(base_frame) {|frame| TkButton.new(frame) { text 'Dismiss' command proc{ tmppath = $style_demo $style_demo = nil tmppath.destroy } }.pack('side'=>'left', 'expand'=>'yes') TkButton.new(frame) { text 'Show Code' command proc{showCode 'style'} }.pack('side'=>'left', 'expand'=>'yes') }.pack('side'=>'bottom', 'fill'=>'x', 'pady'=>'2m') # text txt = TkText.new(base_frame){|t| # setgrid 'true' #width 70 #height 32 wrap 'word' font $font TkScrollbar.new(base_frame) {|s| pack('side'=>'right', 'fill'=>'y') command proc{|*args| t.yview(*args)} t.yscrollcommand proc{|first,last| s.set first,last} } pack('expand'=>'yes', 'fill'=>'both') # family = 'Courier' if $tk_version =~ /^4.*/ style_tag_bold = TkTextTag.new(t, 'font'=>'-*-Courier-Bold-O-Normal--*-120-*-*-*-*-*-*') style_tag_big = TkTextTag.new(t, 'font'=>'-*-Courier-Bold-R-Normal--*-140-*-*-*-*-*-*', 'kanjifont'=>$msg_kanji_font) style_tag_verybig = TkTextTag.new(t, 'font'=>'-*-Helvetica-Bold-R-Normal--*-240-*-*-*-*-*-*') # style_tag_small = TkTextTag.new(t, 'font'=>'-Adobe-Helvetica-Bold-R-Normal-*-100-*', 'kanjifont'=>$kanji_font) style_tag_small = TkTextTag.new(t, 'font'=>'-Adobe-Helvetica-Bold-R-Normal-*-100-*') else style_tag_bold = TkTextTag.new(t, 'font'=>[family, 12, :bold, :italic]) style_tag_big = TkTextTag.new(t, 'font'=>[family, 14, :bold]) style_tag_verybig = TkTextTag.new(t, 'font'=>['Helvetica', 24, :bold]) style_tag_small = TkTextTag.new(t, 'font'=>'Times 8 bold') end ### # case($tk_version) # when /^4.*/ # style_tag_big = TkTextTag.new(t, 'font'=>'-*-Courier-Bold-R-Normal--*-140-*-*-*-*-*-*', 'kanjifont'=>$msg_kanji_font) # style_tag_small = TkTextTag.new(t, 'font'=>'-Adobe-Helvetica-Bold-R-Normal-*-100-*', 'kanjifont'=>$kanji_font) # when /^8.*/ # unless $style_demo_do_first # $style_demo_do_first = true # Tk.tk_call('font', 'create', '@bigascii', # '-copy', '-*-Courier-Bold-R-Normal--*-140-*-*-*-*-*-*') # Tk.tk_call('font', 'create', '@smallascii', # '-copy', '-Adobe-Helvetica-Bold-R-Normal-*-100-*') # Tk.tk_call('font', 'create', '@cBigFont', # '-compound', '@bigascii @msg_knj') # Tk.tk_call('font', 'create', '@cSmallFont', # '-compound', '@smallascii @kanji') # end # style_tag_big = TkTextTag.new(t, 'font'=>'@cBigFont') # style_tag_small = TkTextTag.new(t, 'font'=>'@cSmallFont') # end # if TkWinfo.depth($root).to_i > 1 style_tag_color1 = TkTextTag.new(t, 'background'=>'#a0b7ce') style_tag_color2 = TkTextTag.new(t, 'foreground'=>'red') style_tag_raised = TkTextTag.new(t, 'relief'=>'raised', 'borderwidth'=>1) style_tag_sunken = TkTextTag.new(t, 'relief'=>'sunken', 'borderwidth'=>1) else style_tag_color1 = TkTextTag.new(t, 'background'=>'black', 'foreground'=>'white') style_tag_color2 = TkTextTag.new(t, 'background'=>'black', 'foreground'=>'white') style_tag_raised = TkTextTag.new(t, 'background'=>'white', 'relief'=>'raised', 'borderwidth'=>1) style_tag_sunken = TkTextTag.new(t, 'background'=>'white', 'relief'=>'sunken', 'borderwidth'=>1) end # if $tk_version =~ /^4\.[01]/ style_tag_bgstipple = TkTextTag.new(t, 'background'=>'black', 'borderwidth'=>0, 'bgstipple'=>'gray25') else style_tag_bgstipple = TkTextTag.new(t, 'background'=>'black', 'borderwidth'=>0, 'bgstipple'=>'gray12') end style_tag_fgstipple = TkTextTag.new(t, 'fgstipple'=>'gray50') style_tag_underline = TkTextTag.new(t, 'underline'=>'on') style_tag_overstrike = TkTextTag.new(t, 'overstrike'=>'on') style_tag_right = TkTextTag.new(t, 'justify'=>'right') style_tag_center = TkTextTag.new(t, 'justify'=>'center') if $tk_version =~ /^4.*/ style_tag_super = TkTextTag.new(t, 'offset'=>'4p', 'font'=>'-Adobe-Courier-Medium-R-Normal--*-100-*-*-*-*-*-*') style_tag_sub = TkTextTag.new(t, 'offset'=>'-2p', 'font'=>'-Adobe-Courier-Medium-R-Normal--*-100-*-*-*-*-*-*') else style_tag_super = TkTextTag.new(t, 'offset'=>'4p', 'font'=>[family, 10]) style_tag_sub = TkTextTag.new(t, 'offset'=>'-2p', 'font'=>[family, 10]) end style_tag_margins = TkTextTag.new(t, 'lmargin1'=>'12m', 'lmargin2'=>'6m', 'rmargin'=>'10m') style_tag_spacing = TkTextTag.new(t, 'spacing1'=>'10p', 'spacing2'=>'2p', 'lmargin1'=>'12m', 'lmargin2'=>'6m', 'rmargin'=>'10m') # insert('end', 'Text widgets like this one allow you to display information in a variety of styles. Display styles are controlled using a mechanism called ') insert('end', 'tags', style_tag_big) insert('end', '. Tags are just textual names that you can apply to one or more ranges of characters within a text widget. You can configure tags with various display styles. If you do this, then the tagged characters will be displayed with the styles you chose. The available display styles are: ') insert('end', "\n1. Font.", style_tag_big) insert('end', " You can choose any X font, ") insert('end', "large", style_tag_verybig) insert('end', " or ") insert('end', "small", style_tag_small) insert('end', ".\n") insert('end', "\n2. Color.", style_tag_big) insert('end', " You can change either the ") insert('end', "background", style_tag_color1) insert('end', " or ") insert('end', "foreground", style_tag_color2) insert('end', "\ncolor, or ") insert('end', "both", style_tag_color1, style_tag_color2) insert('end', ".\n") insert('end', "\n3. Stippling.", style_tag_big) insert('end', " You can cause either the ") insert('end', "background", style_tag_bgstipple) insert('end', " or ") insert('end', "foreground", style_tag_fgstipple) insert('end', "\ninformation to be drawn with a stipple fill instead of a solid fill.\n") insert('end', "\n4. Underlining.", style_tag_big) insert('end', " You can ") insert('end', "underline", style_tag_underline) insert('end', " ranges of text.\n") insert('end', "\n5. Overstrikes.", style_tag_big) insert('end', " You can ") insert('end', "draw lines through", style_tag_overstrike) insert('end', " ranges of text.\n") insert('end', "\n6. 3-D effects.", style_tag_big) insert('end', " You can arrange for the background to be drawn\nwith a border that makes characters appear either\n") insert('end', "raised", style_tag_raised) insert('end', " or ") insert('end', "sunken", style_tag_sunken) insert('end', ".\n") insert('end', "\n7. Justification.", style_tag_big) insert('end', " You can arrange for lines to be displayed\n") insert('end', "left-justified,\n") insert('end', "right-justified, or\n", style_tag_right) insert('end', "centered.\n", style_tag_center) insert('end', "\n8. Superscripts and subscripts.", style_tag_big) insert('end', " You can control the vertical\n") insert('end', "position of text to generate superscript effects like 10") insert('end', "n", style_tag_super) insert('end', " or\nsubscript effects like X") insert('end', "i", style_tag_sub) insert('end', ".\n") insert('end', "\n9. Margins.", style_tag_big) insert('end', " You can control the amount of extra space left") insert('end', " on\neach side of the text:\n") insert('end', "This paragraph is an example of the use of ", style_tag_margins) insert('end', "margins. It consists of a single line of text ", style_tag_margins) insert('end', "that wraps around on the screen. There are two ", style_tag_margins) insert('end', "separate left margin values, one for the first ", style_tag_margins) insert('end', "display line associated with the text line, ", style_tag_margins) insert('end', "and one for the subsequent display lines, which ", style_tag_margins) insert('end', "occur because of wrapping. There is also a ", style_tag_margins) insert('end', "separate specification for the right margin, ", style_tag_margins) insert('end', "which is used to choose wrap points for lines.\n", style_tag_margins) insert('end', "\n10. Spacing.", style_tag_big) insert('end', " You can control the spacing of lines with three\n") insert('end', "separate parameters. \"Spacing1\" tells how much ") insert('end', "extra space to leave\nabove a line, \"spacing3\" ") insert('end', "tells how much space to leave below a line,\nand ") insert('end', "if a text line wraps, \"spacing2\" tells how much ") insert('end', "space to leave\nbetween the display lines that ") insert('end', "make up the text line.\n") insert('end', "These indented paragraphs illustrate how spacing ", style_tag_spacing) insert('end', "can be used. Each paragraph is actually a ", style_tag_spacing) insert('end', "single line in the text widget, which is ", style_tag_spacing) insert('end', "word-wrapped by the widget.\n", style_tag_spacing) insert('end', "Spacing1 is set to 10 points for this text, ", style_tag_spacing) insert('end', "which results in relatively large gaps between ", style_tag_spacing) insert('end', "the paragraphs. Spacing2 is set to 2 points, ", style_tag_spacing) insert('end', "which results in just a bit of extra space ", style_tag_spacing) insert('end', "within a pararaph. Spacing3 isn't used ", style_tag_spacing) insert('end', "in this example.\n", style_tag_spacing) insert('end', "To see where the space is, select ranges of ", style_tag_spacing) insert('end', "text within these paragraphs. The selection ", style_tag_spacing) insert('end', "highlight will cover the extra space.", style_tag_spacing) } txt.width 70 txt.height 32
arnab0073/idea
.rvm/src/ruby-2.3.0/lib/profiler.rb
# frozen_string_literal: false # Profile provides a way to Profile your Ruby application. # # Profiling your program is a way of determining which methods are called and # how long each method takes to complete. This way you can detect which # methods are possible bottlenecks. # # Profiling your program will slow down your execution time considerably, # so activate it only when you need it. Don't confuse benchmarking with # profiling. # # There are two ways to activate Profiling: # # == Command line # # Run your Ruby script with <code>-rprofile</code>: # # ruby -rprofile example.rb # # If you're profiling an executable in your <code>$PATH</code> you can use # <code>ruby -S</code>: # # ruby -rprofile -S some_executable # # == From code # # Just require 'profile': # # require 'profile' # # def slow_method # 5000.times do # 9999999999999999*999999999 # end # end # # def fast_method # 5000.times do # 9999999999999999+999999999 # end # end # # slow_method # fast_method # # The output in both cases is a report when the execution is over: # # ruby -rprofile example.rb # # % cumulative self self total # time seconds seconds calls ms/call ms/call name # 68.42 0.13 0.13 2 65.00 95.00 Integer#times # 15.79 0.16 0.03 5000 0.01 0.01 Fixnum#* # 15.79 0.19 0.03 5000 0.01 0.01 Fixnum#+ # 0.00 0.19 0.00 2 0.00 0.00 IO#set_encoding # 0.00 0.19 0.00 1 0.00 100.00 Object#slow_method # 0.00 0.19 0.00 2 0.00 0.00 Module#method_added # 0.00 0.19 0.00 1 0.00 90.00 Object#fast_method # 0.00 0.19 0.00 1 0.00 190.00 #toplevel module Profiler__ class Wrapper < Struct.new(:defined_class, :method_id, :hash) # :nodoc: private :defined_class=, :method_id=, :hash= def initialize(klass, mid) super(klass, mid, nil) self.hash = Struct.instance_method(:hash).bind(self).call end def to_s "#{defined_class.inspect}#".sub(/\A\#<Class:(.*)>#\z/, '\1.') << method_id.to_s end alias inspect to_s end # internal values @@start = nil # the start time that profiling began @@stacks = nil # the map of stacks keyed by thread @@maps = nil # the map of call data keyed by thread, class and id. Call data contains the call count, total time, PROFILE_CALL_PROC = TracePoint.new(*%i[call c_call b_call]) {|tp| # :nodoc: now = Process.times[0] stack = (@@stacks[Thread.current] ||= []) stack.push [now, 0.0] } PROFILE_RETURN_PROC = TracePoint.new(*%i[return c_return b_return]) {|tp| # :nodoc: now = Process.times[0] key = Wrapper.new(tp.defined_class, tp.method_id) stack = (@@stacks[Thread.current] ||= []) if tick = stack.pop threadmap = (@@maps[Thread.current] ||= {}) data = (threadmap[key] ||= [0, 0.0, 0.0, key]) data[0] += 1 cost = now - tick[0] data[1] += cost data[2] += cost - tick[1] stack[-1][1] += cost if stack[-1] end } module_function # Starts the profiler. # # See Profiler__ for more information. def start_profile @@start = Process.times[0] @@stacks = {} @@maps = {} PROFILE_CALL_PROC.enable PROFILE_RETURN_PROC.enable end # Stops the profiler. # # See Profiler__ for more information. def stop_profile PROFILE_CALL_PROC.disable PROFILE_RETURN_PROC.disable end # Outputs the results from the profiler. # # See Profiler__ for more information. def print_profile(f) stop_profile total = Process.times[0] - @@start if total == 0 then total = 0.01 end totals = {} @@maps.values.each do |threadmap| threadmap.each do |key, data| total_data = (totals[key] ||= [0, 0.0, 0.0, key]) total_data[0] += data[0] total_data[1] += data[1] total_data[2] += data[2] end end # Maybe we should show a per thread output and a totals view? data = totals.values data = data.sort_by{|x| -x[2]} sum = 0 f.printf " %% cumulative self self total\n" f.printf " time seconds seconds calls ms/call ms/call name\n" for d in data sum += d[2] f.printf "%6.2f %8.2f %8.2f %8d ", d[2]/total*100, sum, d[2], d[0] f.printf "%8.2f %8.2f %s\n", d[2]*1000/d[0], d[1]*1000/d[0], d[3] end f.printf "%6.2f %8.2f %8.2f %8d ", 0.0, total, 0.0, 1 # ??? f.printf "%8.2f %8.2f %s\n", 0.0, total*1000, "#toplevel" # ??? end end
arnab0073/idea
.rvm/src/ruby-2.3.0/nacl/create_nmf.rb
#!/usr/bin/ruby # Copyright:: Copyright 2012 Google Inc. # License:: All Rights Reserved. # Original Author:: <NAME> (mailto:<EMAIL>) # # Wrapper for create_nmf.py / generate_nmf.py require File.join(File.dirname(__FILE__), 'nacl-config') include NaClConfig $verbosity = 0 def usage_and_exit $stderr.puts "Usage: #{$PROGRAM_NAME} [--verbose=N] path/to/input.nexe path/to/output.nmf" exit false end def create_dynamically_linked(nmf, exe) cmd = [ PYTHON, CREATE_NMF, '-o', nmf, '-D', OBJDUMP, '-L', HOST_LIB, exe ] puts cmd.join(' ') if $verbosity > 0 exec(*cmd) end def create_statically_linked(nmf, exe) File.open(nmf, "w") {|f| f.write <<-EOS.gsub(/^ {6}/, '') { "program": { "#{ARCH}": { "url": "#{exe}" } } } EOS } end def main while m = ARGV.first.match(/--([a-z-]+)(?:=(\S+))?/) case m[1] when 'verbose' usage_and_exit unless m[2][/\A[0-9]+\z/] $verbosity = m[2].to_i when 'help' usage_end_exit end ARGV.shift end usage_and_exit if ARGV.size < 2 exe, nmf = ARGV[0], ARGV[1] if newlib? create_statically_linked(nmf, exe) else create_dynamically_linked(nmf, exe) end end if __FILE__ == $0 main() end
arnab0073/idea
.rvm/src/ruby-2.3.0/test/-ext-/symbol/test_inadvertent_creation.rb
<reponame>arnab0073/idea<filename>.rvm/src/ruby-2.3.0/test/-ext-/symbol/test_inadvertent_creation.rb # frozen_string_literal: false require 'test/unit' require "-test-/symbol" module Test_Symbol class TestInadvertent < Test::Unit::TestCase def noninterned_name(prefix = "") prefix += "_#{Thread.current.object_id.to_s(36).tr('-', '_')}" begin name = "#{prefix}_#{rand(0x1000).to_s(16)}_#{Time.now.usec}" end while Bug::Symbol.find(name) name end def setup @obj = Object.new end def assert_not_pinneddown(name, msg = nil) assert_not_send([Bug::Symbol, :pinneddown?, name], msg) end def assert_not_interned(name, msg = nil) assert_not_send([Bug::Symbol, :find, name], msg) end def assert_not_interned_error(obj, meth, name, msg = nil, &block) e = assert_raise(NameError, msg) {obj.__send__(meth, name, &block)} if Symbol === name assert_not_pinneddown(name, msg) else assert_not_interned(name, msg) end e end def assert_not_interned_false(obj, meth, name, msg = nil) assert_not_send([obj, meth, name], msg) if Symbol === name assert_not_pinneddown(name, msg) else assert_not_interned(name, msg) end end Feature5072 = '[ruby-core:38367]' def test_module_const_get cl = Class.new name = noninterned_name("A") assert_not_interned_error(cl, :const_get, name, Feature5072) assert_not_interned_error(cl, :const_get, name.to_sym) end def test_module_const_defined? cl = Class.new name = noninterned_name("A") assert_not_interned_false(cl, :const_defined?, name, Feature5072) name = noninterned_name assert_not_interned_error(cl, :const_defined?, name.to_sym) end def test_module_define_method_type_error cl = Class.new name = noninterned_name assert_raise(TypeError) {cl.class_eval {define_method(name, "")}} assert_not_interned(name) assert_raise(TypeError) {cl.class_eval {define_method(name.to_sym, "")}} assert_not_pinneddown(name) end def test_module_define_method_argument_error cl = Class.new name = noninterned_name assert_raise(ArgumentError) {cl.class_eval {define_method(name)}} assert_not_interned(name) assert_raise(ArgumentError) {cl.class_eval {define_method(name.to_sym)}} assert_not_pinneddown(name) end def test_respond_to_missing feature5072 = Feature5072 c = Class.new do def self.respond_to_missing?(*) super end end s = noninterned_name # assert_not_interned_false(c, :respond_to?, s, feature5072) assert_not_interned_false(c, :method_defined?, s, feature5072) assert_not_interned_false(c, :public_method_defined?, s, feature5072) assert_not_interned_false(c, :private_method_defined?, s, feature5072) assert_not_interned_false(c, :protected_method_defined?, s, feature5072) assert_not_interned_false(c, :const_defined?, noninterned_name("A"), feature5072) assert_not_interned_false(c, :instance_variable_defined?, noninterned_name("@"), feature5072) assert_not_interned_false(c, :class_variable_defined?, noninterned_name("@@"), feature5072) end def test_missing_method bug10985 = '[ruby-core:68564] [Bug #10985]' m = nil c = Class.new do def self.respond_to_missing?(*) true end end s = noninterned_name assert_nothing_raised(NameError, bug10985) {m = c.method(s)} assert_raise_with_message(NoMethodError, /#{s}/) {m.call} s = noninterned_name assert_nothing_raised(NameError, bug10985) {m = c.public_method(s.to_sym)} assert_raise_with_message(NoMethodError, /#{s}/) {m.call} s = noninterned_name assert_nothing_raised(NameError, bug10985) {m = c.singleton_method(s.to_sym)} assert_raise_with_message(NoMethodError, /#{s}/) {m.call} end Feature5079 = '[ruby-core:38404]' def test_undefined_instance_variable feature5079 = Feature5079 c = Class.new iv = noninterned_name("@") assert_not_interned_false(c, :instance_variable_get, iv, feature5079) assert_not_interned_error(c, :remove_instance_variable, iv, feature5079) end def test_undefined_class_variable feature5079 = Feature5079 c = Class.new cv = noninterned_name("@@") assert_not_interned_error(c, :class_variable_get, cv, feature5079) assert_not_interned_error(c, :remove_class_variable, cv, feature5079) end def test_undefined_const feature5079 = Feature5079 c = Class.new s = noninterned_name("A") assert_not_interned_error(c, :remove_const, s, feature5079) end def test_undefined_method feature5079 = Feature5079 c = Class.new s = noninterned_name assert_not_interned_error(c, :method, s, feature5079) assert_not_interned_error(c, :public_method, s, feature5079) assert_not_interned_error(c, :instance_method, s, feature5079) assert_not_interned_error(c, :public_instance_method, s, feature5079) assert_not_interned_error(c, :singleton_method, s, feature5079) end Feature5089 = '[ruby-core:38447]' def test_const_missing feature5089 = Feature5089 c = Class.new do def self.const_missing(const_name) raise NameError, const_name.to_s end end s = noninterned_name("A") assert_not_interned_error(c, :const_get, s.to_sym, feature5089) assert_not_interned_false(c, :autoload?, s.to_sym, feature5089) end def test_aliased_method feature5089 = Feature5089 c = Class.new do def self.alias_method(str) super(:puts, str) end end s = noninterned_name assert_not_interned_error(c, :alias_method, s, feature5089) assert_not_interned_error(c, :private_class_method, s, feature5089) assert_not_interned_error(c, :private_constant, s, feature5089) assert_not_interned_error(c, :private, s, feature5089) assert_not_interned_error(c, :protected, s, feature5089) assert_not_interned_error(c, :public, s, feature5089) assert_not_interned_error(c, :public_class_method, s, feature5089) assert_not_interned_error(c, :public_constant, s, feature5089) assert_not_interned_error(c, :remove_method, s, feature5089) assert_not_interned_error(c, :undef_method, s, feature5089) assert_not_interned_error(c, :untrace_var, s, feature5089) end Feature5112 = '[ruby-core:38576]' def test_public_send name = noninterned_name e = assert_raise(NoMethodError) {@obj.public_send(name, Feature5112)} assert_not_interned(name) assert_equal(name, e.name) assert_equal([Feature5112], e.args) end def test_send name = noninterned_name e = assert_raise(NoMethodError) {@obj.send(name, Feature5112)} assert_not_interned(name) assert_equal(name, e.name) assert_equal([Feature5112], e.args) end def test___send__ name = noninterned_name e = assert_raise(NoMethodError) {@obj.__send__(name, Feature5112)} assert_not_interned(name) assert_equal(name, e.name) assert_equal([Feature5112], e.args) end def test_thread_aref Thread.current[:test] = nil name = noninterned_name assert_nil(Thread.current[name]) assert_not_interned(name) end def test_thread_key? Thread.current[:test] = nil name = noninterned_name assert_not_send([Thread.current, :key?, name]) assert_not_interned(name) end def test_thread_variable_get Thread.current.thread_variable_set(:test, nil) name = noninterned_name assert_nil(Thread.current.thread_variable_get(name)) assert_not_pinneddown(name) end def test_thread_variable_set name = noninterned_name Thread.current.thread_variable_set(name, 42) assert_not_pinneddown(name) end def test_thread_variable? Thread.current.thread_variable_set(:test, nil) name = noninterned_name assert_not_send([Thread.current, :thread_variable?, name]) assert_not_interned(name) end def test_enumerable_inject_op name = noninterned_name assert_raise(NoMethodError) {[1, 2].inject(name)} assert_not_interned(name) end def test_module_const_set name = noninterned_name mod = Module.new assert_raise(NameError) {mod.const_set(name, true)} assert_not_interned(name) assert_raise(NameError) {mod.const_set(name.to_sym, true)} assert_not_pinneddown(name) end def test_module_cvar_set name = noninterned_name mod = Module.new assert_raise(NameError) {mod.class_variable_set(name, true)} assert_not_interned(name) assert_raise(NameError) {mod.class_variable_set(name.to_sym, true)} assert_not_pinneddown(name) end def test_object_ivar_set name = noninterned_name obj = Object.new assert_raise(NameError) {obj.instance_variable_set(name, true)} assert_not_interned(name) assert_raise(NameError) {obj.instance_variable_set(name.to_sym, true)} assert_not_pinneddown(name) end def test_struct_new name = noninterned_name assert_raise(NameError) {Struct.new(name)} assert_not_interned(name) end def test_struct_aref s = Struct.new(:foo).new name = noninterned_name assert_raise(NameError) {s[name]} assert_not_interned(name) end def test_struct_aset s = Struct.new(:foo).new name = noninterned_name assert_raise(NameError) {s[name] = true} assert_not_interned(name) end def test_invalid_attr name = noninterned_name("*") mod = Module.new assert_raise(NameError) {mod.module_eval {attr(name)}} assert_not_interned(name) assert_raise(NameError) {mod.module_eval {attr(name.to_sym)}} assert_not_pinneddown(name) end def test_invalid_attr_reader name = noninterned_name("*") mod = Module.new assert_raise(NameError) {mod.module_eval {attr_reader(name)}} assert_not_interned(name) assert_raise(NameError) {mod.module_eval {attr_reader(name.to_sym)}} assert_not_pinneddown(name) end def test_invalid_attr_writer name = noninterned_name("*") mod = Module.new assert_raise(NameError) {mod.module_eval {attr_writer(name)}} assert_not_interned(name) assert_raise(NameError) {mod.module_eval {attr_writer(name.to_sym)}} assert_not_pinneddown(name) end def test_invalid_attr_accessor name = noninterned_name("*") mod = Module.new assert_raise(NameError) {mod.module_eval {attr_accessor(name)}} assert_not_interned(name) assert_raise(NameError) {mod.module_eval {attr_accessor(name.to_sym)}} assert_not_pinneddown(name) end def test_gc_attrset assert_separately(['-r-test-/symbol', '-', '[ruby-core:62226] [Bug #9787]'], <<-'end;') # begin bug = ARGV.shift def noninterned_name(prefix = "") prefix += "_#{Thread.current.object_id.to_s(36).tr('-', '_')}" begin name = "#{prefix}_#{rand(0x1000).to_s(16)}_#{Time.now.usec}" end while Bug::Symbol.find(name) or Bug::Symbol.find(name + "=") name end names = Array.new(1000) {noninterned_name("gc")} names.each {|n| n.to_sym} GC.start(immediate_sweep: false) names.each do |n| eval(":#{n}=") assert_nothing_raised(TypeError, bug) {eval("proc{self.#{n} = nil}")} end end; end def test_execopt_key name = noninterned_name.intern assert_raise(ArgumentError) { system(".", name => nil) } assert_not_pinneddown(name) end def test_execopt_redirect_value name = noninterned_name.intern assert_raise(ArgumentError) { system(".", [] => name) } assert_not_pinneddown(name) end def test_execopt_redirect_path name = noninterned_name.intern assert_raise(TypeError) { system(".", [] => [name, 0]) } assert_not_pinneddown(name) end def test_execopt_redirect_symbol name = noninterned_name.intern assert_raise(ArgumentError) { system(".", in: name) } assert_not_pinneddown(name) end def assert_no_immortal_symbol_created(name) name = noninterned_name(name) yield(name) assert_not_pinneddown(name) end def assert_no_immortal_symbol_in_method_missing(name) assert_no_immortal_symbol_created("send should not leak - #{name}") do |name| assert_raise(NoMethodError) {yield(name)} end end def test_send_leak_string assert_no_immortal_symbol_in_method_missing("str") do |name| 42.send(name) end end def test_send_leak_symbol assert_no_immortal_symbol_in_method_missing("sym") do |name| 42.send(name.to_sym) end end def test_send_leak_string_custom_method_missing x = Object.new def x.method_missing(*); super; end assert_no_immortal_symbol_in_method_missing("str mm") do |name| x.send(name) end end def test_send_leak_symbol_custom_method_missing x = Object.new def x.method_missing(*); super; end assert_no_immortal_symbol_in_method_missing("sym mm") do |name| x.send(name.to_sym) end end def test_send_leak_string_no_optimization assert_no_immortal_symbol_in_method_missing("str slow") do |name| 42.method(:send).call(name) end end def test_send_leak_symbol_no_optimization assert_no_immortal_symbol_in_method_missing("sym slow") do |name| 42.method(:send).call(name.to_sym) end end def test_send_leak_string_custom_method_missing_no_optimization x = Object.new def x.method_missing(*); super; end assert_no_immortal_symbol_in_method_missing("str mm slow") do |name| x.method(:send).call(name) end end def test_send_leak_symbol_custom_method_missing_no_optimization x = Object.new def x.method_missing(*); super; end assert_no_immortal_symbol_in_method_missing("sym mm slow") do |name| x.method(:send).call(name.to_sym) end end def test_kwarg_symbol_leak_no_rest foo = -> (arg: 42) {} assert_no_immortal_symbol_created("kwarg no rest") do |name| assert_raise(ArgumentError) { foo.call(name.to_sym => 42) } end end def test_kwarg_symbol_leak_with_rest foo = -> (arg: 2, **options) {} assert_no_immortal_symbol_created("kwarg with rest") do |name| foo.call(name.to_sym => 42) end end def test_kwarg_symbol_leak_just_rest foo = -> (**options) {} assert_no_immortal_symbol_created("kwarg just rest") do |name| foo.call(name.to_sym => 42) end end end end
arnab0073/idea
.rvm/src/ruby-2.3.0/ext/-test-/bignum/extconf.rb
<filename>.rvm/src/ruby-2.3.0/ext/-test-/bignum/extconf.rb # frozen_string_literal: false $INCFLAGS << " -I$(topdir) -I$(top_srcdir)" $srcs = Dir[File.join($srcdir, "*.{#{SRC_EXT.join(%q{,})}}")] inits = $srcs.map {|s| File.basename(s, ".*")} inits.delete("init") inits.map! {|s|"X(#{s})"} $defs << "-DTEST_INIT_FUNCS(X)=\"#{inits.join(' ')}\"" create_makefile("-test-/bignum")
arnab0073/idea
.rvm/src/ruby-2.3.0/sample/philos.rb
<gh_stars>10-100 # # The Dining Philosophers - thread example # require "thread" srand #srand N=9 # number of philosophers $forks = [] for i in 0..N-1 $forks[i] = Mutex.new end $state = "-o"*N def wait sleep rand(20)/10.0 end def think(n) wait end def eat(n) wait end def philosopher(n) while true think n $forks[n].lock if not $forks[(n+1)%N].try_lock $forks[n].unlock # avoid deadlock next end $state[n*2] = ?|; $state[(n+1)%N*2] = ?|; $state[n*2+1] = ?*; print $state, "\n" eat(n) $state[n*2] = ?-; $state[(n+1)%N*2] = ?-; $state[n*2+1] = ?o; print $state, "\n" $forks[n].unlock $forks[(n+1)%N].unlock end end for n in 0..N-1 Thread.start(n){|i| philosopher(i)} sleep 0.1 end sleep
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/winrm-1.8.1/spec/transport_spec.rb
<gh_stars>0 # encoding: UTF-8 require 'rubyntlm' require 'winrm/http/transport' describe WinRM::HTTP::HttpNegotiate, unit: true do describe '#init' do let(:endpoint) { 'some_endpoint' } let(:domain) { 'some_domain' } let(:user) { 'some_user' } let(:password) { '<PASSWORD>' } let(:options) { {} } context 'user is not domain prefixed' do it 'does not pass a domain to the NTLM client' do expect(Net::NTLM::Client).to receive(:new).with(user, password, options) WinRM::HTTP::HttpNegotiate.new(endpoint, user, password, options) end end context 'user is domain prefixed' do it 'passes prefixed domain to the NTLM client' do expect(Net::NTLM::Client).to receive(:new) do |passed_user, passed_password, passed_options| expect(passed_user).to eq user expect(passed_password).to eq password expect(passed_options[:domain]).to eq domain end WinRM::HTTP::HttpNegotiate.new(endpoint, "#{domain}\\#{user}", password, options) end end context 'option is passed with a domain' do let(:options) { { domain: domain } } it 'passes domain option to the NTLM client' do expect(Net::NTLM::Client).to receive(:new) do |passed_user, passed_password, passed_options| expect(passed_user).to eq user expect(passed_password).to eq password expect(passed_options[:domain]).to eq domain end WinRM::HTTP::HttpNegotiate.new(endpoint, user, password, options) end end end end describe 'WinRM connection', integration: true do let(:winrm_connection) do endpoint = config[:endpoint].dup if auth_type == :ssl endpoint.sub!('5985', '5986') endpoint.sub!('http', 'https') end winrm = WinRM::WinRMWebService.new( endpoint, auth_type, options) winrm.logger.level = :error winrm end let(:options) do opts = {} opts[:user] = config[:options][:user] opts[:pass] = config[:options][:pass] opts[:basic_auth_only] = basic_auth_only opts[:no_ssl_peer_verification] = no_ssl_peer_verification opts[:ssl_peer_fingerprint] = ssl_peer_fingerprint opts[:client_cert] = user_cert opts[:client_key] = user_key opts end let(:basic_auth_only) { false } let(:no_ssl_peer_verification) { false } let(:ssl_peer_fingerprint) { nil } let(:user_cert) { nil } let(:user_key) { nil } subject(:output) do executor = winrm_connection.create_executor executor.run_cmd('ipconfig') end shared_examples 'a valid_connection' do it 'has a 0 exit code' do expect(subject).to have_exit_code 0 end it 'includes command output' do expect(subject).to have_stdout_match(/Windows IP Configuration/) end it 'has no errors' do expect(subject).to have_no_stderr end end context 'HttpPlaintext' do let(:basic_auth_only) { true } let(:auth_type) { :plaintext } it_behaves_like 'a valid_connection' end context 'HttpNegotiate' do let(:auth_type) { :negotiate } it_behaves_like 'a valid_connection' end context 'BasicAuthSSL', skip: ENV['winrm_cert'].nil? do let(:basic_auth_only) { true } let(:auth_type) { :ssl } let(:no_ssl_peer_verification) { true } it_behaves_like 'a valid_connection' end context 'ClientCertAuthSSL', skip: ENV['user_cert'].nil? do let(:auth_type) { :ssl } let(:no_ssl_peer_verification) { true } let(:user_cert) { ENV['user_cert'] } let(:user_key) { ENV['user_key'] } before { options[:pass] = nil } it_behaves_like 'a valid_connection' end context 'Negotiate over SSL', skip: ENV['winrm_cert'].nil? do let(:auth_type) { :ssl } let(:no_ssl_peer_verification) { true } it_behaves_like 'a valid_connection' end context 'SSL fingerprint', skip: ENV['winrm_cert'].nil? do let(:auth_type) { :ssl } let(:ssl_peer_fingerprint) { ENV['winrm_cert'] } it_behaves_like 'a valid_connection' end end
arnab0073/idea
.rvm/src/ruby-2.3.0/ext/psych/lib/psych/nodes/alias.rb
<gh_stars>10-100 # frozen_string_literal: false module Psych module Nodes ### # This class represents a {YAML Alias}[http://yaml.org/spec/1.1/#alias]. # It points to an +anchor+. # # A Psych::Nodes::Alias is a terminal node and may have no children. class Alias < Psych::Nodes::Node # The anchor this alias links to attr_accessor :anchor # Create a new Alias that points to an +anchor+ def initialize anchor @anchor = anchor end end end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tk/frame.rb
<reponame>arnab0073/idea # # tk/frame.rb : treat frame widget # require 'tk' class Tk::Frame<TkWindow TkCommandNames = ['frame'.freeze].freeze WidgetClassName = 'Frame'.freeze WidgetClassNames[WidgetClassName] ||= self ################# old version # def initialize(parent=nil, keys=nil) # if keys.kind_of? Hash # keys = keys.dup # @classname = keys.delete('classname') if keys.key?('classname') # @colormap = keys.delete('colormap') if keys.key?('colormap') # @container = keys.delete('container') if keys.key?('container') # @visual = keys.delete('visual') if keys.key?('visual') # end # super(parent, keys) # end # # def create_self # s = [] # s << "-class" << @classname if @classname # s << "-colormap" << @colormap if @colormap # s << "-container" << @container if @container # s << "-visual" << @visual if @visual # tk_call 'frame', @path, *s # end ################# def __boolval_optkeys super() << 'container' end private :__boolval_optkeys def initialize(parent=nil, keys=nil) my_class_name = nil if self.class < WidgetClassNames[self.class::WidgetClassName] my_class_name = self.class.name my_class_name = nil if my_class_name == '' end if parent.kind_of? Hash keys = _symbolkey2str(parent) else if keys keys = _symbolkey2str(keys) keys['parent'] = parent else keys = {'parent'=>parent} end end if keys.key?('classname') keys['class'] = keys.delete('classname') end @classname = keys['class'] @colormap = keys['colormap'] @container = keys['container'] @visual = keys['visual'] if !@classname && my_class_name keys['class'] = @classname = my_class_name end if @classname.kind_of? TkBindTag @db_class = @classname @classname = @classname.id elsif @classname @db_class = TkDatabaseClass.new(@classname) else @db_class = self.class @classname = @db_class::WidgetClassName end super(keys) end #def create_self(keys) # if keys and keys != None # tk_call_without_enc('frame', @path, *hash_kv(keys)) # else # tk_call_without_enc( 'frame', @path) # end #end #private :create_self def database_classname @classname end def self.database_class if self == WidgetClassNames[WidgetClassName] || self.name == '' self else TkDatabaseClass.new(self.name) end end def self.database_classname self.database_class.name end def self.bind(*args, &b) if self == WidgetClassNames[WidgetClassName] || self.name == '' super(*args, &b) else TkDatabaseClass.new(self.name).bind(*args, &b) end end def self.bind_append(*args, &b) if self == WidgetClassNames[WidgetClassName] || self.name == '' super(*args, &b) else TkDatabaseClass.new(self.name).bind_append(*args, &b) end end def self.bind_remove(*args) if self == WidgetClassNames[WidgetClassName] || self.name == '' super(*args) else TkDatabaseClass.new(self.name).bind_remove(*args) end end def self.bindinfo(*args) if self == WidgetClassNames[WidgetClassName] || self.name == '' super(*args) else TkDatabaseClass.new(self.name).bindinfo(*args) end end end #TkFrame = Tk::Frame unless Object.const_defined? :TkFrame #Tk.__set_toplevel_aliases__(:Tk, Tk::Frame, :TkFrame) Tk.__set_loaded_toplevel_aliases__('tk/frame.rb', :Tk, Tk::Frame, :TkFrame)
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/net-ssh-2.2.2/lib/net/ssh/errors.rb
<reponame>arnab0073/idea module Net; module SSH # A general exception class, to act as the ancestor of all other Net::SSH # exception classes. class Exception < ::RuntimeError; end # This exception is raised when authentication fails (whether it be # public key authentication, password authentication, or whatever). class AuthenticationFailed < Exception; end # This exception is raised when a connection attempt times out. class ConnectionTimeout < Exception; end # This exception is raised when the remote host has disconnected # unexpectedly. class Disconnect < Exception; end # This exception is primarily used internally, but if you have a channel # request handler (see Net::SSH::Connection::Channel#on_request) that you # want to fail in such a way that the server knows it failed, you can # raise this exception in the handler and Net::SSH will translate that into # a "channel failure" message. class ChannelRequestFailed < Exception; end # This is exception is primarily used internally, but if you have a channel # open handler (see Net::SSH::Connection::Session#on_open_channel) and you # want to fail in such a way that the server knows it failed, you can # raise this exception in the handler and Net::SSH will translate that into # a "channel open failed" message. class ChannelOpenFailed < Exception attr_reader :code, :reason def initialize(code, reason) @code, @reason = code, reason super "#{reason} (#{code})" end end # Raised when the cached key for a particular host does not match the # key given by the host, which can be indicative of a man-in-the-middle # attack. When rescuing this exception, you can inspect the key fingerprint # and, if you want to proceed anyway, simply call the remember_host! # method on the exception, and then retry. class HostKeyMismatch < Exception # the callback to use when #remember_host! is called attr_writer :callback #:nodoc: # situation-specific data describing the host (see #host, #port, etc.) attr_writer :data #:nodoc: # An accessor for getting at the data that was used to look up the host # (see also #fingerprint, #host, #port, #ip, and #key). def [](key) @data && @data[key] end # Returns the fingerprint of the key for the host, which either was not # found or did not match. def fingerprint @data && @data[:fingerprint] end # Returns the host name for the remote host, as reported by the socket. def host @data && @data[:peer] && @data[:peer][:host] end # Returns the port number for the remote host, as reported by the socket. def port @data && @data[:peer] && @data[:peer][:port] end # Returns the IP address of the remote host, as reported by the socket. def ip @data && @data[:peer] && @data[:peer][:ip] end # Returns the key itself, as reported by the remote host. def key @data && @data[:key] end # Tell Net::SSH to record this host and key in the known hosts file, so # that subsequent connections will remember them. def remember_host! @callback.call end end end; end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/benchmark/bm_vm1_ivar_set.rb
<filename>.rvm/src/ruby-1.9.3-p551/benchmark/bm_vm1_ivar_set.rb<gh_stars>10-100 i = 0 while i<30_000_000 # while loop 1 i+= 1 @a = 1 @b = 2 end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/knife-windows-1.4.1/lib/chef/knife/windows_listener_create.rb
# Author:: <NAME> (<<EMAIL>>) # Copyright:: Copyright (c) 2014-2016 Chef Software, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'chef/knife' require 'chef/knife/winrm_base' require 'openssl' class Chef class Knife class WindowsListenerCreate < Knife banner "knife windows listener create (options)" option :cert_install, :short => "-c CERT_PATH", :long => "--cert-install CERT_PATH", :description => "Adds specified certificate to the Windows Certificate Store's Local Machine personal store before creating listener." option :port, :short => "-p PORT", :long => "--port PORT", :description => "Specify port. Default is 5986", :default => "5986" option :hostname, :short => "-h HOSTNAME", :long => "--hostname HOSTNAME", :description => "Hostname on the listener. Default is blank", :default => "" option :cert_thumbprint, :short => "-t THUMBPRINT", :long => "--cert-thumbprint THUMBPRINT", :description => "Thumbprint of the certificate. Required only if --cert-install option is not used." option :cert_passphrase, :short => "-cp PASSWORD", :long => "--cert-passphrase PASSWORD", :description => "Password for certificate." def get_cert_passphrase print "Enter given certificate's passphrase (empty for no passphrase):" passphrase = STDIN.gets passphrase.strip end def run STDOUT.sync = STDERR.sync = true if Chef::Platform.windows? begin if config[:cert_install] config[:cert_passphrase] = get_cert_passphrase unless config[:cert_passphrase] result = %x{powershell.exe -Command " '#{config[:cert_passphrase]}' | certutil -importPFX '#{config[:cert_install]}' AT_KEYEXCHANGE"} if $?.exitstatus ui.info "Certificate installed to Certificate Store" result = %x{powershell.exe -Command " echo (Get-PfxCertificate #{config[:cert_install]}).thumbprint "} ui.info "Certificate Thumbprint: #{result}" config[:cert_thumbprint] = result.strip else ui.error "Error installing certificate to Certificate Store" ui.error result exit 1 end end unless config[:cert_thumbprint] ui.error "Please specify the --cert-thumbprint" exit 1 end result = %x{winrm create winrm/config/Listener?Address=*+Transport=HTTPS @{Hostname="#{config[:hostname]}";CertificateThumbprint="#{config[:cert_thumbprint]}";Port="#{config[:port]}"}} Chef::Log.debug result if ($?.exitstatus == 0) ui.info "WinRM listener created with Port: #{config[:port]} and CertificateThumbprint: #{config[:cert_thumbprint]}" else ui.error "Error creating WinRM listener. use -VV for more details." exit 1 end rescue => e puts "ERROR: + #{e}" end else ui.error "WinRM listener can be created on Windows system only" exit 1 end end end end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/rubyntlm-0.6.0/spec/lib/net/ntlm/int32_le_spec.rb
<gh_stars>0 require 'spec_helper' describe Net::NTLM::Int32LE do int_values = { :default => 252716124, :default_hex => "\x5C\x24\x10\x0f", :alt => 235938908, :alt_hex => "\x5C\x24\x10\x0e", :small => "\x0F\x00", :size => 4, :bits => 32 } it_behaves_like 'a field', 252716124, false it_behaves_like 'an integer field', int_values end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/mixlib-shellout-1.6.1/lib/mixlib/shellout/exceptions.rb
module Mixlib class ShellOut class ShellCommandFailed < RuntimeError; end class CommandTimeout < RuntimeError; end class InvalidCommandOption < RuntimeError; end end end
arnab0073/idea
.rvm/src/ruby-2.3.0/test/gdbm/test_gdbm.rb
# frozen_string_literal: false begin require 'gdbm' rescue LoadError end if defined? GDBM require 'test/unit' require 'tmpdir' require 'fileutils' class TestGDBM_RDONLY < Test::Unit::TestCase def TestGDBM_RDONLY.uname_s require 'rbconfig' case RbConfig::CONFIG['target_os'] when 'cygwin' require 'etc' Etc.uname[:sysname] else RbConfig::CONFIG['target_os'] end end SYSTEM = uname_s def setup @tmpdir = Dir.mktmpdir("tmptest_gdbm") @prefix = "tmptest_gdbm_#{$$}" @path = "#{@tmpdir}/#{@prefix}_" # prepare to make readonly GDBM file GDBM.open("#{@tmpdir}/#{@prefix}_rdonly", 0400) {|gdbm| gdbm['foo'] = 'FOO' } assert_instance_of(GDBM, @gdbm_rdonly = GDBM.new("#{@tmpdir}/#{@prefix}_rdonly", nil)) end def teardown assert_nil(@gdbm_rdonly.close) ObjectSpace.each_object(GDBM) do |obj| obj.close unless obj.closed? end FileUtils.remove_entry_secure @tmpdir end def test_delete_rdonly if /^CYGWIN_9/ !~ SYSTEM assert_raise(GDBMError) { @gdbm_rdonly.delete("foo") } assert_nil(@gdbm_rdonly.delete("bar")) end end end class TestGDBM < Test::Unit::TestCase SYSTEM = TestGDBM_RDONLY::SYSTEM def setup @tmpdir = Dir.mktmpdir("tmptest_gdbm") @prefix = "tmptest_gdbm_#{$$}" @path = "#{@tmpdir}/#{@prefix}_" assert_instance_of(GDBM, @gdbm = GDBM.new(@path)) end def teardown assert_nil(@gdbm.close) ObjectSpace.each_object(GDBM) do |obj| obj.close unless obj.closed? end begin FileUtils.remove_entry_secure @tmpdir rescue system("fuser", *Dir.entries(@tmpdir).grep(/\A(?!\.\.?\z)/), chdir: @tmpdir) else return end FileUtils.remove_entry_secure @tmpdir end def check_size(expect, gdbm=@gdbm) assert_equal(expect, gdbm.size) n = 0 gdbm.each { n+=1 } assert_equal(expect, n) if expect == 0 assert_equal(true, gdbm.empty?) else assert_equal(false, gdbm.empty?) end end def test_s_new_has_no_block # GDBM.new ignore the block foo = true assert_instance_of(GDBM, gdbm = GDBM.new("#{@tmpdir}/#{@prefix}") { foo = false }) assert_equal(foo, true) assert_nil(gdbm.close) end def test_s_open_create_new return if /^CYGWIN_9/ =~ SYSTEM save_mask = File.umask(0) begin assert_instance_of(GDBM, gdbm = GDBM.open("#{@tmpdir}/#{@prefix}")) gdbm.close assert_equal(File.stat("#{@tmpdir}/#{@prefix}").mode & 0777, 0666) unless /mswin|mingw/ =~ RUBY_PLATFORM assert_instance_of(GDBM, gdbm = GDBM.open("#{@tmpdir}/#{@prefix}2", 0644)) gdbm.close assert_equal(File.stat("#{@tmpdir}/#{@prefix}2").mode & 0777, 0644) ensure File.umask save_mask end end def test_s_open_no_create skip "gdbm_open(GDBM_WRITER) is broken on libgdbm 1.8.0" if /1\.8\.0/ =~ GDBM::VERSION assert_nil(gdbm = GDBM.open("#{@tmpdir}/#{@prefix}", nil)) ensure gdbm.close if gdbm end def test_s_open_3rd_arg assert_instance_of(GDBM, gdbm = GDBM.open("#{@tmpdir}/#{@prefix}", 0644, GDBM::FAST)) gdbm.close # gdbm 1.8.0 specific if defined? GDBM::SYNC assert_instance_of(GDBM, gdbm = GDBM.open("#{@tmpdir}/#{@prefix}", 0644, GDBM::SYNC)) gdbm.close end # gdbm 1.8.0 specific if defined? GDBM::NOLOCK assert_instance_of(GDBM, gdbm = GDBM.open("#{@tmpdir}/#{@prefix}", 0644, GDBM::NOLOCK)) gdbm.close end end def test_s_open_with_block assert_equal(GDBM.open("#{@tmpdir}/#{@prefix}") { :foo }, :foo) end def open_db_child(dbname, *opts) opts = [0644, *opts].map(&:inspect).join(', ') args = [EnvUtil.rubybin, "-rgdbm", "-e", <<-SRC, dbname] STDOUT.sync = true gdbm = GDBM.open(ARGV.shift, #{opts}) puts gdbm.class gets SRC IO.popen(args, "r+") do |f| dbclass = f.gets assert_equal("GDBM", dbclass.chomp) yield end end def test_s_open_lock skip "GDBM.open would block when opening already locked gdbm file on platforms without flock and with lockf" if /solaris|aix/ =~ RUBY_PLATFORM dbname = "#{@tmpdir}/#{@prefix}" open_db_child(dbname) do assert_raise(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) { GDBM.open(dbname, 0644) {|gdbm| assert_instance_of(GDBM, gdbm) } } end end =begin # Is it guaranteed on many OS? def test_s_open_lock_one_process # locking on one process assert_instance_of(GDBM, gdbm = GDBM.open("#{@tmpdir}/#{@prefix}", 0644)) assert_raise(Errno::EWOULDBLOCK) { begin GDBM.open("#{@tmpdir}/#{@prefix}", 0644) rescue Errno::EAGAIN raise Errno::EWOULDBLOCK end } end =end def test_s_open_nolock dbname = "#{@tmpdir}/#{@prefix}" open_db_child(dbname, GDBM::NOLOCK) do assert_nothing_raised(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) { GDBM.open(dbname, 0644) {|gdbm2| assert_instance_of(GDBM, gdbm2) } } end STDERR.puts Dir.glob("#{dbname}*") if $DEBUG # The following test fails on Windows because flock() implementation # is different from Unix. return if /mswin|mingw/ =~ RUBY_PLATFORM open_db_child(dbname) do assert_nothing_raised(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) { # this test is failed on Cygwin98 (???) GDBM.open(dbname, 0644, GDBM::NOLOCK) {|gdbm2| assert_instance_of(GDBM, gdbm2) } } end end if defined? GDBM::NOLOCK # gdbm 1.8.0 specific def test_s_open_error assert_instance_of(GDBM, gdbm = GDBM.open("#{@tmpdir}/#{@prefix}", 0)) assert_raise(Errno::EACCES, Errno::EWOULDBLOCK) { GDBM.open("#{@tmpdir}/#{@prefix}", 0) } gdbm.close end def test_close assert_instance_of(GDBM, gdbm = GDBM.open("#{@tmpdir}/#{@prefix}")) assert_nil(gdbm.close) # closed GDBM file assert_raise(RuntimeError) { gdbm.close } end def test_aref assert_equal('bar', @gdbm['foo'] = 'bar') assert_equal('bar', @gdbm['foo']) assert_nil(@gdbm['bar']) end def test_fetch assert_equal('bar', @gdbm['foo']='bar') assert_equal('bar', @gdbm.fetch('foo')) # key not found assert_raise(IndexError) { @gdbm.fetch('bar') } # test for `ifnone' arg assert_equal('baz', @gdbm.fetch('bar', 'baz')) # test for `ifnone' block assert_equal('foobar', @gdbm.fetch('bar') {|key| 'foo' + key }) end def test_aset num = 0 2.times {|i| assert_equal('foo', @gdbm['foo'] = 'foo') assert_equal('foo', @gdbm['foo']) assert_equal('bar', @gdbm['foo'] = 'bar') assert_equal('bar', @gdbm['foo']) num += 1 if i == 0 assert_equal(num, @gdbm.size) # assign nil assert_equal('', @gdbm['bar'] = '') assert_equal('', @gdbm['bar']) num += 1 if i == 0 assert_equal(num, @gdbm.size) # empty string assert_equal('', @gdbm[''] = '') assert_equal('', @gdbm['']) num += 1 if i == 0 assert_equal(num, @gdbm.size) # Fixnum assert_equal('200', @gdbm['100'] = '200') assert_equal('200', @gdbm['100']) num += 1 if i == 0 assert_equal(num, @gdbm.size) # Big key and value assert_equal('y' * 100, @gdbm['x' * 100] = 'y' * 100) assert_equal('y' * 100, @gdbm['x' * 100]) num += 1 if i == 0 assert_equal(num, @gdbm.size) } end def test_key assert_equal('bar', @gdbm['foo'] = 'bar') assert_equal('foo', @gdbm.key('bar')) assert_nil(@gdbm['bar']) end def test_values_at keys = %w(foo bar baz) values = %w(FOO BAR BAZ) @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values assert_equal(values.reverse, @gdbm.values_at(*keys.reverse)) end def test_select_with_block keys = %w(foo bar baz) values = %w(FOO BAR BAZ) @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values ret = @gdbm.select {|k,v| assert_equal(k.upcase, v) k != "bar" } assert_equal([['baz', 'BAZ'], ['foo', 'FOO']], ret.sort) end def test_length num = 10 assert_equal(0, @gdbm.size) num.times {|i| i = i.to_s @gdbm[i] = i } assert_equal(num, @gdbm.size) @gdbm.shift assert_equal(num - 1, @gdbm.size) end def test_empty? assert_equal(true, @gdbm.empty?) @gdbm['foo'] = 'FOO' assert_equal(false, @gdbm.empty?) end def test_each_pair n = 0 @gdbm.each_pair { n += 1 } assert_equal(0, n) keys = %w(foo bar baz) values = %w(FOO BAR BAZ) @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values n = 0 ret = @gdbm.each_pair {|key, val| assert_not_nil(i = keys.index(key)) assert_equal(val, values[i]) n += 1 } assert_equal(keys.size, n) assert_equal(@gdbm, ret) end def test_each_value n = 0 @gdbm.each_value { n += 1 } assert_equal(0, n) keys = %w(foo bar baz) values = %w(FOO BAR BAZ) @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values n = 0 ret = @gdbm.each_value {|val| assert_not_nil(key = @gdbm.key(val)) assert_not_nil(i = keys.index(key)) assert_equal(val, values[i]) n += 1 } assert_equal(keys.size, n) assert_equal(@gdbm, ret) end def test_each_key n = 0 @gdbm.each_key { n += 1 } assert_equal(0, n) keys = %w(foo bar baz) values = %w(FOO BAR BAZ) @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values n = 0 ret = @gdbm.each_key {|key| assert_not_nil(i = keys.index(key)) assert_equal(@gdbm[key], values[i]) n += 1 } assert_equal(keys.size, n) assert_equal(@gdbm, ret) end def test_each_key_without_block assert_kind_of Enumerator, @gdbm.each_key end def test_keys assert_equal([], @gdbm.keys) keys = %w(foo bar baz) values = %w(FOO BAR BAZ) @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values assert_equal(keys.sort, @gdbm.keys.sort) assert_equal(values.sort, @gdbm.values.sort) end def test_values test_keys end def test_shift assert_nil(@gdbm.shift) assert_equal(0, @gdbm.size) keys = %w(foo bar baz) values = %w(FOO BAR BAZ) @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values ret_keys = [] ret_values = [] while ret = @gdbm.shift ret_keys.push ret[0] ret_values.push ret[1] assert_equal(keys.size - ret_keys.size, @gdbm.size) end assert_equal(keys.sort, ret_keys.sort) assert_equal(values.sort, ret_values.sort) end def test_delete keys = %w(foo bar baz) values = %w(FOO BAR BAZ) key = keys[1] assert_nil(@gdbm.delete(key)) assert_equal(0, @gdbm.size) @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values assert_equal('BAR', @gdbm.delete(key)) assert_nil(@gdbm[key]) assert_equal(2, @gdbm.size) assert_nil(@gdbm.delete(key)) end def test_delete_with_block key = 'no called block' @gdbm[key] = 'foo' assert_equal('foo', @gdbm.delete(key) {|k| k.replace 'called block'}) assert_equal('no called block', key) assert_equal(0, @gdbm.size) key = 'no called block' assert_equal(:blockval, @gdbm.delete(key) {|k| k.replace 'called block'; :blockval}) assert_equal('called block', key) assert_equal(0, @gdbm.size) end def test_delete_if v = "0" 100.times {@gdbm[v] = v; v = v.next} ret = @gdbm.delete_if {|key, val| key.to_i < 50} assert_equal(@gdbm, ret) check_size(50, @gdbm) ret = @gdbm.delete_if {|key, val| key.to_i >= 50} assert_equal(@gdbm, ret) check_size(0, @gdbm) # break v = "0" 100.times {@gdbm[v] = v; v = v.next} check_size(100, @gdbm) n = 0; @gdbm.delete_if {|key, val| break if n > 50 n+=1 true } assert_equal(51, n) check_size(49, @gdbm) @gdbm.clear # raise v = "0" 100.times {@gdbm[v] = v; v = v.next} check_size(100, @gdbm) n = 0; begin @gdbm.delete_if {|key, val| raise "runtime error" if n > 50 n+=1 true } rescue RuntimeError end assert_equal(51, n) check_size(49, @gdbm) end def test_reject v = "0" 100.times {@gdbm[v] = v; v = v.next} hash = @gdbm.reject {|key, val| key.to_i < 50} assert_instance_of(Hash, hash) assert_equal(100, @gdbm.size) assert_equal(50, hash.size) hash.each_pair {|key,val| assert_equal(false, key.to_i < 50) assert_equal(key, val) } hash = @gdbm.reject {|key, val| key.to_i < 100} assert_instance_of(Hash, hash) assert_equal(true, hash.empty?) end def test_clear v = "1" 100.times {v = v.next; @gdbm[v] = v} assert_equal(@gdbm, @gdbm.clear) # validate GDBM#size i = 0 @gdbm.each { i += 1 } assert_equal(@gdbm.size, i) assert_equal(0, i) end def test_invert v = "0" 100.times {@gdbm[v] = v; v = v.next} hash = @gdbm.invert assert_instance_of(Hash, hash) assert_equal(100, hash.size) hash.each_pair {|key, val| assert_equal(key.to_i, val.to_i) } end def test_update hash = {} v = "0" 100.times {v = v.next; hash[v] = v} @gdbm["101"] = "101" @gdbm.update hash assert_equal(101, @gdbm.size) @gdbm.each_pair {|key, val| assert_equal(key.to_i, val.to_i) } end def test_replace hash = {} v = "0" 100.times {v = v.next; hash[v] = v} @gdbm["101"] = "101" @gdbm.replace hash assert_equal(100, @gdbm.size) @gdbm.each_pair {|key, val| assert_equal(key.to_i, val.to_i) } end def test_reorganize size1 = File.size(@path) i = "1" 1000.times {i = i.next; @gdbm[i] = i} @gdbm.clear @gdbm.sync size2 = File.size(@path) @gdbm.reorganize @gdbm.sync size3 = File.size(@path) # p [size1, size2, size3] assert_equal(true, size1 < size2) # this test is failed on Cygwin98. `GDBM version 1.8.0, as of May 19, 1999' assert_equal(true, size3 < size2) assert_equal(size1, size3) end def test_sync assert_instance_of(GDBM, gdbm = GDBM.open("#{@tmpdir}/#{@prefix}", 0666, GDBM::FAST)) assert_equal(gdbm.sync, gdbm) gdbm.close assert_instance_of(GDBM, gdbm = GDBM.open("#{@tmpdir}/#{@prefix}", 0666)) assert_equal(gdbm.sync, gdbm) gdbm.close end def test_cachesize= assert_equal(@gdbm.cachesize = 1024, 1024) end def test_fastmode= assert_equal(@gdbm.fastmode = true, true) end def test_syncmode= assert_equal(@gdbm.syncmode = true, true) end def test_haskey? assert_equal('bar', @gdbm['foo']='bar') assert_equal(true, @gdbm.has_key?('foo')) assert_equal(false, @gdbm.has_key?('bar')) end def test_has_value? assert_equal('bar', @gdbm['foo']='bar') assert_equal(true, @gdbm.has_value?('bar')) assert_equal(false, @gdbm.has_value?('foo')) end def test_to_a v = "0" 100.times {v = v.next; @gdbm[v] = v} ary = @gdbm.to_a assert_instance_of(Array, ary) assert_equal(100, ary.size) ary.each {|key,val| assert_equal(key.to_i, val.to_i) } end def test_to_hash v = "0" 100.times {v = v.next; @gdbm[v] = v} hash = @gdbm.to_hash assert_instance_of(Hash, hash) assert_equal(100, hash.size) hash.each {|key,val| assert_equal(key.to_i, val.to_i) } end end class TestGDBM2 < Test::Unit::TestCase def setup @tmproot = Dir.mktmpdir('ruby-gdbm') end def teardown FileUtils.remove_entry_secure @tmproot if File.directory?(@tmproot) end def test_reader_open_notexist assert_raise(Errno::ENOENT) { GDBM.open("#{@tmproot}/a", 0666, GDBM::READER) } end def test_writer_open_notexist skip "gdbm_open(GDBM_WRITER) is broken on libgdbm 1.8.0" if /1\.8\.0/ =~ GDBM::VERSION assert_raise(Errno::ENOENT) { GDBM.open("#{@tmproot}/a", 0666, GDBM::WRITER) } end def test_wrcreat_open_notexist v = GDBM.open("#{@tmproot}/a", 0666, GDBM::WRCREAT) assert_instance_of(GDBM, v) v.close end def test_newdb_open_notexist v = GDBM.open("#{@tmproot}/a", 0666, GDBM::NEWDB) assert_instance_of(GDBM, v) v.close end def test_reader_open GDBM.open("#{@tmproot}/a.dbm") {} # create a db. v = GDBM.open("#{@tmproot}/a.dbm", nil, GDBM::READER) {|d| assert_raise(GDBMError) { d["k"] = "v" } true } assert(v) end def test_newdb_open GDBM.open("#{@tmproot}/a.dbm") {|dbm| dbm["k"] = "v" } v = GDBM.open("#{@tmproot}/a.dbm", nil, GDBM::NEWDB) {|d| assert_equal(0, d.length) assert_nil(d["k"]) true } assert(v) end def test_freeze GDBM.open("#{@tmproot}/a.dbm") {|d| d.freeze assert_raise(RuntimeError) { d["k"] = "v" } } end end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/glesys/models/compute/server.rb
require 'fog/compute/models/server' module Fog module Compute class Glesys class Server < Fog::Compute::Server extend Fog::Deprecation identity :serverid attribute :hostname attribute :datacenter attribute :cpucores attribute :memorysize attribute :disksize attribute :transfer attribute :bandwidth attribute :uptime attribute :templatename attribute :managedhosting attribute :platform attribute :cost attribute :rootpassword attribute :state attribute :iplist attribute :description attribute :usage attribute :glera_enabled, :aliases => "gleraenabled" attribute :supported_features, :aliases => "supportedfeatures" def ready? state == 'running' end def start requires :identity service.start(:serverid => identity) end def stop requires :identity service.stop(:serverid => identity) end def reboot requires :identity service.reboot(:serverid => identity) end def destroy(options = {}) requires :identity service.destroy(options.merge!({:serverid => identity})) end def save if self.identity options = { :serverid => self.identity, :disksize => disksize, :memorysize => memorysize, :cpucores => cpucores, :hostname => hostname, :bandwidth => bandwidth } data = service.edit(options) else requires :hostname, :rootpassword options = { :datacenter => datacenter || "Falkenberg", :platform => platform || "OpenVz", :hostname => hostname, :templatename => templatename || "Debian 7.0 64-bit", :disksize => disksize || "10", :memorysize => memorysize || "512", :cpucores => cpucores || "1", :rootpassword => <PASSWORD>, :transfer => transfer || "500", :bandwidth => bandwidth || "10", } # optional options when creating a server: [:ip, :ipv6, :description].each do |k| options[k] = attributes[k] if attributes[k] end data = service.create(options) end merge_attributes(data.body['response']['server']) data.status == 200 ? true : false end def setup(credentials = {}) requires :ssh_ip_address, :username require 'net/ssh' attrs = attributes.dup attrs.delete(:rootpassword) commands = [ %{mkdir -p .ssh}, %{echo "#{Fog::JSON.encode(Fog::JSON.sanitize(attrs))}" >> ~/attributes.json} ] if public_key commands << %{echo "#{public_key}" >> ~/.ssh/authorized_keys} end if credentials[:password].nil? && !rootpassword.nil? credentials[:password] = <PASSWORD> end # wait for glesys to be ready wait_for { sshable?(credentials) } Fog::SSH.new(ssh_ip_address, username, credentials).run(commands) end def ssh(command, options={}, &block) if options[:password].nil? && !rootpassword.nil? options[:password] = <PASSWORD> end super(command, options, &block) end def ips Fog::Compute::Glesys::Ips.new(:serverid => identity, :server => self, :service => service).all end def ip(ip) Fog::Compute::Glesys::Ips.new(:serverid => identity, :server => self, :service => service).get(ip) end def public_ip_address(options = {}) return nil if iplist.nil? type = options[:type] || nil ips = case type when :ipv4 then iplist.select { |ip| ip["version"] == 4 } when :ipv6 then iplist.select { |ip| ip["version"] == 6 } else iplist.sort_by { |ip| ip["version"] } end if ips.empty? nil else ips.first["ipaddress"] end end end end end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/-test-/bug-3571/extconf.rb
<gh_stars>0 create_makefile("-test-/bug-3571/bug")
arnab0073/idea
.rvm/src/ruby-2.3.0/sample/pty/script.rb
<filename>.rvm/src/ruby-2.3.0/sample/pty/script.rb require 'pty' if ARGV.size == 0 then ofile = "typescript" else ofile = ARGV[0] end logfile = File.open(ofile,"a") system "stty -echo raw lnext ^_" PTY.spawn("/bin/csh") do |r_pty,w_pty,pid| Thread.new do while true w_pty.print STDIN.getc.chr w_pty.flush end end begin while true c = r_pty.sysread(512) break if c.nil? print c STDOUT.flush logfile.print c end rescue # print $@,':',$!,"\n" logfile.close end end system "stty echo -raw lnext ^v"
arnab0073/idea
.rvm/src/ruby-2.3.0/test/rubygems/test_gem_resolver_dependency_request.rb
# frozen_string_literal: false require 'rubygems/test_case' class TestGemResolverDependencyRequest < Gem::TestCase def setup super @DR = Gem::Resolver::DependencyRequest end def test_development_eh a_dep = dep 'a', '>= 1' a_dep_req = @DR.new a_dep, nil refute a_dep_req.development? b_dep = dep 'b', '>= 1', :development b_dep_req = @DR.new b_dep, nil assert b_dep_req.development? end def test_match_eh spec = util_spec 'a', 1 dependency = dep 'a', '>= 1' dr = @DR.new dependency, nil assert dr.match? spec end def test_match_eh_prerelease spec = util_spec 'a', '1.a' a_dep = dep 'a', '>= 1' a_dr = @DR.new a_dep, nil refute a_dr.match? spec a_pre_dep = dep 'a', '>= 1.a' a_pre_dr = @DR.new a_pre_dep, nil assert a_pre_dr.match? spec end def test_match_eh_prerelease_allow_prerelease spec = util_spec 'a', '2.a' a_dep = dep 'a', '>= 1' a_dr = @DR.new a_dep, nil assert a_dr.match? spec, true end def test_matches_spec_eh spec = util_spec 'a', 1 dependency = dep 'a', '>= 1' dr = @DR.new dependency, nil assert dr.matches_spec? spec end def test_matches_spec_eh_prerelease spec = util_spec 'a', '1.a' dependency = dep 'a', '>= 0' dr = @DR.new dependency, nil assert dr.matches_spec? spec end def test_requirement dependency = dep 'a', '>= 1' dr = @DR.new dependency, nil assert_equal dependency, dr.dependency end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/tcllib/diagrams.rb
<gh_stars>1-10 # # tkextlib/tcllib/diagrams.rb # by <NAME> (<EMAIL>) # # * Part of tcllib extension # * Draw diagrams # require 'tk' require 'tkextlib/tcllib.rb' # TkPackage.require('Diagrams', '0.3') TkPackage.require('Diagrams') module Tk::Tcllib module Diagrams PACKAGE_NAME = 'Diagrams'.freeze def self.package_name PACKAGE_NAME end def self.package_version begin TkPackage.require('Diagrams') rescue '' end end end end class << Tk::Tcllib::Diagrams include TkCore def drawin(canvas) tk_call('::Diagrams::drawin', canvas) canvas end alias draw_in drawin def saveps(filename) tk_call('::Diagrams::saveps', filename) filename end alias save_ps saveps def direction(dir) tk_call('::Diagrams::direction', dir) dir end def currentpos(pos) list(tk_call('::Diagrams::currentpos', pos)) end alias current_pos currentpos alias currentpos= currentpos alias current_pos= currentpos def getpos(anchor, obj) list(tk_call('::Diagrams::getpos', anchor, obj)) end alias get_pos getpos def position(x, y) list(tk_call('::Diagrams::position', x, y)) end def box(text, width=nil, height=nil) if width || height width = '' unless width height = '' unless height list(tk_call('::Diagrams::box', text, width, height)) else list(tk_call('::Diagrams::box', text)) end end def plaintext(text, width=nil, height=nil) if width || height width = '' unless width height = '' unless height list(tk_call('::Diagrams::plaintext', text, width, height)) else list(tk_call('::Diagrams::plaintext', text)) end end def circle(text, radius=nil) if radius list(tk_call('::Diagrams::circle', text, radius)) else list(tk_call('::Diagrams::circle', text)) end end def slanted(text, width=nil, height=nil, angle=nil) if width || height || angle width = '' unless width height = '' unless height if angle list(tk_call('::Diagrams::slanted', text, width, height, angle)) else list(tk_call('::Diagrams::slanted', text, width, height)) end else list(tk_call('::Diagrams::slanted', text)) end end def diamond(text, width=nil, height=nil) if width || height width = '' unless width height = '' unless height list(tk_call('::Diagrams::diamond', text, width, height)) else list(tk_call('::Diagrams::diamond', text)) end end def drum(text, width=nil, height=nil) if width || height width = '' unless width height = '' unless height list(tk_call('::Diagrams::drum', text, width, height)) else list(tk_call('::Diagrams::drum', text)) end end def arrow(text=nil, length=nil, head=nil) if length || head text = '' unless text length = '' unless length list(tk_call('::Diagrams::arrow', text, length, head)) else if text list(tk_call('::Diagrams::arrow', text)) else list(tk_call('::Diagrams::arrow')) end end end def line(*args) ary = [] args.each{|arg| if arg.kind_of?(Array) && arg.length == 2 # [length, angle] ary.concat arg else # ["POSITION", x, y] or length or angle ary << arg end } list(tk_call('::Diagrams::line', *ary)) end def bracket(dir, dist, from_pos, to_pos) list(tk_call('::Diagrams::bracket', dir, dist, from_pos, to_pos)) end def attach(anchor=None) tk_call('::Diagrams::attach', anchor) end def color(name=None) tk_call('::Diagrams::color', name) end def fillcolor(name=None) tk_call('::Diagrams::fillcolor', name) end def textcolor(name=None) tk_call('::Diagrams::textcolor', name) end def usegap(mode=None) bool(tk_call('::Diagrams::usegap', mode)) end alias use_gap usegap def xgap(val=None) number(tk_call('::Diagrams::xgap', val)) end def ygap(val=None) number(tk_call('::Diagrams::ygap', val)) end def textfont(fnt=None) tk_call('::Diagrams::textfont', fnt) end def linewidth(pixels=None) number(tk_call('::Diagrams::linewidth', pixels)) end def linestyle(style=None) tk_call('::Diagrams::linestyle', style) end def pushstate tk_call('::Diagrams::pushstate') end alias push_state pushstate def popstate tk_call('::Diagrams::popstate') end alias pop_state popstate def computepos list(tk_call('::Diagrams::computepos')) end alias compute_pos computepos def boxcoords(x1, y1, x2, y2) list(tk_call('::Diagrams::boxcoords', x1, y1, x2, y2)) end def moveobject(obj) list(tk_call('::Diagrams::moveobject', obj)) end alias move_object moveobject end
arnab0073/idea
.rvm/src/ruby-2.3.0/test/test_weakref.rb
# frozen_string_literal: false require 'test/unit' require 'weakref' class TestWeakRef < Test::Unit::TestCase def make_weakref(level = 10) if level > 0 make_weakref(level - 1) else WeakRef.new(Object.new) end end def test_ref obj = Object.new weak = WeakRef.new(obj) assert_equal(obj.to_s, weak.to_s) assert_predicate(weak, :weakref_alive?) end def test_recycled weaks = [] weak = nil 100.times do weaks << make_weakref ObjectSpace.garbage_collect ObjectSpace.garbage_collect break if weak = weaks.find {|w| !w.weakref_alive?} end assert_raise(WeakRef::RefError) {weak.to_s} assert_not_predicate(weak, :weakref_alive?) end def test_not_reference_different_object bug7304 = '[ruby-core:49044]' weakrefs = [] 3.times do obj = Object.new def obj.foo; end weakrefs << WeakRef.new(obj) ObjectSpace.garbage_collect end assert_nothing_raised(NoMethodError, bug7304) { weakrefs.each do |weak| begin weak.foo rescue WeakRef::RefError end end } end def test_weakref_finalize bug7304 = '[ruby-core:49044]' assert_normal_exit %q{ require 'weakref' obj = Object.new 3.times do WeakRef.new(obj) ObjectSpace.garbage_collect end }, bug7304 end def test_repeated_object_memory_leak bug10537 = '[ruby-core:66428]' assert_no_memory_leak(%w(-rweakref), '', <<-'end;', bug10537, timeout: 60) a = Object.new 150_000.times { WeakRef.new(a) } end; end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/net-ssh-2.6.8/lib/net/ssh/proxy/http.rb
<reponame>arnab0073/idea<filename>.rvm/gems/ruby-2.3.0/gems/net-ssh-2.6.8/lib/net/ssh/proxy/http.rb<gh_stars>10-100 require 'socket' require 'net/ssh/proxy/errors' module Net; module SSH; module Proxy # An implementation of an HTTP proxy. To use it, instantiate it, then # pass the instantiated object via the :proxy key to Net::SSH.start: # # require 'net/ssh/proxy/http' # # proxy = Net::SSH::Proxy::HTTP.new('proxy.host', proxy_port) # Net::SSH.start('host', 'user', :proxy => proxy) do |ssh| # ... # end # # If the proxy requires authentication, you can pass :user and :password # to the proxy's constructor: # # proxy = Net::SSH::Proxy::HTTP.new('proxy.host', proxy_port, # :user => "user", :password => "password") # # Note that HTTP digest authentication is not supported; Basic only at # this point. class HTTP # The hostname or IP address of the HTTP proxy. attr_reader :proxy_host # The port number of the proxy. attr_reader :proxy_port # The map of additional options that were given to the object at # initialization. attr_reader :options # Create a new socket factory that tunnels via the given host and # port. The +options+ parameter is a hash of additional settings that # can be used to tweak this proxy connection. Specifically, the following # options are supported: # # * :user => the user name to use when authenticating to the proxy # * :password => the password to use when authenticating def initialize(proxy_host, proxy_port=80, options={}) @proxy_host = proxy_host @proxy_port = proxy_port @options = options end # Return a new socket connected to the given host and port via the # proxy that was requested when the socket factory was instantiated. def open(host, port) socket = TCPSocket.new(proxy_host, proxy_port) socket.write "CONNECT #{host}:#{port} HTTP/1.0\r\n" if options[:user] credentials = ["#{options[:user]}:#{options[:password]}"].pack("m*").gsub(/\s/, "") socket.write "Proxy-Authorization: Basic #{credentials}\r\n" end socket.write "\r\n" resp = parse_response(socket) return socket if resp[:code] == 200 socket.close raise ConnectError, resp.inspect end private def parse_response(socket) version, code, reason = socket.gets.chomp.split(/ /, 3) headers = {} while (line = socket.gets.chomp) != "" name, value = line.split(/:/, 2) headers[name.strip] = value.strip end if headers["Content-Length"] body = socket.read(headers["Content-Length"].to_i) end return { :version => version, :code => code.to_i, :reason => reason, :headers => headers, :body => body } end end end; end; end
arnab0073/idea
.rvm/src/ruby-2.3.0/lib/rdoc/normal_module.rb
# frozen_string_literal: false ## # A normal module, like NormalClass class RDoc::NormalModule < RDoc::ClassModule def aref_prefix # :nodoc: 'module' end def inspect # :nodoc: "#<%s:0x%x module %s includes: %p extends: %p attributes: %p methods: %p aliases: %p>" % [ self.class, object_id, full_name, @includes, @extends, @attributes, @method_list, @aliases ] end ## # The definition of this module, <tt>module MyModuleName</tt> def definition "module #{full_name}" end ## # This is a module, returns true def module? true end def pretty_print q # :nodoc: q.group 2, "[module #{full_name}: ", "]" do q.breakable q.text "includes:" q.breakable q.seplist @includes do |inc| q.pp inc end q.breakable q.breakable q.text "constants:" q.breakable q.seplist @constants do |const| q.pp const end q.text "attributes:" q.breakable q.seplist @attributes do |attr| q.pp attr end q.breakable q.text "methods:" q.breakable q.seplist @method_list do |meth| q.pp meth end q.breakable q.text "aliases:" q.breakable q.seplist @aliases do |aliaz| q.pp aliaz end q.breakable q.text "comment:" q.breakable q.pp comment end end ## # Modules don't have one, raises NoMethodError def superclass raise NoMethodError, "#{full_name} is a module" end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/digest/extconf.rb
# $RoughId: extconf.rb,v 1.6 2001/07/13 15:38:27 knu Exp $ # $Id: extconf.rb 25189 2009-10-02 12:04:37Z akr $ require "mkmf" $INSTALLFILES = { "digest.h" => "$(HDRDIR)" } create_makefile("digest")
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/spec/unit/plugins/groovy_spec.rb
# # Author:: <NAME> <<EMAIL>> # Copyright:: Copyright (c) 2009 VMware, 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')) describe Ohai::System, "plugin groovy" do before(:each) do @ohai = Ohai::System.new @ohai[:languages] = Mash.new @ohai.stub!(:require_plugin).and_return(true) @status = 0 @stdout = "Groovy Version: 1.6.3 JVM: 1.6.0_0\n" @stderr = "" @ohai.stub!(:run_command).with({:no_status_check=>true, :command=>"groovy -v"}).and_return([@status, @stdout, @stderr]) end it "should get the groovy version from running groovy -v" do @ohai.should_receive(:run_command).with({:no_status_check=>true, :command=>"groovy -v"}).and_return([0, "Groovy Version: 1.6.3 JVM: 1.6.0_0\n", ""]) @ohai._require_plugin("groovy") end it "should set languages[:groovy][:version]" do @ohai._require_plugin("groovy") @ohai.languages[:groovy][:version].should eql("1.6.3") end it "should not set the languages[:groovy] tree up if groovy command fails" do @status = 1 @stdout = "Groovy Version: 1.6.3 JVM: 1.6.0_0\n" @stderr = "" @ohai.stub!(:run_command).with({:no_status_check=>true, :command=>"groovy -v"}).and_return([@status, @stdout, @stderr]) @ohai._require_plugin("groovy") @ohai.languages.should_not have_key(:groovy) end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/demos-en/hscale.rb
<reponame>arnab0073/idea<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/sample/demos-en/hscale.rb require "tkcanvas" if defined?($hscale_demo) && $hscale_demo $hscale_demo.destroy $hscale_demo = nil end $hscale_demo = TkToplevel.new {|w| title("Horizontal Scale Demonstration") iconname("hscale") } positionWindow($hscale_demo) base_frame = TkFrame.new($hscale_demo).pack(:fill=>:both, :expand=>true) msg = TkLabel.new(base_frame) { font $font wraplength '3.5i' justify 'left' text "An arrow and a horizontal scale are displayed below. If you click or drag mouse button 1 in the scale, you can change the length of the arrow." } msg.pack('side'=>'top') TkFrame.new(base_frame) {|frame| TkButton.new(frame) { text 'Dismiss' command proc { tmppath = $hscale_demo $hscale_demo = nil tmppath.destroy } }.pack('side'=>'left', 'expand'=>'yes') TkButton.new(frame) { text 'Show Code' command proc { showCode 'hscale' } }.pack('side'=>'left', 'expand'=>'yes') }.pack('side'=>'bottom', 'fill'=>'x', 'pady'=>'2m') def setWidth(w, width) width = width + 21 x2 = width - 30 if x2 < 21 x2 = 21 end w.coords 'poly',20,15,20,35,x2,35,x2,45,width,25,x2,5,x2,15,20,15 w.coords 'line',20,15,20,35,x2,35,x2,45,width,25,x2,5,x2,15,20,15 end TkFrame.new(base_frame) {|frame| canvas = TkCanvas.new(frame) {|c| width 50 height 50 bd 0 highlightthickness 0 TkcPolygon.new(c, '0', '0', '1', '1', '2', '2') { fill 'DeepSkyBlue' tags 'poly' } TkcLine.new(c, '0', '0', '1', '1', '2', '2', '0', '0') { fill 'black' tags 'line' } }.pack('side'=>'top', 'expand'=>'yes', 'anchor'=>'s', 'fill'=>'x', 'padx'=>'15') scale = TkScale.new(frame) { orient 'horizontal' length 284 from 0 to 250 command proc{|value| setWidth(canvas, value)} tickinterval 50 }.pack('side'=>'bottom', 'expand'=>'yes', 'anchor'=>'n') scale.set 75 }.pack('side'=>'top', 'fill'=>'x')
arnab0073/idea
.rvm/src/ruby-2.3.0/lib/rubygems/resolver/molinillo.rb
<gh_stars>0 # frozen_string_literal: false require 'rubygems/resolver/molinillo/lib/molinillo'
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/winrm-1.8.1/spec/spec_helper.rb
<reponame>arnab0073/idea # encoding: UTF-8 require 'rubygems' require 'bundler/setup' require 'winrm' require 'json' require_relative 'matchers' # Creates a WinRM connection for integration tests module ConnectionHelper # rubocop:disable AbcSize def winrm_connection winrm = WinRM::WinRMWebService.new( config[:endpoint], config[:auth_type].to_sym, config[:options]) winrm.logger.level = :error winrm end # rubocop:enable AbcSize def config @config ||= begin cfg = symbolize_keys(YAML.load(File.read(winrm_config_path))) cfg[:options].merge!(basic_auth_only: true) unless cfg[:auth_type].eql? :kerberos merge_environment!(cfg) cfg end end def merge_environment!(config) merge_config_option_from_environment(config, 'user') merge_config_option_from_environment(config, 'pass') merge_config_option_from_environment(config, 'no_ssl_peer_verification') if ENV['use_ssl_peer_fingerprint'] config[:options][:ssl_peer_fingerprint] = ENV['winrm_cert'] end config[:endpoint] = ENV['winrm_endpoint'] if ENV['winrm_endpoint'] end def merge_config_option_from_environment(config, key) env_key = 'winrm_' + key config[:options][key.to_sym] = ENV[env_key] if ENV[env_key] end def winrm_config_path # Copy config-example.yml to config.yml and edit for your local configuration path = File.expand_path("#{File.dirname(__FILE__)}/config.yml") unless File.exist?(path) # user hasn't done this, so use sane defaults for unit tests path = File.expand_path("#{File.dirname(__FILE__)}/config-example.yml") end path end # rubocop:disable Metrics/MethodLength def symbolize_keys(hash) hash.each_with_object({}) do |(key, value), result| new_key = case key when String then key.to_sym else key end new_value = case value when Hash then symbolize_keys(value) else value end result[new_key] = new_value result end end # rubocop:enable Metrics/MethodLength end RSpec.configure do |config| config.include(ConnectionHelper) end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/benchmark/bm_vm2_method.rb
def m nil end i=0 while i<6_000_000 # benchmark loop 2 i+=1 m; m; m; m; m; m; m; m; end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/puma-1.6.3/ext/puma_http11/extconf.rb
require 'mkmf' dir_config("puma_http11") create_makefile("puma/puma_http11")
arnab0073/idea
.rvm/src/ruby-2.3.0/ext/-test-/bug-5832/extconf.rb
<gh_stars>0 # frozen_string_literal: false create_makefile("-test-/bug-5832/bug")
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/gssapi-1.2.0/lib/gssapi/simple.rb
=begin Copyright © 2010 <NAME> <<EMAIL>> Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php =end module GSSAPI # This class is a simple wrapper around the most common usage of GSSAPI. If you are looking at doing # something a bit more advanced you may want to check out the LibGSSAPI module. class Simple attr_reader :context attr_reader :delegated_credentials # Initialize a new GSSAPI::Simple object # @param [String] host_name the fully qualified host name # @param [String] service_name The service name. This can either be a # GSS_KRB5_NT_PRINCIPAL_NAME in the form of srvc/fqdn@REALM # or # GSS_C_NT_HOSTBASED_SERVICE in the form of srvc@fqdn # If there is no '@fqdn' part, the host_name will be appended. # If no service_name is given at all the default service of 'host@fqdn' will be used. def initialize(host_name, service_name=nil, keytab=nil) @host = host_name @service = service_name.nil? ? "host@#{@host}" : (service_name.include?('@') ? service_name : "#{service_name}@#{@host}") @int_svc_name = import_name(@service) @context = nil # the security context @scred = nil # the service credentials. really only used for the server-side via acquire_credentials set_keytab(keytab) unless keytab.nil? @delegated_credentials = nil end # Convert a String to a GSSAPI usable buffer (gss_buffer_desc) # @param [String] str the string to convert def import_name(str) buff_str = LibGSSAPI::UnManagedGssBufferDesc.new buff_str.value = str # Choose the appropriate mechanism based on the string passed. if (str =~ /[A-Za-z0-9]+\/[^@]+@.+$/) mech = LibGSSAPI::GssOID.gss_c_no_oid else mech = LibGSSAPI::GSS_C_NT_HOSTBASED_SERVICE end name = FFI::MemoryPointer.new :pointer # gss_name_t min_stat = FFI::MemoryPointer.new :OM_uint32 maj_stat = LibGSSAPI.gss_import_name(min_stat, buff_str.pointer, mech, name) raise GssApiError.new(maj_stat, min_stat), "gss_import_name did not return GSS_S_COMPLETE" if maj_stat != 0 LibGSSAPI::GssNameT.new(name.get_pointer(0)) end # Initialize the GSS security context (client initiator). If there was a previous call that issued a # continue you can pass the continuation token in via the token param. # If no flags are set the default flags are LibGSSAPI::GSS_C_MUTUAL_FLAG | LibGSSAPI::GSS_C_SEQUENCE_FLAG # @param [String] in_token an input token sent from the remote service in a continuation. # @param [Hash] opts misc opts to be set # @option opts [Fixnum] :flags override all other flags. If you set the :delegate option this option will override it. # @see http://tools.ietf.org/html/rfc4121#section-4.1.1.1 # @option opts [Boolean] :delegate if true set the credential delegate flag # @return [String, true] if a continuation flag is set it will return the output token that is needed to send # to the remote host. Otherwise it returns true and the GSS security context has been established. def init_context(in_token = nil, opts = {}) min_stat = FFI::MemoryPointer.new :OM_uint32 pctx = (@context.nil? ? LibGSSAPI::GssCtxIdT.gss_c_no_context.address_of : @context.address_of) mech = LibGSSAPI::GssOID.gss_c_no_oid if(opts[:flags]) flags = opts[:flags] else flags = (LibGSSAPI::GSS_C_MUTUAL_FLAG | LibGSSAPI::GSS_C_SEQUENCE_FLAG | LibGSSAPI::GSS_C_CONF_FLAG | LibGSSAPI::GSS_C_INTEG_FLAG) flags |= LibGSSAPI::GSS_C_DELEG_FLAG if opts[:delegate] flags |= LibGSSAPI::GSS_C_DELEG_POLICY_FLAG if opts[:delegate] end in_tok = LibGSSAPI::UnManagedGssBufferDesc.new in_tok.value = in_token out_tok = LibGSSAPI::ManagedGssBufferDesc.new ret_flags = FFI::MemoryPointer.new :OM_uint32 maj_stat = LibGSSAPI.gss_init_sec_context(min_stat, nil, pctx, @int_svc_name, mech, flags, 0, nil, in_tok.pointer, nil, out_tok.pointer, ret_flags, nil) raise GssApiError.new(maj_stat, min_stat), "gss_init_sec_context did not return GSS_S_COMPLETE" if maj_stat > 1 # The returned context may be equal to the passed in @context. If so, we # must not create another AutoPointer to the same gss_buffer_t. If we do # we will double delete it. ctx = pctx.get_pointer(0) @context = LibGSSAPI::GssCtxIdT.new(ctx) if ctx != @context maj_stat == 1 ? out_tok.value : true end # Accept a security context that was initiated by a remote peer. # @param [String] in_token The token sent by the remote client to initiate the context # @return [String, true] If this is part of a continuation it will return a token to be passed back to the remote # otherwise it will simply return true. def accept_context(in_token) raise GssApiError, "No credentials yet acquired. Call #{self.class.name}#acquire_credentials first" if @scred.nil? min_stat = FFI::MemoryPointer.new :OM_uint32 pctx = (@context.nil? ? LibGSSAPI::GssCtxIdT.gss_c_no_context.address_of : @context.address_of) no_chn_bind = LibGSSAPI::GSS_C_NO_CHANNEL_BINDINGS @client = FFI::MemoryPointer.new :pointer # Will hold the initiating client name after the call mech = FFI::MemoryPointer.new :pointer # Will hold the mech being used after the call in_tok = GSSAPI::LibGSSAPI::UnManagedGssBufferDesc.new in_tok.value = in_token out_tok = GSSAPI::LibGSSAPI::ManagedGssBufferDesc.new ret_flags = FFI::MemoryPointer.new :OM_uint32 delegated_cred_handle = FFI::MemoryPointer.new :pointer maj_stat = LibGSSAPI.gss_accept_sec_context(min_stat, pctx, @scred, in_tok.pointer, no_chn_bind, @client, mech, out_tok.pointer, ret_flags, nil, delegated_cred_handle) raise GssApiError.new(maj_stat, min_stat), "gss_accept_sec_context did not return GSS_S_COMPLETE" if maj_stat > 1 if (ret_flags.read_uint32 & LibGSSAPI::GSS_C_DELEG_FLAG) != 0 @delegated_credentials = LibGSSAPI::GssCredIdT.new(delegated_cred_handle.get_pointer(0)) end # The returned context may be equal to the passed in @context. If so, we # must not create another AutoPointer to the same gss_buffer_t. If we do # we will double delete it. ctx = pctx.get_pointer(0) @context = LibGSSAPI::GssCtxIdT.new(ctx) if ctx != @context out_tok.length > 0 ? out_tok.value : true end def get_mic(token) min_stat = FFI::MemoryPointer.new :OM_uint32 qop_req = GSSAPI::LibGSSAPI::GSS_C_QOP_DEFAULT in_buff = GSSAPI::LibGSSAPI::UnManagedGssBufferDesc.new in_buff.value = token out_buff = GSSAPI::LibGSSAPI::ManagedGssBufferDesc.new maj_stat = GSSAPI::LibGSSAPI.gss_get_mic(min_stat, @context, qop_req, in_buff.pointer, out_buff.pointer) raise GssApiError.new(maj_stat, min_stat), "Failed to gss_get_mic" if maj_stat != 0 out_buff.value end # Get textual representation of internal GSS name # @return [String] textual representation of internal GSS name def display_name raise GssApiError.new(), "No context accepted yet. Call #{self.class.name}#accept_context(in_token) first" if @client.nil? output_name = GSSAPI::LibGSSAPI::ManagedGssBufferDesc.new min_stat = FFI::MemoryPointer.new :OM_uint32 maj_stat = LibGSSAPI.gss_display_name(min_stat, @client.get_pointer(0), output_name.pointer, nil) if maj_stat != GSSAPI::LibGSSAPI::GSS_S_COMPLETE raise GssApiError.new(maj_stat, min_stat), "gss_display_name did not return GSS_S_COMPLETE but #{ maj_stat }" end output_name.value end # Acquire security credentials. This does not log you in. It grabs the credentials from a cred cache or keytab. # @param [Hash] opts options to pass to the gss_acquire_cred function. # @option opts [String] :usage The credential usage type (:accept, :initiate, :both). It defaults to 'accept' since # this method is most usually called on the server only. # @return [true] It will return true if everything succeeds and the @scred variable will be set for future methods. If # an error ocurrs an exception will be raised. def acquire_credentials(princ = @int_svc_name, opts = {:usage => :accept}) min_stat = FFI::MemoryPointer.new :OM_uint32 scred = FFI::MemoryPointer.new :pointer case opts[:usage] when :accept usage = LibGSSAPI::GSS_C_ACCEPT when :initiate usage = LibGSSAPI::GSS_C_INITIATE when :both usage = LibGSSAPI::GSS_C_BOTH else raise GssApiError, "Bad option passed to #{self.class.name}#acquire_credentials" end maj_stat = LibGSSAPI.gss_acquire_cred(min_stat, princ, 0, LibGSSAPI::GSS_C_NO_OID_SET, usage, scred, nil, nil) raise GssApiError.new(maj_stat, min_stat), "gss_acquire_cred did not return GSS_S_COMPLETE" if maj_stat != 0 @scred = LibGSSAPI::GssCredIdT.new(scred.get_pointer(0)) true end # Wrap a message using gss_wrap. It can either encrypt the message (confidentiality) or simply sign it (integrity). # @param [String] msg The message to wrap # @param [Boolean] encrypt Whether or not to encrypt the message or just sign it. The default is to encrypt. # @return [String] The wrapped message. It will raise an exception on error def wrap_message(msg, encrypt = true) min_stat = FFI::MemoryPointer.new :OM_uint32 conf_req = (encrypt ? 1 : 0) qop_req = GSSAPI::LibGSSAPI::GSS_C_QOP_DEFAULT in_buff = GSSAPI::LibGSSAPI::UnManagedGssBufferDesc.new in_buff.value = msg conf_state = FFI::MemoryPointer.new :OM_uint32 out_buff = GSSAPI::LibGSSAPI::ManagedGssBufferDesc.new maj_stat = GSSAPI::LibGSSAPI.gss_wrap(min_stat, @context, conf_req, qop_req, in_buff.pointer, conf_state, out_buff.pointer) raise GssApiError.new(maj_stat, min_stat), "Failed to gss_wrap message" if maj_stat != 0 out_buff.value end # Unwrap a message previously wrapped with gss_wrap. # @param [String] msg The message to unwrap # @param [Boolean] encrypted Whether or not this message was encrypted (true) or just signed (false) def unwrap_message(msg, encrypted = true) min_stat = FFI::MemoryPointer.new :OM_uint32 in_buff = GSSAPI::LibGSSAPI::UnManagedGssBufferDesc.new in_buff.value = msg out_buff = GSSAPI::LibGSSAPI::ManagedGssBufferDesc.new conf_state = FFI::MemoryPointer.new :int conf_state.write_int((encrypted ? 1 : 0)) q_op = FFI::MemoryPointer.new :OM_uint32 q_op.write_int(0) maj_stat = GSSAPI::LibGSSAPI.gss_unwrap(min_stat, @context, in_buff.pointer, out_buff.pointer, conf_state, q_op) raise GssApiError.new(maj_stat, min_stat), "Failed to gss_unwrap message" if maj_stat != 0 out_buff.value end # Add a path to a custom keytab file # @param [String] keytab the path to the keytab def set_keytab(keytab) maj_stat = LibGSSAPI.krb5_gss_register_acceptor_identity(keytab) raise GssApiError.new(maj_stat, min_stat), "krb5_gss_register_acceptor_identity did not return GSS_S_COMPLETE" if maj_stat != 0 true end end # Simple end # GSSAPI
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/tcllib/cursor.rb
# # tkextlib/tcllib/cursor.rb # by <NAME> (<EMAIL>) # # * Part of tcllib extension # * Procedures to handle CURSOR data # require 'tk' require 'tkextlib/tcllib.rb' module Tk module Tcllib module Cursor PACKAGE_NAME = 'cursor'.freeze def self.package_name PACKAGE_NAME end def self.package_version begin TkPackage.require('cursor') rescue '' end end def self.not_available fail RuntimeError, "'tkextlib/tcllib/cursor' extension is not available on your current environment." end def self.cursor_display(win=None) Tk::Tcllib::Cursor.not_available end def self.cursor_propagate(win, cursor) Tk::Tcllib::Cursor.not_available end def self.cursor_restore(win, cursor = None) Tk::Tcllib::Cursor.not_available end end end def self.cursor_display(parent=None) # Pops up a dialog with a listbox containing all the cursor names. # Selecting a cursor name will display it in that dialog. # This is simply for viewing any available cursors on the platform . #tk_call_without_enc('::cursor::display', parent) Tk::Tcllib::Cursor.cursor_display(parent) end end class TkWindow def cursor_propagate(cursor) # Sets the cursor for self and all its descendants to cursor. #tk_call_without_enc('::cursor::propagate', @path, cursor) Tk::Tcllib::Cursor.cursor_propagate(self, cursor) end def cursor_restore(cursor = None) # Restore the original or previously set cursor for self and all its # descendants. If cursor is specified, that will be used if on any # widget that did not have a preset cursor (set by a previous call # to TkWindow#cursor_propagate). #tk_call_without_enc('::cursor::restore', @path, cursor) Tk::Tcllib::Cursor.cursor_restore(self, cursor) end end # TkPackage.require('cursor', '0.1') TkPackage.require('cursor') module Tk module Tcllib class << Cursor undef not_available end module Cursor extend TkCore def self.cursor_display(win=None) tk_call_without_enc('::cursor::display', _epath(win)) end def self.cursor_propagate(win, cursor) #tk_call_without_enc('::cursor::propagate', win.path, cursor) tk_call_without_enc('::cursor::propagate', _epath(win), cursor) end def self.cursor_restore(win, cursor = None) #tk_call_without_enc('::cursor::restore', win.path, cursor) tk_call_without_enc('::cursor::restore', _epath(win), cursor) end end end end
arnab0073/idea
.rvm/src/ruby-2.3.0/lib/rdoc/token_stream.rb
<reponame>arnab0073/idea<filename>.rvm/src/ruby-2.3.0/lib/rdoc/token_stream.rb # frozen_string_literal: false ## # A TokenStream is a list of tokens, gathered during the parse of some entity # (say a method). Entities populate these streams by being registered with the # lexer. Any class can collect tokens by including TokenStream. From the # outside, you use such an object by calling the start_collecting_tokens # method, followed by calls to add_token and pop_token. module RDoc::TokenStream ## # Converts +token_stream+ to HTML wrapping various tokens with # <tt><span></tt> elements. The following tokens types are wrapped in spans # with the given class names: # # TkCONSTANT :: 'ruby-constant' # TkKW :: 'ruby-keyword' # TkIVAR :: 'ruby-ivar' # TkOp :: 'ruby-operator' # TkId :: 'ruby-identifier' # TkNode :: 'ruby-node' # TkCOMMENT :: 'ruby-comment' # TkREGEXP :: 'ruby-regexp' # TkSTRING :: 'ruby-string' # TkVal :: 'ruby-value' # # Other token types are not wrapped in spans. def self.to_html token_stream token_stream.map do |t| next unless t style = case t when RDoc::RubyToken::TkCONSTANT then 'ruby-constant' when RDoc::RubyToken::TkKW then 'ruby-keyword' when RDoc::RubyToken::TkIVAR then 'ruby-ivar' when RDoc::RubyToken::TkOp then 'ruby-operator' when RDoc::RubyToken::TkId then 'ruby-identifier' when RDoc::RubyToken::TkNode then 'ruby-node' when RDoc::RubyToken::TkCOMMENT then 'ruby-comment' when RDoc::RubyToken::TkREGEXP then 'ruby-regexp' when RDoc::RubyToken::TkSTRING then 'ruby-string' when RDoc::RubyToken::TkVal then 'ruby-value' end text = CGI.escapeHTML t.text if style then "<span class=\"#{style}\">#{text}</span>" else text end end.join end ## # Adds +tokens+ to the collected tokens def add_tokens(*tokens) tokens.flatten.each { |token| @token_stream << token } end alias add_token add_tokens ## # Starts collecting tokens def collect_tokens @token_stream = [] end alias start_collecting_tokens collect_tokens ## # Remove the last token from the collected tokens def pop_token @token_stream.pop end ## # Current token stream def token_stream @token_stream end ## # Returns a string representation of the token stream def tokens_to_s token_stream.compact.map { |token| token.text }.join '' end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/syck/lib/syck/ypath.rb
# # YAML::YPath # warn "#{caller[0]}: YAML::YPath is deprecated" if $VERBOSE module Syck class YPath attr_accessor :segments, :predicates, :flags def initialize( str ) @segments = [] @predicates = [] @flags = nil while str =~ /^\/?(\/|[^\/\[]+)(?:\[([^\]]+)\])?/ @segments.push $1 @predicates.push $2 str = $' end unless str.to_s.empty? @segments += str.split( "/" ) end if @segments.length == 0 @segments.push "." end end def self.each_path( str ) # # Find choices # paths = [] str = "(#{ str })" while str.sub!( /\(([^()]+)\)/, "\n#{ paths.length }\n" ) paths.push $1.split( '|' ) end # # Construct all possible paths # all = [ str ] ( paths.length - 1 ).downto( 0 ) do |i| all = all.collect do |a| paths[i].collect do |p| a.gsub( /\n#{ i }\n/, p ) end end.flatten.uniq end all.collect do |path| yield YPath.new( path ) end end end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/lib/ohai/plugins/solaris2/hostname.rb
# # Author:: <NAME> (<<EMAIL>>) # Author:: <NAME> <<EMAIL>> # Copyright:: Copyright (c) 2008 Opscode, Inc. # 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. # require 'socket' provides "hostname", "fqdn" hostname from("hostname") fqdn_lookup = Socket.getaddrinfo(hostname, nil, nil, nil, nil, Socket::AI_CANONNAME).first[2] if fqdn_lookup.split('.').length > 1 # we recieved an fqdn fqdn fqdn_lookup else # default to assembling one fqdn(from("hostname") + "." + from("domainname")) end
arnab0073/idea
.rvm/src/ruby-2.3.0/test/-ext-/bignum/test_bigzero.rb
# frozen_string_literal: false require 'test/unit' require "-test-/bignum" class TestBignum < Test::Unit::TestCase class TestBigZero < Test::Unit::TestCase def test_equal_0 bug8204 = '[ruby-core:53893] [Bug #8204]' (0..10).each do |i| assert_equal(0, Bug::Bignum.zero(i), "#{bug8204} Bignum.zero(#{i})") end end end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/-test-/old_thread_select/extconf.rb
create_makefile("-test-/old_thread_select/old_thread_select")
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/net-ssh-2.6.8/test/test_all.rb
<gh_stars>10-100 $: << '.' # $ ruby -Ilib -Itest -rrubygems test/test_all.rb # $ ruby -Ilib -Itest -rrubygems test/transport/test_server_version.rb Dir.chdir(File.dirname(__FILE__)) do test_files = Dir['**/test_*.rb']-['test_all.rb'] # prevent circular require test_files = test_files.reject { |f| f =~ /^manual/ } test_files = test_files.select { |f| f =~ Regexp.new(ENV['ONLY']) } if ENV['ONLY'] test_files = test_files.reject { |f| f =~ Regexp.new(ENV['EXCEPT']) } if ENV['EXCEPT'] test_files.each { |file| require(file) } end
arnab0073/idea
.rvm/src/ruby-2.3.0/test/rubygems/test_gem_command.rb
# frozen_string_literal: false require 'rubygems/test_case' require 'rubygems/command' class Gem::Command public :parser end class TestGemCommand < Gem::TestCase def setup super @xopt = nil Gem::Command.common_options.clear Gem::Command.common_options << [ ['-x', '--exe', 'Execute'], lambda do |*a| @xopt = true end ] @cmd_name = 'doit' @cmd = Gem::Command.new @cmd_name, 'summary' end def test_self_add_specific_extra_args added_args = %w[--all] @cmd.add_option '--all' do |v,o| end Gem::Command.add_specific_extra_args @cmd_name, added_args assert_equal added_args, Gem::Command.specific_extra_args(@cmd_name) h = @cmd.add_extra_args [] assert_equal added_args, h end def test_self_add_specific_extra_args_unknown added_args = %w[--definitely_not_there] Gem::Command.add_specific_extra_args @cmd_name, added_args assert_equal added_args, Gem::Command.specific_extra_args(@cmd_name) h = @cmd.add_extra_args [] assert_equal [], h end def test_basic_accessors assert_equal "doit", @cmd.command assert_equal "gem doit", @cmd.program_name assert_equal "summary", @cmd.summary end def test_common_option_in_class assert Array === Gem::Command.common_options end def test_defaults @cmd.add_option('-h', '--help [COMMAND]', 'Get help on COMMAND') do |value, options| options[:help] = value end @cmd.defaults = { :help => true } @cmd.when_invoked do |options| assert options[:help], "Help options should default true" end use_ui @ui do @cmd.invoke end assert_match %r|Usage: gem doit|, @ui.output end def test_invoke done = false @cmd.when_invoked { done = true } use_ui @ui do @cmd.invoke end assert done end def test_invoke_with_bad_options use_ui @ui do @cmd.when_invoked do true end ex = assert_raises OptionParser::InvalidOption do @cmd.invoke('-zzz') end assert_match(/invalid option:/, ex.message) end end def test_invoke_with_common_options @cmd.when_invoked do true end use_ui @ui do @cmd.invoke "-x" end assert @xopt, "Should have done xopt" end def test_invoke_with_build_args @cmd.when_invoked { true } use_ui @ui do @cmd.invoke_with_build_args ["-x"], ["--awesome=true"] end assert_equal ["--awesome=true"], @cmd.options[:build_args] end # Returning false from the command handler invokes the usage output. def test_invoke_with_help done = false use_ui @ui do @cmd.add_option('-h', '--help [COMMAND]', 'Get help on COMMAND') do |value, options| options[:help] = true done = true end @cmd.invoke('--help') assert done end assert_match(/Usage/, @ui.output) assert_match(/gem doit/, @ui.output) assert_match(/\[options\]/, @ui.output) assert_match(/-h/, @ui.output) assert_match(/--help \[COMMAND\]/, @ui.output) assert_match(/Get help on COMMAND/, @ui.output) assert_match(/-x/, @ui.output) assert_match(/--exe/, @ui.output) assert_match(/Execute/, @ui.output) assert_match(/Common Options:/, @ui.output) end def test_invoke_with_options @cmd.add_option('-h', '--help [COMMAND]', 'Get help on COMMAND') do |value, options| options[:help] = true end @cmd.when_invoked do |opts| assert opts[:help] end use_ui @ui do @cmd.invoke '-h' end assert_match %r|Usage: gem doit|, @ui.output end def test_option_recognition @cmd.add_option('-h', '--help [COMMAND]', 'Get help on COMMAND') do |value, options| options[:help] = true end @cmd.add_option('-f', '--file FILE', 'File option') do |value, options| options[:help] = true end assert @cmd.handles?(['-x']) assert @cmd.handles?(['-h']) assert @cmd.handles?(['-h', 'command']) assert @cmd.handles?(['--help', 'command']) assert @cmd.handles?(['-f', 'filename']) assert @cmd.handles?(['--file=filename']) refute @cmd.handles?(['-z']) refute @cmd.handles?(['-f']) refute @cmd.handles?(['--toothpaste']) args = ['-h', 'command'] @cmd.handles?(args) assert_equal ['-h', 'command'], args end def test_show_lookup_failure_suggestions_local correct = "non_existent_with_hint" misspelled = "nonexistent_with_hint" spec_fetcher do |fetcher| fetcher.spec correct, 2 end use_ui @ui do @cmd.show_lookup_failure misspelled, Gem::Requirement.default, [], :local end expected = <<-EXPECTED ERROR: Could not find a valid gem 'nonexistent_with_hint' (>= 0) in any repository EXPECTED assert_equal expected, @ui.error end def test_show_lookup_failure_suggestions_none spec_fetcher do |fetcher| fetcher.spec 'correct', 2 end use_ui @ui do @cmd.show_lookup_failure 'other', Gem::Requirement.default, [], :remote end expected = <<-EXPECTED ERROR: Could not find a valid gem 'other' (>= 0) in any repository EXPECTED assert_equal expected, @ui.error end def test_show_lookup_failure_suggestions_remote correct = "non_existent_with_hint" misspelled = "nonexistent_with_hint" spec_fetcher do |fetcher| fetcher.spec correct, 2 end use_ui @ui do @cmd.show_lookup_failure misspelled, Gem::Requirement.default, [], :remote end expected = <<-EXPECTED ERROR: Could not find a valid gem 'nonexistent_with_hint' (>= 0) in any repository ERROR: Possible alternatives: non_existent_with_hint EXPECTED assert_equal expected, @ui.error end end
arnab0073/idea
.rvm/src/ruby-2.3.0/test/rdoc/test_rdoc_rd_inline.rb
# frozen_string_literal: false require 'rdoc/test_case' class TestRDocRdInline < RDoc::TestCase def setup super @inline = RDoc::RD::Inline.new '+text+', 'text' end def test_class_new inline = RDoc::RD::Inline.new @inline refute_equal inline.rdoc, inline.reference end def test_initialize inline = RDoc::RD::Inline.new 'text' assert_equal inline.rdoc, inline.reference refute_same inline.rdoc, inline.reference end def test_initialize_inline inline = RDoc::RD::Inline.new @inline assert_equal '+text+', inline.rdoc assert_equal 'text', inline.reference end def test_append_inline out = @inline.append @inline assert_same @inline, out assert_equal '+text++text+', @inline.rdoc assert_equal 'texttext', @inline.reference end def test_append_string @inline.append ' more' assert_equal '+text+ more', @inline.rdoc assert_equal 'text more', @inline.reference end def test_equals2 assert_equal @inline, RDoc::RD::Inline.new('+text+', 'text') refute_equal @inline, RDoc::RD::Inline.new('+text+', 'other') refute_equal @inline, RDoc::RD::Inline.new('+other+', 'text') refute_equal @inline, Object.new end def test_inspect assert_equal '(inline: +text+)', @inline.inspect end def test_to_s assert_equal '+text+', @inline.to_s end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/safe-tk.rb
<reponame>arnab0073/idea #!/usr/bin/env ruby # This script is a sample of MultiTkIp class require "multi-tk" ############################### TkLabel.new(:text=>'This is the Default Master Ipnterpreter').pack(:padx=>5, :pady=>3) TkButton.new(:text=>'QUIT', :command=>proc{exit}).pack(:pady=>3) TkFrame.new(:borderwidth=>2, :height=>3, :relief=>:sunken).pack(:fill=>:x, :expand=>true, :padx=>10, :pady=>7) safe0_p = proc{|*args| p args} ############################### puts "---- create a safe slave IP with Ruby's safe-level == 1 ----------" ip = MultiTkIp.new_safe_slave(1){|*args| safe0_p["safe_slave safe_level == #{$SAFE}", args]} puts "\n---- create procs ----------" puts 'x = proc{p [\'proc x\', "$SAFE==#{$SAFE}"]; exit}' #x = proc{p ['proc x', "$SAFE==#{$SAFE}"]; exit} x = proc{p ['proc x', "$SAFE==#{$SAFE}"]; exit} TkLabel.new(:text=>'x = proc{p [\'proc x\', "$SAFE==#{$SAFE}"]; exit}', :anchor=>:w).pack(:fill=>:x) puts 'y = proc{|label| p [\'proc y\', "$SAFE==#{$SAFE}", label]; label.text($SAFE)}' y = proc{|label| p ['proc y', "$SAFE==#{$SAFE}", label]; label.text($SAFE)} TkLabel.new(:text=>'y = proc{|label| p [\'proc y\', "$SAFE==#{$SAFE}", label]; label.text($SAFE)}', :anchor=>:w).pack(:fill=>:x) puts 'z = proc{p [\'proc z\', "$SAFE==#{$SAFE}"]; exit}' z = proc{p ['proc z', "$SAFE==#{$SAFE}"]; exit} TkLabel.new(:text=>'z = proc{p [\'proc z\', "$SAFE==#{$SAFE}"]; exit}', :anchor=>:w).pack(:fill=>:x) puts "\n---- call 1st eval_proc ----------" print 'lbl = ' p lbl = ip.eval_proc{ TkLabel.new(:text=>"1st eval_proc : $SAFE == #{$SAFE}").pack f = TkFrame.new.pack TkLabel.new(f, :text=>"$SAFE == ").pack(:side=>:left) # TkLabel.new(f, :text=>" (<-- 'lbl' widget is here)").pack(:side=>:right) l = TkLabel.new(f).pack(:side=>:right) TkButton.new(:text=>':command=>proc{l.text($SAFE)}', :command=>proc{l.text($SAFE)}).pack(:fill=>:x, :padx=>5) TkButton.new(:text=>':command=>x', :command=>x).pack(:fill=>:x, :padx=>5) TkButton.new(:text=>':command=>proc{exit}', :command=>proc{ safe0_p["'exit' is called at $SAFE=#{$SAFE}"];exit} ).pack(:fill=>:x, :padx=>5) TkFrame.new(:borderwidth=>2, :height=>3, :relief=>:sunken).pack(:fill=>:x, :expand=>true, :padx=>10, :pady=>7) l # return the label widget } puts "\n---- change the safe slave IP's safe-level ==> 3 ----------" ip.safe_level = 3 puts "\n---- call 2nd eval_proc ----------" p ip.eval_proc(proc{ TkLabel.new(:text=>"2nd eval_proc : $SAFE == #{$SAFE}").pack f = TkFrame.new.pack TkLabel.new(f, :text=>"$SAFE == ").pack(:side=>:left) l = TkLabel.new(f, :text=>$SAFE).pack(:side=>:right) TkButton.new(:text=>':command=>proc{l.text($SAFE)}', :command=>proc{l.text($SAFE)}).pack(:fill=>:x, :padx=>5) TkButton.new(:text=>':command=>proc{y.call(l)}', :command=>proc{y.call(l)}).pack(:fill=>:x, :padx=>5) TkButton.new(:text=>':command=>proc{Proc.new(&y).call(l)}', :command=>proc{ Proc.new(&y).call(l) }).pack(:fill=>:x, :padx=>5) TkButton.new(:text=>':command=>proc{MultiTkIp._proc_on_current_safelevel(y).call(l)}', :command=>proc{ MultiTkIp._proc_on_current_safelevel(y).call(l) }).pack(:fill=>:x, :padx=>5) if false && Object.const_defined?(:RubyVM) && ::RubyVM.class == Class TkButton.new(:text=>':command=>proc{Thread.new(l, &y).value}', :command=>proc{ Thread.new(l, &y).value }).pack(:fill=>:x, :padx=>5) else # KNOWN BUG:: # Current multi-tk.rb cannot support long term threads on callbacks. # Such a thread freezes the Ruby/Tk process. end TkButton.new(:text=>':command=>proc{z.call}', :command=>proc{z.call}).pack(:fill=>:x, :padx=>5) TkFrame.new(:borderwidth=>2, :height=>3, :relief=>:sunken).pack(:fill=>:x, :expand=>true, :padx=>10, :pady=>7) }) puts "\n---- call 1st and 2nd eval_str ----------" p bind = ip.eval_str(' TkLabel.new(:text=>"1st and 2nd eval_str : $SAFE == #{$SAFE}").pack f = TkFrame.new.pack TkLabel.new(f, :text=>"$SAFE == ").pack(:side=>:left) l = TkLabel.new(f, :text=>$SAFE).pack(:side=>:right) TkButton.new(:text=>":command=>proc{y.call(l)}", :command=>proc{y.call(l)}).pack(:fill=>:x, :padx=>5) binding ', binding) p ip.eval_str(" TkButton.new(:text=>':command=>proc{ l.text = $SAFE }', :command=>proc{ l.text = $SAFE }).pack(:fill=>:x, :padx=>5) TkFrame.new(:borderwidth=>2, :height=>3, :relief=>:sunken).pack(:fill=>:x, :expand=>true, :padx=>10, :pady=>7) ", bind) puts "\n---- change the safe slave IP's safe-level ==> 4 ----------" ip.safe_level = 4 puts "\n---- call 3rd and 4th eval_proc ----------" p ip.eval_proc{ TkLabel.new(:text=>"3rd and 4th eval_proc : $SAFE == #{$SAFE}").pack } p ip.eval_proc{ TkButton.new(:text=>':command=>proc{ lbl.text = $SAFE }', :command=>proc{ lbl.text = $SAFE }).pack(:fill=>:x, :padx=>5) } puts "\n---- start event-loop ( current $SAFE == #{$SAFE} ) ----------" Tk.mainloop
arnab0073/idea
.rvm/src/ruby-2.3.0/ext/io/console/extconf.rb
# frozen_string_literal: false require 'mkmf' ok = true hdr = nil case when macro_defined?("_WIN32", "") # rb_w32_map_errno: 1.8.7 vk_header = File.exist?("#$srcdir/win32_vk.list") ? "chksum" : "inc" vk_header = "#{'{$(srcdir)}' if $nmake == ?m}win32_vk.#{vk_header}" when hdr = %w"termios.h termio.h".find {|h| have_header(h)} have_func("cfmakeraw", hdr) when have_header(hdr = "sgtty.h") %w"stty gtty".each {|f| have_func(f, hdr)} else ok = false end if ok have_header("sys/ioctl.h") if hdr # rb_check_hash_type: 1.9.3 # rb_io_get_write_io: 1.9.1 # rb_cloexec_open: 2.0.0 $defs << "-D""ENABLE_IO_GETPASS=1" create_makefile("io/console") {|conf| conf << "\n""VK_HEADER = #{vk_header}\n" } end
arnab0073/idea
.rvm/src/ruby-2.3.0/test/test_prime.rb
# frozen_string_literal: false require 'test/unit' require 'prime' require 'timeout' class TestPrime < Test::Unit::TestCase # The first 100 prime numbers PRIMES = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, ] def test_each primes = [] Prime.each do |p| break if p > 541 primes << p end assert_equal PRIMES, primes end def test_each_by_prime_number_theorem 3.upto(15) do |i| max = 2**i primes = [] Prime.each do |p| break if p >= max primes << p end # Prime number theorem assert_operator primes.length, :>=, max/Math.log(max) delta = 0.05 li = (2..max).step(delta).inject(0){|sum,x| sum + delta/Math.log(x)} assert_operator primes.length, :<=, li end end def test_each_without_block enum = Prime.each assert_respond_to(enum, :each) assert_kind_of(Enumerable, enum) assert_respond_to(enum, :with_index) assert_respond_to(enum, :next) assert_respond_to(enum, :succ) assert_respond_to(enum, :rewind) end def test_instance_without_block enum = Prime.instance.each assert_respond_to(enum, :each) assert_kind_of(Enumerable, enum) assert_respond_to(enum, :with_index) assert_respond_to(enum, :next) assert_respond_to(enum, :succ) assert_respond_to(enum, :rewind) end def test_new exception = assert_raise(NoMethodError) { Prime.new } end def test_enumerator_succ enum = Prime.each assert_equal PRIMES[0, 50], 50.times.map{ enum.succ } assert_equal PRIMES[50, 50], 50.times.map{ enum.succ } enum.rewind assert_equal PRIMES[0, 100], 100.times.map{ enum.succ } end def test_enumerator_with_index enum = Prime.each last = -1 enum.with_index do |p,i| break if i >= 100 assert_equal last+1, i assert_equal PRIMES[i], p last = i end end def test_enumerator_with_index_with_offset enum = Prime.each last = 5-1 enum.with_index(5).each do |p,i| break if i >= 100+5 assert_equal last+1, i assert_equal PRIMES[i-5], p last = i end end def test_enumerator_with_object object = Object.new enum = Prime.each enum.with_object(object).each do |p, o| assert_equal object, o break end end def test_enumerator_size enum = Prime.each assert_equal Float::INFINITY, enum.size assert_equal Float::INFINITY, enum.with_object(nil).size assert_equal Float::INFINITY, enum.with_index(42).size end def test_default_instance_does_not_have_compatibility_methods assert_not_respond_to(Prime.instance, :succ) assert_not_respond_to(Prime.instance, :next) end def test_prime_each_basic_argument_checking assert_raise(ArgumentError) { Prime.prime?(1,2) } assert_raise(ArgumentError) { Prime.prime?(1.2) } end class TestInteger < Test::Unit::TestCase def test_prime_division pd = PRIMES.inject(&:*).prime_division assert_equal PRIMES.map{|p| [p, 1]}, pd pd = (-PRIMES.inject(&:*)).prime_division assert_equal [-1, *PRIMES].map{|p| [p, 1]}, pd end def test_from_prime_division assert_equal PRIMES.inject(&:*), Integer.from_prime_division(PRIMES.map{|p| [p,1]}) assert_equal(-PRIMES.inject(&:*), Integer.from_prime_division([[-1, 1]] + PRIMES.map{|p| [p,1]})) end def test_prime? # zero and unit assert_not_predicate(0, :prime?) assert_not_predicate(1, :prime?) # small primes assert_predicate(2, :prime?) assert_predicate(3, :prime?) # squared prime assert_not_predicate(4, :prime?) assert_not_predicate(9, :prime?) # mersenne numbers assert_predicate((2**31-1), :prime?) assert_not_predicate((2**32-1), :prime?) # fermat numbers assert_predicate((2**(2**4)+1), :prime?) assert_not_predicate((2**(2**5)+1), :prime?) # Euler! # large composite assert_not_predicate(((2**13-1) * (2**17-1)), :prime?) # factorial assert_not_predicate((2...100).inject(&:*), :prime?) # negative assert_not_predicate(-1, :prime?) assert_not_predicate(-2, :prime?) assert_not_predicate(-3, :prime?) assert_not_predicate(-4, :prime?) end end def test_eratosthenes_works_fine_after_timeout sieve = Prime::EratosthenesSieve.instance sieve.send(:initialize) begin # simulates that Timeout.timeout interrupts Prime::EratosthenesSieve#extend_table def sieve.Integer(n) n = super(n) sleep 10 if /compute_primes/ =~ caller.first return n end assert_raise(Timeout::Error) do Timeout.timeout(0.5) { Prime.each(7*37){} } end ensure class << sieve remove_method :Integer end end assert_not_include Prime.each(7*37).to_a, 7*37, "[ruby-dev:39465]" end end
arnab0073/idea
.rvm/src/ruby-2.3.0/gems/test-unit-3.1.5/lib/test/unit/test-suite-creator.rb
#-- # # Author:: <NAME> # Copyright:: # * Copyright (c) 2011 <NAME> <tt><<EMAIL>></tt> # License:: Ruby license. module Test module Unit class TestSuiteCreator # :nodoc: def initialize(test_case) @test_case = test_case end def create suite = TestSuite.new(@test_case.name, @test_case) collect_test_names.each do |test_name| data_sets = @test_case.find_attribute(test_name, :data) if data_sets data_sets.each do |data_set| data_set = data_set.call if data_set.respond_to?(:call) data_set.each do |label, data| append_test(suite, test_name) do |test| test.assign_test_data(label, data) end end end else append_test(suite, test_name) end end append_test(suite, "default_test") if suite.empty? suite end private def append_test(suite, test_name) test = @test_case.new(test_name) yield(test) if block_given? suite << test if test.valid? end def collect_test_names methods = @test_case.public_instance_methods(true) super_test_case = @test_case.superclass methods -= super_test_case.public_instance_methods(true) methods |= @test_case.public_instance_methods(false) method_names = methods.collect(&:to_s) test_names = method_names.find_all do |method_name| /\Atest./ =~ method_name or @test_case.find_attribute(method_name, :test) end __send__("sort_test_names_in_#{@test_case.test_order}_order", test_names) end def sort_test_names_in_alphabetic_order(test_names) test_names.sort end def sort_test_names_in_random_order(test_names) test_names.sort_by {rand(test_names.size)} end def sort_test_names_in_defined_order(test_names) added_method_names = @test_case.added_method_names test_names.sort do |test1, test2| test1_defined_order = added_method_names.index(test1) test2_defined_order = added_method_names.index(test2) if test1_defined_order and test2_defined_order test1_defined_order <=> test2_defined_order elsif test1_defined_order 1 elsif test2_defined_order -1 else test1 <=> test2 end end end end end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/sample/openssl/certstore.rb
require 'c_rehash' require 'crlstore' class CertStore include OpenSSL include X509 attr_reader :self_signed_ca attr_reader :other_ca attr_reader :ee attr_reader :crl attr_reader :request def initialize(certs_dir) @certs_dir = certs_dir @c_store = CHashDir.new(@certs_dir) @c_store.hash_dir(true) @crl_store = CrlStore.new(@c_store) @x509store = Store.new @self_signed_ca = @other_ca = @ee = @crl = nil # Uncomment this line to let OpenSSL to check CRL for each certs. # @x509store.flags = V_FLAG_CRL_CHECK | V_FLAG_CRL_CHECK_ALL add_path scan_certs end def generate_cert(filename) @c_store.load_pem_file(filename) end def verify(cert) error, crl_map = do_verify(cert) if error [[false, cert, crl_map[cert.subject], error]] else @x509store.chain.collect { |c| [true, c, crl_map[c.subject], nil] } end end def match_cert(cert1, cert2) (cert1.issuer.cmp(cert2.issuer) == 0) and cert1.serial == cert2.serial end def is_ca?(cert) case guess_cert_type(cert) when CERT_TYPE_SELF_SIGNED true when CERT_TYPE_OTHER true else false end end def scan_certs @self_signed_ca = [] @other_ca = [] @ee = [] @crl = [] @request = [] load_certs end private def add_path @x509store.add_path(@certs_dir) end def do_verify(cert) error_map = {} crl_map = {} result = @x509store.verify(cert) do |ok, ctx| cert = ctx.current_cert if ctx.current_crl crl_map[cert.subject] = true end if ok if !ctx.current_crl if crl = @crl_store.find_crl(cert) crl_map[cert.subject] = true if crl.revoked.find { |revoked| revoked.serial == cert.serial } ok = false error_string = 'certification revoked' end end end end error_map[cert.subject] = error_string if error_string ok end error = if result nil else error_map[cert.subject] || @x509store.error_string end return error, crl_map end def load_certs @c_store.get_certs.each do |certfile| cert = generate_cert(certfile) case guess_cert_type(cert) when CERT_TYPE_SELF_SIGNED @self_signed_ca << cert when CERT_TYPE_OTHER @other_ca << cert when CERT_TYPE_EE @ee << cert else raise "Unknown cert type." end end @c_store.get_crls.each do |crlfile| @crl << generate_cert(crlfile) end end CERT_TYPE_SELF_SIGNED = 0 CERT_TYPE_OTHER = 1 CERT_TYPE_EE = 2 def guess_cert_type(cert) ca = self_signed = is_cert_self_signed(cert) cert.extensions.each do |ext| # Ignores criticality of extensions. It's 'guess'ing. case ext.oid when 'basicConstraints' /CA:(TRUE|FALSE), pathlen:(\d+)/ =~ ext.value ca = ($1 == 'TRUE') unless ca when 'keyUsage' usage = ext.value.split(/\s*,\s*/) ca = usage.include?('Certificate Sign') unless ca when 'nsCertType' usage = ext.value.split(/\s*,\s*/) ca = usage.include?('SSL CA') unless ca end end if ca if self_signed CERT_TYPE_SELF_SIGNED else CERT_TYPE_OTHER end else CERT_TYPE_EE end end def is_cert_self_signed(cert) # cert.subject.cmp(cert.issuer) == 0 cert.subject.to_s == cert.issuer.to_s end end if $0 == __FILE__ c = CertStore.new("trust_certs") end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkmacpkg.rb
# # tkmacpkg.rb - load tk/macpkg.rb # require 'tk/macpkg'
arnab0073/idea
.rvm/src/ruby-2.3.0/test/excludes/TestException.rb
# frozen_string_literal: false reason = %[\ Because machine stack overflow can happen anywhere, even critical sections including external libraries, it is very neary impossible to recover from such situation. ] exclude /test_machine_stackoverflow/, reason exclude :test_machine_stackoverflow_by_define_method, reason
arnab0073/idea
.rvm/src/ruby-2.3.0/test/date/test_date_new.rb
<reponame>arnab0073/idea<filename>.rvm/src/ruby-2.3.0/test/date/test_date_new.rb # frozen_string_literal: false require 'test/unit' require 'date' class TestDateNew < Test::Unit::TestCase def test_jd d = Date.jd dt = DateTime.jd assert_equal([-4712, 1, 1], [d.year, d.mon, d.mday]) assert_equal([-4712, 1, 1], [dt.year, dt.mon, dt.mday]) assert_equal([0, 0, 0], [dt.hour, dt.min, dt.sec]) d2 = Date.jd dt2 = DateTime.jd assert_equal(d, d2) assert_equal(dt, dt2) d = Date.jd(0) assert_equal([-4712, 1, 1], [d.year, d.mon, d.mday]) d = DateTime.jd(0, 0,0,0, 0) assert_equal([-4712, 1, 1, 0, 0, 0, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.jd(0, 0,0,0, '+0900') assert_equal([-4712, 1, 1, 0, 0, 0, 9.to_r/24], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) end def test_jd__ex assert_raise(ArgumentError) do DateTime.jd(0, 23,59,60,0) end end def test_ordinal d = Date.ordinal dt = DateTime.ordinal assert_equal([-4712, 1, 1], [d.year, d.mon, d.mday]) assert_equal([-4712, 1, 1], [dt.year, dt.mon, dt.mday]) assert_equal([0, 0, 0], [dt.hour, dt.min, dt.sec]) d2 = Date.ordinal dt2 = DateTime.ordinal assert_equal(d, d2) assert_equal(dt, dt2) d = Date.ordinal(-4712,1) assert_equal([-4712, 1, 1], [d.year, d.mon, d.mday]) d = Date.ordinal(-4712,1.0) assert_equal([-4712, 1, 1], [d.year, d.mon, d.mday]) d = DateTime.ordinal(-4712,1, 0,0,0, 0) assert_equal([-4712, 1, 1, 0, 0, 0, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.ordinal(-4712,1, 0,0,0, '+0900') assert_equal([-4712, 1, 1, 0, 0, 0, 9.to_r/24], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) end def test_ordinal__neg d = Date.ordinal(-1,-1) assert_equal([-1, 365], [d.year, d.yday]) d = DateTime.ordinal(-1,-1, -1,-1,-1, 0) assert_equal([-1, 365, 23, 59, 59, 0], [d.year, d.yday, d.hour, d.min, d.sec, d.offset]) end def test_ordinal__ex assert_raise(ArgumentError) do Date.ordinal(2001,366) end assert_raise(ArgumentError) do DateTime.ordinal(2001,365, 23,59,60, 0) end end def test_civil d = Date.civil dt = DateTime.civil assert_equal([-4712, 1, 1], [d.year, d.mon, d.mday]) assert_equal([-4712, 1, 1], [dt.year, dt.mon, dt.mday]) assert_equal([0, 0, 0], [dt.hour, dt.min, dt.sec]) d2 = Date.civil dt2 = DateTime.civil assert_equal(d, d2) assert_equal(dt, dt2) d = Date.civil(-4712,1,1) assert_equal([-4712, 1, 1], [d.year, d.mon, d.mday]) d = Date.civil(-4712,1,1.0) assert_equal([-4712, 1, 1], [d.year, d.mon, d.mday]) d = DateTime.civil(-4712,1,1, 0,0,0, 0) assert_equal([-4712, 1, 1, 0, 0, 0, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.civil(-4712,1,1, 0,0,0, '+0900') assert_equal([-4712, 1, 1, 0, 0, 0, 9.to_r/24], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.civil(2001,2,3 + 1.to_r/2) assert_equal([2001, 2, 3, 12, 0, 0, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.civil(2001,2,3, 4 + 1.to_r/2) assert_equal([2001, 2, 3, 4, 30, 0, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.civil(2001,2,3, 4,5 + 1.to_r/2) assert_equal([2001, 2, 3, 4, 5, 30, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.civil(2001,2,3, 4,5,6 + 1.to_r/2) assert_equal([2001, 2, 3, 4, 5, 6, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) assert_equal(1.to_r/2, d.sec_fraction) end def test_civil__neg d = Date.civil(-1,-1,-1) assert_equal([-1, 12, 31], [d.year, d.mon, d.mday]) d = DateTime.civil(-1,-1,-1, -1,-1,-1, 0) assert_equal([-1, 12, 31, 23, 59, 59, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) end def test_civil__ex assert_raise(ArgumentError) do Date.civil(2001,2,29) end assert_raise(ArgumentError) do DateTime.civil(2001,2,28, 23,59,60, 0) end assert_raise(ArgumentError) do DateTime.civil(2001,2,28, 24,59,59, 0) end end def test_civil__reform d = Date.jd(Date::ENGLAND, Date::ENGLAND) dt = DateTime.jd(Date::ENGLAND, 0,0,0,0, Date::ENGLAND) assert_equal([1752, 9, 14], [d.year, d.mon, d.mday]) assert_equal([1752, 9, 14], [dt.year, dt.mon, dt.mday]) d -= 1 dt -= 1 assert_equal([1752, 9, 2], [d.year, d.mon, d.mday]) assert_equal([1752, 9, 2], [dt.year, dt.mon, dt.mday]) d = Date.jd(Date::ITALY, Date::ITALY) dt = DateTime.jd(Date::ITALY, 0,0,0,0, Date::ITALY) assert_equal([1582, 10, 15], [d.year, d.mon, d.mday]) assert_equal([1582, 10, 15], [dt.year, dt.mon, dt.mday]) d -= 1 dt -= 1 assert_equal([1582, 10, 4], [d.year, d.mon, d.mday]) assert_equal([1582, 10, 4], [dt.year, dt.mon, dt.mday]) end def test_commercial d = Date.commercial dt = DateTime.commercial assert_equal([-4712, 1, 1], [d.year, d.mon, d.mday]) assert_equal([-4712, 1, 1], [dt.year, dt.mon, dt.mday]) assert_equal([0, 0, 0], [dt.hour, dt.min, dt.sec]) d2 = Date.commercial dt2 = DateTime.commercial assert_equal(d, d2) assert_equal(dt, dt2) d = Date.commercial(1582,40,5) assert_equal([1582, 10, 15], [d.year, d.mon, d.mday]) d = Date.commercial(1582,40,5.0) assert_equal([1582, 10, 15], [d.year, d.mon, d.mday]) d = DateTime.commercial(1582,40,5, 0,0,0, 0) assert_equal([1582, 10, 15, 0, 0, 0, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.commercial(1582,40,5, 0,0,0, '+0900') assert_equal([1582, 10, 15, 0, 0, 0, 9.to_r/24], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) end def test_commercial__neg d = Date.commercial(1998,-1,-1) assert_equal([1999, 1, 3], [d.year, d.mon, d.mday]) d = DateTime.commercial(1998,-1,-1, -1,-1,-1, 0) assert_equal([1999, 1, 3, 23, 59, 59, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) end def test_commercial__ex assert_raise(ArgumentError) do Date.commercial(1997,53,1) end assert_raise(ArgumentError) do DateTime.commercial(1997,52,1, 23,59,60, 0) end end def test_weeknum skip unless Date.respond_to?(:weeknum, true) d = Date.__send__(:weeknum) dt = DateTime.__send__(:weeknum) assert_equal([-4712, 1, 1], [d.year, d.mon, d.mday]) assert_equal([-4712, 1, 1], [dt.year, dt.mon, dt.mday]) assert_equal([0, 0, 0], [dt.hour, dt.min, dt.sec]) d = Date.__send__(:weeknum, 2002,11,4, 0) assert_equal(2452355, d.jd) d = DateTime.__send__(:weeknum, 2002,11,4, 0, 11,22,33) assert_equal(2452355, d.jd) assert_equal([11,22,33], [d.hour, d.min, d.sec]) assert_raise(ArgumentError) do Date.__send__(:weeknum, 1999,53,0, 0) end assert_raise(ArgumentError) do Date.__send__(:weeknum, 1999,-53,-1, 0) end end def test_nth_kday skip unless Date.respond_to?(:nth_kday, true) d = Date.__send__(:nth_kday) dt = DateTime.__send__(:nth_kday) assert_equal([-4712, 1, 1], [d.year, d.mon, d.mday]) assert_equal([-4712, 1, 1], [dt.year, dt.mon, dt.mday]) assert_equal([0, 0, 0], [dt.hour, dt.min, dt.sec]) d = Date.__send__(:nth_kday, 1992,2, 5,6) assert_equal(2448682, d.jd) d = DateTime.__send__(:nth_kday, 1992,2, 5,6, 11,22,33) assert_equal(2448682, d.jd) assert_equal([11,22,33], [d.hour, d.min, d.sec]) assert_raise(ArgumentError) do Date.__send__(:nth_kday, 2006,5, 5,0) end assert_raise(ArgumentError) do Date.__send__(:nth_kday, 2006,5, -5,0) end end def test_today z = Time.now d = Date.today t = Time.now t2 = Time.utc(t.year, t.mon, t.mday) t3 = Time.utc(d.year, d.mon, d.mday) assert_in_delta(t2, t3, t - z + 2) assert_equal(false, DateTime.respond_to?(:today)) end def test_now assert_equal(false, Date.respond_to?(:now)) z = Time.now d = DateTime.now t = Time.now t2 = Time.local(d.year, d.mon, d.mday, d.hour, d.min, d.sec) assert_in_delta(t, t2, t - z + 2) end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/bootstraptest/test_autoload.rb
<filename>.rvm/src/ruby-1.9.3-p551/bootstraptest/test_autoload.rb assert_equal 'ok', %q{ File.unlink('zzz.rb') if File.file?('zzz.rb') instance_eval do autoload :ZZZ, './zzz.rb' begin ZZZ rescue LoadError :ok end end }, '[ruby-dev:43816]' assert_equal 'ok', %q{ open('zzz.rb', 'w') {|f| f.puts '' } instance_eval do autoload :ZZZ, './zzz.rb' begin ZZZ rescue NameError :ok end end }, '[ruby-dev:43816]' assert_equal 'ok', %q{ open('zzz.rb', 'w') {|f| f.puts 'class ZZZ; def self.ok;:ok;end;end'} instance_eval do autoload :ZZZ, './zzz.rb' ZZZ.ok end }, '[ruby-dev:43816]' assert_equal 'ok', %q{ open("zzz.rb", "w") {|f| f.puts "class ZZZ; def self.ok;:ok;end;end"} autoload :ZZZ, "./zzz.rb" ZZZ.ok } assert_equal 'ok', %q{ open("zzz.rb", "w") {|f| f.puts "class ZZZ; def self.ok;:ok;end;end"} autoload :ZZZ, "./zzz.rb" require "./zzz.rb" ZZZ.ok } assert_equal 'ok', %q{ open("zzz.rb", "w") {|f| f.puts "class ZZZ; def self.ok;:ok;end;end"} autoload :ZZZ, "./zzz.rb" proc{$SAFE=4; ZZZ.ok}.call } assert_equal 'ok', %q{ open("zzz.rb", "w") {|f| f.puts "class ZZZ; def self.ok;:ok;end;end"} autoload :ZZZ, "./zzz.rb" require "./zzz.rb" proc{$SAFE=4; ZZZ.ok}.call } assert_equal 'ok', %q{ open("zzz.rb", "w") {|f| f.puts "class ZZZ; def hoge;:ok;end;end"} autoload :ZZZ, File.join(Dir.pwd, 'zzz.rb') module M; end Thread.new{M.instance_eval('$SAFE=4; ZZZ.new.hoge')}.value } assert_equal 'ok', %q{ open("zzz.rb", "w") {|f| f.puts "class ZZZ; def hoge;:ok;end;end"} autoload :ZZZ, File.join(Dir.pwd, 'zzz.rb') module M; end Thread.new{$SAFE=4; M.instance_eval('ZZZ.new.hoge')}.value } assert_equal 'ok', %q{ open("zzz.rb", "w") {|f| f.puts "class ZZZ; def hoge;:ok;end;end"} autoload :ZZZ, File.join(Dir.pwd, 'zzz.rb') Thread.new{$SAFE=4; eval('ZZZ.new.hoge')}.value } assert_equal 'ok', %q{ open("zzz.rb", "w") {|f| f.puts "class ZZZ; def hoge;:ok;end;end"} autoload :ZZZ, File.join(Dir.pwd, 'zzz.rb') module M; end Thread.new{eval('$SAFE=4; ZZZ.new.hoge')}.value } assert_equal 'okok', %q{ open("zzz.rb", "w") {|f| f.puts "class ZZZ; def self.ok;:ok;end;end"} autoload :ZZZ, "./zzz.rb" t1 = Thread.new {ZZZ.ok} t2 = Thread.new {ZZZ.ok} [t1.value, t2.value].join } assert_finish 5, %q{ autoload :ZZZ, File.expand_path(__FILE__) begin ZZZ rescue NameError end }, '[ruby-core:21696]' assert_equal 'A::C', %q{ open("zzz.rb", "w") {} class A autoload :C, "./zzz" class C end C end }
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/iwidgets/sample/feedback.rb
<reponame>arnab0073/idea<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/iwidgets/sample/feedback.rb #!/usr/bin/env ruby require 'tk' require 'tkextlib/iwidgets' Tk::Iwidgets::Feedback.new(:labeltext=>'Status', :steps=>20){|fb| pack(:padx=>10, :pady=>10, :fill=>:both, :expand=>true) TkTimer.new(500, 20, proc{fb.step}).start(2500) } Tk.mainloop
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/examples/fork.rb
<gh_stars>1000+ # :stopdoc: # # Because of the global interpreter lock, Kernel#fork is the best way # to achieve true concurrency in Ruby scripts. However, there are peculiarities # when using fork and passing file descriptors between process. These # peculiarities affect the logging framework. # # In short, always reopen file descriptors in the child process after fork has # been called. The RollingFile appender uses flock to safely coordinate the # rolling of the log file when multiple processes are writing to the same # file. If the file descriptor is opened in the parent and multiple children # are forked, then each child will use the same file descriptor lock; when one # child locks the file any other child will also have the lock. This creates a # race condition in the rolling code. The solution is to reopen the file to # obtain a new file descriptor in each of the children. # require 'logging' log = Logging.logger['example'] log.add_appenders( Logging.appenders.rolling_file('roller.log', :age => 'daily') ) log.level = :debug # Create four child processes and reopen the "roller.log" file descriptor in # each child. Now log rolling will work safely. 4.times do fork { Logging.reopen log.info "This is child process #{Process.pid}" } end log.info "This is the parent process #{Process.pid}" # :startdoc:
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/dl/win32/extconf.rb
if compiled?('dl') and $mswin||$bccwin||$mingw||$cygwin create_makefile('win32') end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tk/optionobj.rb
# # tk/optionobj.rb : control options for a group of widgets # # NOTE: If you want to use key-only option (no value), # use Tk::None for the value of the key-only option. # # e.g. hash_kv({'aaa'=>1, 'bbb'=>Tk::None, 'ccc'=>3}) # => ["-aaa", 1, "-bbb", "-ccc", 3] # require 'tk' module Tk class OptionObj < Hash include TkUtil def initialize(hash = nil) super() @observ = [] update_without_notify(_symbolkey2str(hash)) if hash end def observ_info @observ.dup end def observs @observ.collect{|win| if win.kind_of?(Array) win[0] else win end } end def _remove_win(win) if win.kind_of?(Array) widget, method = win @observ.delete_if{|x| if x.kind_of?(Array) x[0] == widget else x == widget end } else @observ.delete_if{|x| if x.kind_of?(Array) x[0] == win else x == win end } end end private :_remove_win def assign(*wins) # win := # widget #==> call widget.configure(hash) # [widget] #==> call widget.configure(hash) # [widget, nil, {src=>target, ... }] # #==> call widget.configure(hash) # with converting hash-key # [widget, method] #==> call widget.method(hash) # [widget, method, {src=>target, ... }] # #==> call widget.method(hash) # with converting hash-key # [widget [receiver, method, arg, ... ]] # #==> call receiver.method(arg, ... , hash) # [widget [receiver, method, arg, ... ], {src=>target, ... }] # #==> call receiver.method(arg, ... , hash) # with onverting hash-key # # src := option_name_on_optobj # # target := # nil #==> not use the src # option_name_on_target_widget # [ option_name_on_target_widget, ... ] # #==> set all of them # wins.each{|win| _remove_win(win) @observ << win notify(win) } self end def unassign(*wins) wins.each{|win| _remove_win(win) } self end def notify(target = nil) if target targets = [target] elsif @observ.empty? return self else targets = @observ.dup end return self if empty? org_hash = _symbolkey2str(self) targets.each{|win| widget = receiver = win hash = org_hash begin if win.kind_of?(Array) widget, method, conv_tbl = win receiver = widget if conv_tbl hash = {} org_hash.each{|key, val| key = conv_tbl[key] if conv_tbl.key?(key) next unless key if key.kind_of?(Array) key.each{|k| hash[k] = val} else hash[key] = val end } end if method.kind_of?(Array) receiver, method, *args = method receiver.__send__(method, *(args << hash)) elsif method widget.__send__(method, hash) else widget.configure(hash) end else widget.configure(self) end rescue => e if ( ( widget.kind_of?(TkObject) \ && widget.respond_to?('exist?') \ && ! receiver.exist? ) \ || ( receiver.kind_of?(TkObject) \ && receiver.respond_to?('exist?') \ && ! receiver.exist? ) ) @observ.delete(win) else fail e end end } self end alias apply notify def +(hash) unless hash.kind_of?(Hash) fail ArgumentError, "expect a Hash" end new_obj = self.dup new_obj.update_without_notify(_symbolkey2str(hash)) new_obj end alias update_without_notify update def update(hash) update_without_notify(_symbolkey2str(hash)) notify end def configure(key, value=nil) if key.kind_of?(Hash) update(key) else store(key,value) end end def [](key) super(key.to_s) end alias cget [] def store(key, val) key = key.to_s super(key, val) notify end def []=(key, val) store(key,val) end def replace(hash) super(_symbolkey2str(hash)) notify end def default(opt) fail RuntimeError, "unknown option `#{opt}'" end private :default undef :default= end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/rubyntlm-0.6.0/lib/net/ntlm/encode_util.rb
<filename>.rvm/gems/ruby-2.3.0/gems/rubyntlm-0.6.0/lib/net/ntlm/encode_util.rb<gh_stars>0 module Net module NTLM class EncodeUtil if RUBY_VERSION == "1.8.7" require "kconv" # Decode a UTF16 string to a ASCII string # @param [String] str The string to convert def self.decode_utf16le(str) Kconv.kconv(swap16(str), Kconv::ASCII, Kconv::UTF16) end # Encodes a ASCII string to a UTF16 string # @param [String] str The string to convert def self.encode_utf16le(str) swap16(Kconv.kconv(str, Kconv::UTF16, Kconv::ASCII)) end # Taggle the strings endianness between big/little and little/big # @param [String] str The string to swap the endianness on def self.swap16(str) str.unpack("v*").pack("n*") end else # Use native 1.9 string encoding functions # Decode a UTF16 string to a ASCII string # @param [String] str The string to convert def self.decode_utf16le(str) str.force_encoding(Encoding::UTF_16LE) str.encode(Encoding::UTF_8, Encoding::UTF_16LE).force_encoding('UTF-8') end # Encodes a ASCII string to a UTF16 string # @param [String] str The string to convert # @note This implementation may seem stupid but the problem is that UTF16-LE and UTF-8 are incompatiable # encodings. This library uses string contatination to build the packet bytes. The end result is that # you can either marshal the encodings elsewhere of simply know that each time you call encode_utf16le # the function will convert the string bytes to UTF-16LE and note the encoding as UTF-8 so that byte # concatination works seamlessly. def self.encode_utf16le(str) str = str.force_encoding('UTF-8') if [::Encoding::ASCII_8BIT,::Encoding::US_ASCII].include?(str.encoding) str.dup.force_encoding('UTF-8').encode(Encoding::UTF_16LE, Encoding::UTF_8).force_encoding('UTF-8') end end end end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/demos-en/image1.rb
## image1.rb # # This demonstration script displays two image widgets. # # two image widgets demo (called by 'widget') # # toplevel widget if defined?($image1_demo) && $image1_demo $image1_demo.destroy $image1_demo = nil end # demo toplevel widget $image1_demo = TkToplevel.new {|w| title('Image Demonstration #1') iconname("Image1") positionWindow(w) } base_frame = TkFrame.new($image1_demo).pack(:fill=>:both, :expand=>true) # label msg = TkLabel.new(base_frame) { font $font wraplength '4i' justify 'left' text "This demonstration displays two images, each in a separate label widget." } msg.pack('side'=>'top') # frame TkFrame.new(base_frame) {|frame| TkButton.new(frame) { text 'Dismiss' command proc{ tmppath = $image1_demo $image1_demo = nil tmppath.destroy } }.pack('side'=>'left', 'expand'=>'yes') TkButton.new(frame) { text 'Show Code' command proc{showCode 'image1'} }.pack('side'=>'left', 'expand'=>'yes') }.pack('side'=>'bottom', 'fill'=>'x', 'pady'=>'2m') # image image1a = \ TkPhotoImage.new('file'=>[$demo_dir,'..', 'images','earth.gif'].join(File::Separator)) image1b = \ TkPhotoImage.new('file'=>[$demo_dir,'..', 'images','earthris.gif'].join(File::Separator)) # label #[ TkLabel.new(base_frame, 'image'=>image1a, 'bd'=>1, 'relief'=>'sunken'), # TkLabel.new(base_frame, 'image'=>image1b, 'bd'=>1, 'relief'=>'sunken') #].each{|w| w.pack('side'=>'top', 'padx'=>'.5m', 'pady'=>'.5m')} [ Tk::Label.new(base_frame, 'image'=>image1a, 'bd'=>1, 'relief'=>'sunken'), Tk::Label.new(base_frame, 'image'=>image1b, 'bd'=>1, 'relief'=>'sunken') ].each{|w| w.pack('side'=>'top', 'padx'=>'.5m', 'pady'=>'.5m')}
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/lib/ohai/plugins/windows/cpu.rb
<filename>.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/lib/ohai/plugins/windows/cpu.rb<gh_stars>0 # # Author:: <NAME> <<EMAIL>> # Copyright:: Copyright (c) 2010 VMware, 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' provides "cpu" cpuinfo = Mash.new cpu_number = 0 index = 0 WMI::Win32_Processor.find(:all).each do |processor| # # On Windows Server 2003 R2 (i.e. 5.2.*), numberofcores property # doesn't exist on the Win32_Processor class unless the user has # patched their system with: # http://support.microsoft.com/kb/932370 # # We're returning nil for cpu["cores"] and cpu["count"] # when we don't see numberofcores property # number_of_cores = nil begin number_of_cores = processor.numberofcores cpu_number += number_of_cores rescue NoMethodError => e Ohai::Log.info("Can not find numberofcores property on Win32_Processor. Consider applying this patch: http://support.microsoft.com/kb/932370") end current_cpu = index.to_s index += 1 cpuinfo[current_cpu] = Mash.new cpuinfo[current_cpu]["vendor_id"] = processor.manufacturer cpuinfo[current_cpu]["family"] = processor.family.to_s cpuinfo[current_cpu]["model"] = processor.revision.to_s cpuinfo[current_cpu]["stepping"] = processor.stepping cpuinfo[current_cpu]["physical_id"] = processor.deviceid #cpuinfo[current_cpu]["core_id"] = XXX cpuinfo[current_cpu]["cores"] = number_of_cores cpuinfo[current_cpu]["model_name"] = processor.description cpuinfo[current_cpu]["mhz"] = processor.maxclockspeed.to_s cpuinfo[current_cpu]["cache_size"] = "#{processor.l2cachesize} KB" #cpuinfo[current_cpu]["flags"] = XXX end cpu cpuinfo cpu[:total] = (cpu_number == 0) ? nil : cpu_number cpu[:real] = index
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/gssapi-1.2.0/examples/gss_iov_client.rb
#!/usr/bin/env ruby $: << '../lib' $: << '.' #require 'gssapi/heimdal' require 'gssapi' require 'gss_iov_helpers' require 'base64' require 'socket' class GssIovClient include GssIOVHelpers def initialize @host = 'example.org' @service = 'host' @sock = TCPSocket.new(@host, 8082) @gss = GSSAPI::Simple.new(@host, @service) end def run handshake begin print "> " msg = STDIN.gets.chomp emsg = iov_encrypt(msg) @sock.write("#{emsg.last}\n") end while msg != 'exit' @sock.close end private def handshake tok = @gss.init_context stok = Base64.strict_encode64(tok) @sock.write("#{stok}\n") # send initial token stok = @sock.gets.chomp # get back continuation token ctx = @gss.init_context(Base64.strict_decode64(stok.chomp)) # complete security context puts "Connection #{(ctx ? 'succeeded' : 'failed')}" end # Encrypt message def msg_enc(msg) emsg = @gss.wrap_message(msg) Base64.strict_encode64(emsg) end end cli = GssIovClient.new cli.run
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/spec/unit/plugins/solaris2/virtualization_spec.rb
# # Author:: <NAME> (<<EMAIL>>) # Copyright:: Copyright (c) 2009 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper.rb') describe Ohai::System, "Solaris virtualization platform" do before(:each) do @ohai = Ohai::System.new @ohai[:os] = "solaris2" @ohai.stub!(:require_plugin).and_return(true) @ohai.extend(SimpleFromFile) # default to all requested Files not existing File.stub!(:exists?).with("/usr/sbin/psrinfo").and_return(false) File.stub!(:exists?).with("/usr/sbin/smbios").and_return(false) File.stub!(:exists?).with("/usr/sbin/zoneadm").and_return(false) end describe "when we are checking for kvm" do before(:each) do File.should_receive(:exists?).with("/usr/sbin/psrinfo").and_return(true) @stdin = mock("STDIN", { :close => true }) @pid = 10 @stderr = mock("STDERR") @stdout = mock("STDOUT") @status = 0 end it "should run psrinfo -pv" do @ohai.should_receive(:popen4).with("/usr/sbin/psrinfo -pv").and_return(true) @ohai._require_plugin("solaris2::virtualization") end it "Should set kvm guest if psrinfo -pv contains QEMU Virtual CPU" do @stdout.stub!(:read).and_return("QEMU Virtual CPU") @ohai.stub!(:popen4).with("/usr/sbin/psrinfo -pv").and_yield(@pid, @stdin, @stdout, @stderr).and_return(@status) @ohai._require_plugin("solaris2::virtualization") @ohai[:virtualization][:system].should == "kvm" @ohai[:virtualization][:role].should == "guest" end it "should not set virtualization if kvm isn't there" do @ohai.should_receive(:popen4).with("/usr/sbin/psrinfo -pv").and_return(true) @ohai._require_plugin("solaris2::virtualization") @ohai[:virtualization].should == {} end end describe "when we are parsing smbios" do before(:each) do File.should_receive(:exists?).with("/usr/sbin/smbios").and_return(true) @stdin = mock("STDIN", { :close => true }) @pid = 20 @stderr = mock("STDERR") @stdout = mock("STDOUT") @status = 0 end it "should run smbios" do @ohai.should_receive(:popen4).with("/usr/sbin/smbios").and_return(true) @ohai._require_plugin("solaris2::virtualization") end it "should set virtualpc guest if smbios detects Microsoft Virtual Machine" do ms_vpc_smbios=<<-MSVPC ID SIZE TYPE 1 72 SMB_TYPE_SYSTEM (system information) Manufacturer: Microsoft Corporation Product: Virtual Machine Version: VS2005R2 Serial Number: 1688-7189-5337-7903-2297-1012-52 UUID: D29974A4-BE51-044C-BDC6-EFBC4B87A8E9 Wake-Up Event: 0x6 (power switch) MSVPC @stdout.stub!(:read).and_return(ms_vpc_smbios) @ohai.stub!(:popen4).with("/usr/sbin/smbios").and_yield(@pid, @stdin, @stdout, @stderr).and_return(@status) @ohai._require_plugin("solaris2::virtualization") @ohai[:virtualization][:system].should == "virtualpc" @ohai[:virtualization][:role].should == "guest" end it "should set vmware guest if smbios detects VMware Virtual Platform" do vmware_smbios=<<-VMWARE ID SIZE TYPE 1 72 SMB_TYPE_SYSTEM (system information) Manufacturer: VMware, Inc. Product: VMware Virtual Platform Version: None Serial Number: VMware-50 3f f7 14 42 d1 f1 da-3b 46 27 d0 29 b4 74 1d UUID: a86cc405-e1b9-447b-ad05-6f8db39d876a Wake-Up Event: 0x6 (power switch) VMWARE @stdout.stub!(:read).and_return(vmware_smbios) @ohai.stub!(:popen4).with("/usr/sbin/smbios").and_yield(@pid, @stdin, @stdout, @stderr).and_return(@status) @ohai._require_plugin("solaris2::virtualization") @ohai[:virtualization][:system].should == "vmware" @ohai[:virtualization][:role].should == "guest" end it "should run smbios and not set virtualization if nothing is detected" do @ohai.should_receive(:popen4).with("/usr/sbin/smbios").and_return(true) @ohai._require_plugin("solaris2::virtualization") @ohai[:virtualization].should == {} end end it "should not set virtualization if no tests match" do @ohai._require_plugin("solaris2::virtualization") @ohai[:virtualization].should == {} end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/test/test_proxy.rb
require File.expand_path('../setup', __FILE__) module TestLogging class TestProxy < Test::Unit::TestCase include LoggingTestCase def setup super ::Logging.init @appender = Logging.appenders.string_io('test_appender') logger = Logging.logger[Array] logger.level = :debug logger.appenders = @appender end def test_initialize ary = [] proxy = Logging::Proxy.new ary assert_instance_of Array, proxy proxy.concat [1,2,3] assert_equal 3, proxy.length assert_equal [1,2,3], ary end def test_method_logging proxy = Logging::Proxy.new [] assert_equal 0, proxy.length assert_equal "Array#length()\n", @appender.readline proxy.concat [1,2,3] assert_equal "Array#concat(#{[1,2,3].inspect})\n", @appender.readline proxy = Logging::Proxy.new Array proxy.name assert_equal "Array.name()\n", @appender.readline proxy.new 0 assert_equal "Array.new(0)\n", @appender.readline end def test_custom_method_logging proxy = Logging::Proxy.new([]) { |name, *args, &block| @logger << "#@leader#{name}(#{args.inspect[1..-2]})" rv = @object.__send__(name, *args, &block) @logger << " => #{rv.inspect}\n" rv } @appender.clear assert_equal 0, proxy.length assert_equal "Array#length() => 0\n", @appender.readline proxy.concat [1,2,3] assert_equal "Array#concat(#{[1,2,3].inspect}) => #{[1,2,3].inspect}\n", @appender.readline proxy.concat [4,5,6] assert_equal "Array#concat(#{[4,5,6].inspect}) => #{[1,2,3,4,5,6].inspect}\n", @appender.readline end def test_error_when_proxying_nil assert_raises(ArgumentError, 'Cannot proxy nil') { Logging::Proxy.new nil } end end # TestProxy end # TestLogging
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkafter.rb
# # tkafter.rb - load tk/after.rb # require 'tk/timer'
arnab0073/idea
.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/gem-wrappers-1.2.7/test/gem-wrappers/fakes.rb
<reponame>arnab0073/idea module GemWrappers class FakeInstaller def initialize @executables = [] end def install(executable) @executables << executable end def uninstall(executable) @executables.delete(executable) end def executables @executables end def ensure @ensure = true end def ensure? @ensure end def wrappers_path "/path/to/wrappers" end end class FakeEnvironment def ensure @ensure = true end def ensure? @ensure end def file_name "/path/to/environment" end end class Fake def initialize @executables = [] end def install(executables) @executables += executables end def uninstall(executables) @executables -= executables end def executables @executables end def environment_file "/path/to/environment" end def wrappers_path "/path/to/wrappers" end end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/bootstraptest/test_class.rb
# class assert_equal 'true', %q( class C; end Object.const_defined?(:C) ) assert_equal 'Class', %q( class C; end C.class ) assert_equal 'C', %q( class C; end C.name ) assert_equal 'C', %q( class C; end C.new.class ) assert_equal 'C', %q( class C; end C.new.class.name ) assert_equal 'Class', %q( class C; end C.new.class.class ) # inherited class assert_equal 'true', %q( class A; end class C < A; end Object.const_defined?(:C) ) assert_equal 'Class', %q( class A; end class C < A; end C.class ) assert_equal 'C', %q( class A; end class C < A; end C.name ) assert_equal 'C', %q( class A; end class C < A; end C.new.class ) assert_equal 'C', %q( class A; end class C < A; end C.new.class.name ) assert_equal 'Class', %q( class A; end class C < A; end C.new.class.class ) # module assert_equal 'true', %q( module M; end Object.const_defined?(:M) ) assert_equal 'Module', %q( module M; end M.class ) assert_equal 'M', %q( module M; end M.name ) assert_equal 'C', %q( module M; end class C; include M; end C.new.class ) # nested class assert_equal 'A::B', %q( class A; end class A::B; end A::B ) assert_equal 'A::B', %q( class A; end class A::B; end A::B.name ) assert_equal 'A::B', %q( class A; end class A::B; end A::B.new.class ) assert_equal 'Class', %q( class A; end class A::B; end A::B.new.class.class ) assert_equal 'A::B::C', %q( class A; end class A::B; end class A::B::C; end A::B::C ) assert_equal 'A::B::C', %q( class A; end class A::B; end class A::B::C; end A::B::C.name ) assert_equal 'Class', %q( class A; end class A::B; end class A::B::C; end A::B::C.class ) assert_equal 'A::B::C', %q( class A; end class A::B; end class A::B::C; end A::B::C.new.class ) assert_equal 'Class', %q( class A; end class A::B; end class A::B::C; end A::B::C.new.class.class ) assert_equal 'A::B2', %q( class A; end class A::B; end class A::B2 < A::B; end A::B2 ) assert_equal 'Class', %q( class A; end class A::B; end class A::B2 < A::B; end A::B2.class ) # reopen assert_equal 'true', %q( class C; end; c1 = ::C class C; end; c2 = ::C c1.equal?(c2) ) assert_equal '1', %q( class C; end class A; end begin class C < A; end; rescue TypeError; 1 end ) assert_equal '1', %q( class C; end begin module C; end; rescue TypeError; 1 end ) assert_equal '1', %q( C = 1 # [yarv-dev:782] begin class C; end; rescue TypeError; 1 end ) assert_equal '1', %q( C = 1 # [yarv-dev:800] begin module C; end; rescue TypeError; 1 end ) # colon2, colon3 assert_equal '1', %q( class A; end; A::C = 1; A::C ) assert_equal '1', %q( A = 7; begin A::C = 7; rescue TypeError; 1 end ) assert_equal '1', %q( begin 7::C = 7; rescue TypeError; 1 end ) assert_equal 'C', %q( class A; class ::C; end end; C ) assert_equal 'Class', %q( class A; class ::C; end end; C.class ) assert_equal 'OK', %q( class A; ::C = "OK"; end; C ) assert_equal 'String', %q( class A; ::C = "OK"; end; C.class ) # class/module dup assert_equal 'Class', %q( class C; end; C.dup.class ) assert_equal 'Module', %q( module M; end; M.dup.class ) assert_equal "ok", %q{ module Foo end begin def foo(&b) Foo.module_eval &b end foo{ def bar end } bar() rescue NameError :ok end }, '[ruby-core:14378]' assert_equal '3', %q{ $i = 0 class C def self.const_missing *args $i+=1 end end 3.times{ C::FOO } $i } assert_match /::C\z/, %q{ c = nil Module.new{|m| c = class m::C; name; end} c }, '[ruby-dev:38456]' assert_normal_exit %q{ s = Symbol.dup class << s end s.allocate.to_s }, '[ruby-core:30843]'
blueberrystream/capistrano-locally
spec/spec_helper.rb
$LOAD_PATH.unshift File.expand_path('../lib', __dir__) require 'capistrano' require 'singleton' require 'sshkit' require 'capistrano/locally'
blueberrystream/capistrano-locally
spec/capistrano/locally_spec.rb
require 'spec_helper' module Capistrano class DummyDSL include DSL end end describe Capistrano::Locally do it 'has a version number' do expect(Capistrano::Locally::VERSION).not_to be nil end let(:dsl) { Capistrano::DummyDSL.new } let(:servers) do [::Capistrano::Configuration::Server.new("server1"), ::Capistrano::Configuration::Server.new("server2"), ::Capistrano::Configuration::Server.new("localhost"), ::Capistrano::Configuration::Server.new("server3"), ::Capistrano::Configuration::Server.new("127.0.0.1"), ::Capistrano::Configuration::Server.new("server10")] end let(:locally_servers) do servers.reject do |server| server.hostname == 'localhost' end end it 'keeps the same method parameters with the original' do original = dsl.method(:original_on) override = dsl.method(:on) expect(override.parameters).to eq original.parameters end context '#on' do let(:opts) { {} } let(:block) { proc { true } } it 'calls the original "#on" with arguments excluding "localhost" server' do allow(dsl).to receive(:original_on).with(locally_servers, opts, &block) dsl.on(servers, opts, &block) end end end
blueberrystream/capistrano-locally
capistrano-locally.gemspec
<filename>capistrano-locally.gemspec<gh_stars>0 # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'capistrano/locally/version' Gem::Specification.new do |spec| spec.name = "capistrano-locally" spec.version = Capistrano::Locally::VERSION spec.authors = ["<NAME>"] spec.email = ["<EMAIL>"] spec.summary = %q{Capistrano plugin to simplify "localhost" deployment.} spec.description = <<-EOS Capistrano plugin to simplify "localhost" deployment. Capistrano can deploy the source to any hosts including localhost via SSH (`SSHKit::Backend::Netssh`). But when limiting to some simple case that deployment to localhost, SSH isn't sometimes necessary. A `capistrano-locally` deploys without SSH only when a target host named "localhost". EOS spec.homepage = "https://github.com/komazarari/capistrano-locally" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_dependency "capistrano", "~> 3.0" spec.add_development_dependency "bundler" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rspec" spec.add_development_dependency "rspec_junit_formatter" end
blueberrystream/capistrano-locally
lib/capistrano/locally/version.rb
module Capistrano module Locally VERSION = "0.2.7" end end
1debit/plaid-ruby
lib/plaidio/customer.rb
<reponame>1debit/plaid-ruby<filename>lib/plaidio/customer.rb<gh_stars>0 module Plaidio # This is used when a customer needs to be defined by the plaid access token. # Abstracting as a class makes it easier since we wont have to redefine the access_token over and over. class Customer BASE_URL = 'https://tartan.plaid.com' # This initializes our instance variables, and sets up a new Customer class. def initialize Plaidio::Configure::KEYS.each do |key| instance_variable_set(:"@#{key}", Plaidio.instance_variable_get(:"@#{key}")) end end def mfa_step(access_token,code) @mfa = code post("/connect/step", access_token, mfa: @mfa) return parse_response(@response,1) end def mfa_auth_step(access_token,code) @mfa = code post("/auth/step", access_token, mfa: @mfa) return parse_response(@response,1) end def get_transactions(access_token) get('/connect', access_token) return parse_response(@response,2) end def delete_account(access_token) delete('/connect', access_token) return parse_response(@response,3) end def auth(access_token) get('/auth', access_token) return parse_response(@response,4) end def info(access_token) get('/info', access_token) return parse_response(@response,5) end def upgrade(access_token,level) post('/upgrade', access_token, {upgrade_to: level, login: true}) return parse_response(@response, 4) end protected def parse_response(response,method) case method when 1 case response.code when 200 @parsed_response = Hash.new @parsed_response[:code] = response.code response = JSON.parse(response) @parsed_response[:access_token] = response["access_token"] @parsed_response[:accounts] = response["accounts"] @parsed_response[:transactions] = response["transactions"] return @parsed_response else @parsed_response = Hash.new @parsed_response[:code] = response.code @parsed_response[:message] = response return @parsed_response end when 2 case response.code when 200 @parsed_response = Hash.new @parsed_response[:code] = response.code response = JSON.parse(response) @parsed_response[:transactions] = response["transactions"] return @parsed_response else @parsed_response = Hash.new @parsed_response[:code] = response.code @parsed_response[:message] = response return @parsed_response end when 3 case response.code when 200 @parsed_response = Hash.new @parsed_response[:code] = response.code response = JSON.parse(response) @parsed_response[:message] = response return @parsed_response else @parsed_response = Hash.new @parsed_response[:code] = response.code @parsed_response[:message] = response return @parsed_response end when 4 case response.code when 200 @parsed_response = Hash.new @parsed_response[:code] = response.code response = JSON.parse(response) @parsed_response[:accounts] = response["accounts"] return @parsed_response else @parsed_response = Hash.new @parsed_response[:code] = response.code @parsed_response[:message] = response return @parsed_response end when 5 case response.code when 200 @parsed_response = Hash.new @parsed_response[:code] = response.code response = JSON.parse(response) @parsed_response[:accounts] = response["accounts"] @parsed_response[:info] = response['info'] return @parsed_response else @parsed_response = Hash.new @parsed_response[:code] = response.code @parsed_response[:message] = response return @parsed_response end end end private def get(path,access_token,options={}) url = BASE_URL + path params = {:client_id => self.instance_variable_get(:'@customer_id'), :secret => self.instance_variable_get(:'@secret'), :access_token => access_token} @response = RestClient.get(url,:params =>params) return @response end def post(path,access_token,options={}) url = BASE_URL + path params = { :client_id => self.instance_variable_get(:'@customer_id') ,:secret => self.instance_variable_get(:'@secret'), :access_token => access_token, :mfa => @mfa } params.merge!(options) @response = RestClient.post url, params return @response end def delete(path,access_token,options={}) url = BASE_URL + path @response = RestClient.delete(url,:params => {:client_id => self.instance_variable_get(:'@customer_id'), :secret => self.instance_variable_get(:'@secret'), :access_token => access_token}) return @response end end end
1debit/plaid-ruby
lib/plaidio.rb
<reponame>1debit/plaid-ruby require 'plaidio/config' require 'plaidio/call' require 'plaidio/customer' require 'rest_client' module Plaidio class << self include Plaidio::Configure # Defined when a user exists with a unique access_token. Ex: Plaidio.customer.get_transactions def customer @customer = Plaidio::Customer.new end # Defined for generic calls without access_tokens required. Ex: Plaidio.call.add_accounts(username,password,type) def call @call = Plaidio::Call.new end end end
1debit/plaid-ruby
plaidio.gemspec
<filename>plaidio.gemspec Gem::Specification.new do |s| s.name = 'plaidio' s.version = '0.1.6' s.date = '2015-07-30' s.summary = "Plaid.io api gem" s.description = "A simple to use ruby wrapper for Plaid.io API." s.authors = ["<NAME>", "<NAME>"] s.email = '<EMAIL>' s.files = ["lib/plaidio.rb", "lib/plaidio/config.rb","lib/plaidio/call.rb","lib/plaidio/customer.rb"] s.homepage = 'https://github.com/j4ustin/plaidio' s.license = 'MIT' s.add_runtime_dependency "rest-client" s.add_runtime_dependency "json" s.add_development_dependency "rake" s.add_development_dependency "rspec" end
1debit/plaid-ruby
lib/plaidio/call.rb
<gh_stars>0 module Plaidio class Call BASE_URL = 'https://tartan.plaid.com/' # This initializes our instance variables, and sets up a new Customer class. def initialize Plaidio::Configure::KEYS.each do |key| instance_variable_set(:"@#{key}", Plaidio.instance_variable_get(:"@#{key}")) end end def add_account(type,username,password,email) post('/connect',type,username,password,email) return parse_response(@response) end def add_ach_account(type,username,password,email) post('/auth',type,username,password,email) return parse_response(@response) end def get_place(id) get('/entity',id) return parse_place(@response) end def exchange_token(public_token) post_to_exchange(public_token) return parse_exchange(@response) end protected def parse_exchange(response) case response.code when 200 @parsed_response = Hash.new @parsed_response[:code] = response.code response = JSON.parse(response) @parsed_response[:access_token] = response["access_token"] else @parsed_response = Hash.new @parsed_response[:code] = response.code @parsed_response[:message] = response return @parsed_response end end def parse_response(response) case response.code when 200 @parsed_response = Hash.new @parsed_response[:code] = response.code response = JSON.parse(response) @parsed_response[:access_token] = response["access_token"] @parsed_response[:accounts] = response["accounts"] @parsed_response[:transactions] = response["transactions"] @parsed_response[:accounts] = response["accounts"] return @parsed_response when 201 @parsed_response = Hash.new @parsed_response[:code] = response.code response = JSON.parse(response) @parsed_response = Hash.new @parsed_response[:type] = response["type"] @parsed_response[:access_token] = response["access_token"] @parsed_response[:mfa_info] = response["mfa_info"] @parsed_response[:mfa] = response['mfa'] return @parsed_response else @parsed_response = Hash.new @parsed_response[:code] = response.code @parsed_response[:message] = response return @parsed_response end end def parse_place(response) @parsed_response = Hash.new @parsed_response[:code] = response.code response = JSON.parse(response)["entity"] @parsed_response[:category] = response["category"] @parsed_response[:name] = response["name"] @parsed_response[:id] = response["_id"] @parsed_response[:phone] = response["meta"]["contact"]["telephone"] @parsed_response[:location] = response["meta"]["location"] return @parsed_response end private def post_to_exchange(public_token) url = BASE_URL + '/exchange_token' @response = RestClient.post url, :client_id => self.instance_variable_get(:'@customer_id') ,:secret => self.instance_variable_get(:'@secret'), :public_token => public_token return @response end def post(path,type,username,password,email) url = BASE_URL + path @response = RestClient.post url, :client_id => self.instance_variable_get(:'@customer_id') ,:secret => self.instance_variable_get(:'@secret'), :type => type ,:credentials => '{"username":"' + username + '", "password":"' + password + '"}', :email => email return @response end def get(path,id) url = BASE_URL + path @response = RestClient.get(url,:params => {:entity_id => id}) return @response end end end
ciholas/cdp-examples
ruby/cdp-ruby-example.rb
<reponame>ciholas/cdp-examples # Ciholas, Inc. - www.ciholas.com # Licensed under: creativecommons.org/licenses/by/4.0 require 'bindata' require 'ipaddr' require 'socket' # Maximum size of any UDP packet received RECEIVE_BUFFER_SIZE = 65536 # The expected value of the CDP Header MARK field CDP_MARK_WORD = 0x3230434C # The expected value of the CDP Header STRING field CDP_STRING_WORD = 'CDP0002' # The type for a CDP Position V3 Data Item CDP_DATA_ITEM_POSITION_V3 = 0x0135 # The CDP Data Item has a header with a total size of 4 bytes and a variable length payload # CDP Data Item container type class CdpDataItem < BinData::Record endian :little # All data items are transmitted in little-endian uint16 :identifier # Identifier: The type of the CDP Data Item (2 bytes) (type is a reserved word in Ruby) uint16 :len # Len: The size of the Data Item, not including the Data Item Header (2 bytes) (size is a reserved word in Ruby) string :payload, :read_length => :len # The remaining bytes in the Data Item are the payload end # The CDP Packet has a header with a total size of 20 bytes and a variable length array of data items # CDP Packet container type class CdpPacket < BinData::Record endian :little # All packets are transmitted in little-endian buffer :header, :length => 20 do uint32 :mark # Mark: The magic word '0x3230434C' in little-endian (842023756 in decimal) (4 bytes) uint32 :sequence # Sequence: The sequence number of the CDP packet (4 bytes) string :str, :length => 8 # Str: The ASCII string 'CDP0002\0' (8 bytes) uint32 :serial # Serial Number: Unique identifier of the reporting device (4 bytes) end array :data_items, :type => CdpDataItem, :read_until => :eof # The remaining bytes are an array of CDP Data Items end # The Position V3 (type 0x0135) data item has a total size of 30 bytes # Position V3 Data Item container type class CdpPositionV3 < BinData::Record endian :little # All data items are transmitted in little-endian uint32 :serial_number # Serial Number: The serial number of the reporting device (4 bytes) uint64 :network_time # Network Time: The timestamp when the sensor recorded the data (8 bytes) int32 :x_in_mm # X-Coordinate: The x-coordinate from the origin (4 bytes) int32 :y_in_mm # Y-Coordinate: The y-coordinate from the origin (4 bytes) int32 :z_in_mm # Z-Coordinate: The z-coordinate from the origin (4 bytes) uint16 :quality # Quality: The quality of the computed position (2 bytes) uint8 :anchor_count # Anchor Count: The number of anchors involved in the calculation of this position (1 byte) uint8 :flags # Flags: 1 bit = inactive mode. 1 bit = was not calculated. 6 bits = unused. (1 byte) uint16 :smoothing # The effective smoothing factor (2 bytes) end # Ensure correct usage of the program if ARGV.length == 3 multicast_addr = ARGV[0] udp_port = ARGV[1] interface_addr = ARGV[2] else puts 'Usage: cdp-ruby-example GROUP PORT INTERFACE' puts ' GROUP - IP to listen on (ie: 172.16.58.3)' puts ' PORT - Port to listen on (ie 7667)' puts ' INTERFACE - Source local interface IP address (This should be your local interface that is on the same subnet as the CUWB Network)' exit(1) end puts 'Started CDP Ruby Example Program' # Setup membership membership = IPAddr.new(multicast_addr).hton + IPAddr.new(interface_addr).hton # Create a UDP socket for listening to CDP packets socket = UDPSocket.new # Allow other apps to use the same port/ifc socket.setsockopt(:SOL_SOCKET, :SO_REUSEADDR, 1) # Setup receive ip address socket.setsockopt(:IPPROTO_IP, :IP_ADD_MEMBERSHIP, membership) # Bind the socket socket.bind(Socket::INADDR_ANY, udp_port) # The setup of the socket is complete, so data can now be pulled from it # Loop on reception of packet loop do # Block on receiving a UDP packet message, addr = socket.recvfrom(RECEIVE_BUFFER_SIZE) # At this point, if the line below was not commented out, raw data would be printed to the console. If no data is printed, verify that the CUWB Network is running # puts message # Extract a CDP Packet from the message cdp_packet = CdpPacket.read(message) # Ensure the CDP Header is valid (that is, that the mark matches the 'magic word' and that the string matches the specified ASCII string) if cdp_packet.header.mark == CDP_MARK_WORD and cdp_packet.header.str[0...6] == CDP_STRING_WORD[0...6] begin # Loop through all data items in the packet cdp_packet.data_items.each do |data_item| # For this example, we only care about type 0x0135, which is Position V3, all other types will be ignored if data_item.identifier == CDP_DATA_ITEM_POSITION_V3 # Extract the remaining bytes from the Data Item payload, these are the bytes corresponding to Position V3 position_v3_item = CdpPositionV3.read(data_item.payload) # Print out all the fields in the Position V3 data item # Flags and Smoothing will be ignored for conciseness puts "Position V3 - Serial Number #{position_v3_item.serial_number}, Network Time #{position_v3_item.network_time}, Coordinates: (#{position_v3_item.x_in_mm}, #{position_v3_item.y_in_mm}, #{position_v3_item.z_in_mm}), Quality: #{position_v3_item.quality}, Anchor Count: #{position_v3_item.anchor_count}" end end end else raise 'Unrecognized CDP Header' end end
ciholas/cdp-examples
c/object-oriented/src/rake/source.rake
### constants class Source OUT_DIR = 'output' OBJS_DIR = ".objects/" OUTPUT = "#{OUT_DIR}/cdp-c-example" SRC_FILES = FileList["src/**/*.c"] OBJ_FILES = SRC_FILES.ext('.o').map { |sf| File.join(".objects",sf) } FLAGS="-Isrc -Isrc/include -pthread" end ### rules #.c to .o rule /.*\.o/ => proc { |t| t.ext('.c').sub(Source::OBJS_DIR, '') } do |t| puts "#{Display::BLUE}Compiling#{Display::BLANK} #{t.name} #{Display::BLUE}from#{Display::BLANK} #{t.source}" sh "mkdir -p #{File.dirname(t.name)}" sh "gcc -o #{t.name} -c #{t.sources.join(" ")} #{Source::FLAGS}" end #.o to binary rule Source::OUTPUT => Source::OBJ_FILES do |t| puts Display::BLUE+"Finalizing binary"+Display::BLANK sh "mkdir -p #{Source::OUT_DIR}" sh "gcc -o #{Source::OUTPUT} #{t.sources.join(" ")} #{Source::FLAGS}" end ### tasks desc 'builds the source, disregarding if nothing has changed' task source: Source::OUTPUT desc 'cleans the output folder' task :clean do sh "rm -rf #{Source::OUT_DIR} #{Source::OBJS_DIR}" end task default: :source
twittemb/homebrew-formulae
Formula/xcodecoverageconverter.rb
# Documentation: https://docs.brew.sh/Formula-Cookbook # https://rubydoc.brew.sh/Formula # PLEASE REMOVE ALL GENERATED COMMENTS BEFORE SUBMITTING YOUR PULL REQUEST! class Xcodecoverageconverter < Formula desc "" homepage "https://github.com/twittemb/XcodeCoverageConverter" url "https://github.com/twittemb/XcodeCoverageConverter.git", :tag => "0.2.1", :revision => "3e668c2b0a9aed9bbc67391d1f9e64232e8edb40" head "https://github.com/twittemb/XcodeCoverageConverter.git" depends_on :xcode => ["11.0", :build] version "0.2.1" sha256 "" license "MIT" def install system "make", "install", "prefix=#{prefix}" end test do system false end end
oneplanetliving/hyper-router
lib/react/router.rb
module React class Router < React::NativeLibrary imports 'ReactRouter' end end
oneplanetliving/hyper-router
lib/hyper-router/version.rb
<reponame>oneplanetliving/hyper-router module HyperRouter VERSION = '4.2.6.lap28' HYPERLOOP_VERSION = '1.0.0.lap28' end
oneplanetliving/hyper-router
lib/hyperstack/router/component.rb
<reponame>oneplanetliving/hyper-router<gh_stars>0 module Hyperstack class Router class Component class << self def inherited(base) base.include(Mixin) end end end end end
oneplanetliving/hyper-router
lib/hyper-router/component_methods.rb
# rubocop:disable Style/MethodName module HyperRouter module ComponentMethods def Link(to, opts = {}, &children) opts[:to] = {}.tap do |hash| hash[:pathname] = to hash[:search] = opts.delete(:search) if opts[:search] hash[:hash] = opts.delete(:hash) if opts[:hash] end.to_n React::Router::DOM::Link(opts, &children) end def NavLink(to, opts = {}, &children) opts[:to] = to.to_n opts[:activeClassName] = opts.delete(:active_class).to_n if opts[:active_class] opts[:activeStyle] = opts.delete(:active_style).to_n if opts[:active_style] opts[:isActive] = opts.delete(:active).to_n if opts[:active] if (%i[activeClassName activeStyle isActive] & opts.keys).any? React::State.get_state(HyperRouter, :location) end React::Router::DOM::NavLink(opts, &children) end def Redirect(to, opts = {}) opts[:to] = to.to_n React::Router::Redirect(opts) end def format_params(e) { match: HyperRouter::Match.new(`#{e}.match`), location: HyperRouter::Location.new(`#{e}.location`), history: HyperRouter::History.new(`#{e}.history`) } end def Route(to, opts = {}, &block) opts[:path] = to.to_n if opts[:mounts] component = opts.delete(:mounts) opts[:component] = lambda do |e| route_params = format_params(e) React.create_element(component, route_params).to_n end end if block opts[:render] = lambda do |e| route_params = format_params(e) yield(route_params.values).to_n end end React::Router::Route(opts) end def Switch(&children) React::Router::Switch(&children) end end end
oneplanetliving/hyper-router
lib/hyperstack/router/hash.rb
module Hyperstack class Router module Hash def self.included(base) base.extend(HyperRouter::ClassMethods) base.history(:hash) base.include(HyperRouter::InstanceMethods) base.include(HyperRouter::ComponentMethods) end end end end
oneplanetliving/hyper-router
lib/hyperstack/router.rb
<reponame>oneplanetliving/hyper-router module Hyperstack class Router def self.inherited(child) child.include(Hyperstack::Component::Mixin) child.include(Base) end end class BrowserRouter def self.inherited(child) child.include(Hyperstack::Component::Mixin) child.include(Hyperstack::Router::Browser) end end class HashRouter def self.inherited(child) child.include(Hyperstack::Component::Mixin) child.include(Hyperstack::Router::Hash) end end class MemoryRouter def self.inherited(child) child.include(Hyperstack::Component::Mixin) child.include(Hyperstack::Router::Memory) end end class StaticRouter def self.inherited(child) child.include(Hyperstack::Component::Mixin) child.include(Hyperstack::Router::Static) end end end