_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q1700
RDoc.Fortran95parser.check_external_aliases
train
def check_external_aliases(subname, params, comment, test=nil) @@external_aliases.each{ |alias_item| if subname == alias_item["old_name"] || subname.upcase == alias_item["old_name"].upcase && @options.ignore_case new_meth = initialize_external_method(alias_item["new_name"], subname, params, @file_name, comment) new_meth.visibility = alias_item["visibility"] progress "e" @stats.num_methods += 1 alias_item["file_or_module"].add_method(new_meth) if !alias_item["file_or_module"].include_requires?(@file_name, @options.ignore_case) alias_item["file_or_module"].add_require(Require.new(@file_name, "")) end end } end
ruby
{ "resource": "" }
q1701
RDoc.Fortran95parser.united_to_one_line
train
def united_to_one_line(f90src) return "" unless f90src lines = f90src.split("\n") previous_continuing = false now_continuing = false body = "" lines.each{ |line| words = line.split("") next if words.empty? && previous_continuing commentout = false brank_flag = true ; brank_char = "" squote = false ; dquote = false ignore = false words.collect! { |char| if previous_continuing && brank_flag now_continuing = true ignore = true case char when "!" ; break when " " ; brank_char << char ; next "" when "&" brank_flag = false now_continuing = false next "" else brank_flag = false now_continuing = false ignore = false next brank_char + char end end ignore = false if now_continuing next "" elsif !(squote) && !(dquote) && !(commentout) case char when "!" ; commentout = true ; next char when "\""; dquote = true ; next char when "\'"; squote = true ; next char when "&" ; now_continuing = true ; next "" else next char end elsif commentout next char elsif squote case char when "\'"; squote = false ; next char else next char end elsif dquote case char when "\""; dquote = false ; next char else next char end end } if !ignore && !previous_continuing || !brank_flag if previous_continuing body << words.join("") else body << "\n" + words.join("") end end previous_continuing = now_continuing ? true : nil now_continuing = nil } return body end
ruby
{ "resource": "" }
q1702
RDoc.Fortran95parser.continuous_line?
train
def continuous_line?(line) continuous = false if /&\s*?(!.*)?$/ =~ line continuous = true if comment_out?($~.pre_match) continuous = false end end return continuous end
ruby
{ "resource": "" }
q1703
RDoc.Fortran95parser.comment_out?
train
def comment_out?(line) return nil unless line commentout = false squote = false ; dquote = false line.split("").each { |char| if !(squote) && !(dquote) case char when "!" ; commentout = true ; break when "\""; dquote = true when "\'"; squote = true else next end elsif squote case char when "\'"; squote = false else next end elsif dquote case char when "\""; dquote = false else next end end } return commentout end
ruby
{ "resource": "" }
q1704
RDoc.Fortran95parser.semicolon_to_linefeed
train
def semicolon_to_linefeed(text) return "" unless text lines = text.split("\n") lines.collect!{ |line| words = line.split("") commentout = false squote = false ; dquote = false words.collect! { |char| if !(squote) && !(dquote) && !(commentout) case char when "!" ; commentout = true ; next char when "\""; dquote = true ; next char when "\'"; squote = true ; next char when ";" ; "\n" else next char end elsif commentout next char elsif squote case char when "\'"; squote = false ; next char else next char end elsif dquote case char when "\""; dquote = false ; next char else next char end end } words.join("") } return lines.join("\n") end
ruby
{ "resource": "" }
q1705
RDoc.Fortran95parser.remove_empty_head_lines
train
def remove_empty_head_lines(text) return "" unless text lines = text.split("\n") header = true lines.delete_if{ |line| header = false if /\S/ =~ line header && /^\s*?$/ =~ line } lines.join("\n") end
ruby
{ "resource": "" }
q1706
Zlib.ZStream.end
train
def end unless ready? then warn "attempt to close uninitialized stream; ignored." return nil end if in_stream? then warn "attempt to close unfinished zstream; reset forced" reset end reset_input err = Zlib.send @func_end, pointer Zlib.handle_error err, message @flags = 0 # HACK this may be wrong @output = nil @next_out.free unless @next_out.nil? @next_out = nil nil end
ruby
{ "resource": "" }
q1707
Zlib.ZStream.reset
train
def reset err = Zlib.send @func_reset, pointer Zlib.handle_error err, message @flags = READY reset_input end
ruby
{ "resource": "" }
q1708
Zlib.Deflate.do_deflate
train
def do_deflate(data, flush) if data.nil? then run '', Zlib::FINISH else data = StringValue data if flush != Zlib::NO_FLUSH or not data.empty? then # prevent BUF_ERROR run data, flush end end end
ruby
{ "resource": "" }
q1709
Zlib.Deflate.params
train
def params(level, strategy) err = Zlib.deflateParams pointer, level, strategy raise Zlib::BufError, 'buffer expansion not implemented' if err == Zlib::BUF_ERROR Zlib.handle_error err, message nil end
ruby
{ "resource": "" }
q1710
Zlib.GzipReader.check_footer
train
def check_footer @zstream.flags |= Zlib::GzipFile::FOOTER_FINISHED footer = @zstream.input.slice! 0, 8 rest = @io.read 8 - footer.length footer << rest if rest raise NoFooter, 'footer is not found' unless footer.length == 8 crc, length = footer.unpack 'VV' @zstream[:total_in] += 8 # to rewind correctly raise CRCError, 'invalid compressed data -- crc error' unless @crc == crc raise LengthError, 'invalid compressed data -- length error' unless length == @zstream.total_out end
ruby
{ "resource": "" }
q1711
Zlib.GzipWriter.make_header
train
def make_header flags = 0 extra_flags = 0 flags |= Zlib::GzipFile::FLAG_ORIG_NAME if @orig_name flags |= Zlib::GzipFile::FLAG_COMMENT if @comment extra_flags |= Zlib::GzipFile::EXTRAFLAG_FAST if @level == Zlib::BEST_SPEED extra_flags |= Zlib::GzipFile::EXTRAFLAG_SLOW if @level == Zlib::BEST_COMPRESSION header = [ Zlib::GzipFile::MAGIC1, # byte 0 Zlib::GzipFile::MAGIC2, # byte 1 Zlib::GzipFile::METHOD_DEFLATE, # byte 2 flags, # byte 3 @mtime.to_i, # bytes 4-7 extra_flags, # byte 8 @os_code # byte 9 ].pack 'CCCCVCC' @io.write header @io.write "#{@orig_name}\0" if @orig_name @io.write "#{@comment}\0" if @comment @zstream.flags |= Zlib::GzipFile::HEADER_FINISHED end
ruby
{ "resource": "" }
q1712
Zlib.GzipWriter.make_footer
train
def make_footer footer = [ @crc, # bytes 0-3 @zstream.total_in, # bytes 4-7 ].pack 'VV' @io.write footer @zstream.flags |= Zlib::GzipFile::FOOTER_FINISHED end
ruby
{ "resource": "" }
q1713
Zlib.GzipWriter.write
train
def write(data) make_header unless header_finished? data = String data if data.length > 0 or sync? then @crc = Zlib.crc32_c @crc, data, data.length flush = sync? ? Zlib::SYNC_FLUSH : Zlib::NO_FLUSH @zstream.run data, flush end write_raw end
ruby
{ "resource": "" }
q1714
Zlib.Inflate.<<
train
def <<(string) string = StringValue string unless string.nil? if finished? then unless string.nil? then @input ||= '' @input << string end else run string, Zlib::SYNC_FLUSH end end
ruby
{ "resource": "" }
q1715
REXML.Element.each_with_something
train
def each_with_something( test, max=0, name=nil ) num = 0 child=nil @elements.each( name ){ |child| yield child if test.call(child) and num += 1 return if max>0 and num == max } end
ruby
{ "resource": "" }
q1716
XMLRPC.BasicServer.check_arity
train
def check_arity(obj, n_args) ary = obj.arity if ary >= 0 n_args == ary else n_args >= (ary+1).abs end end
ruby
{ "resource": "" }
q1717
Gem::Security.Policy.verify_gem
train
def verify_gem(signature, data, chain, time = Time.now) Gem.ensure_ssl_available cert_class = OpenSSL::X509::Certificate exc = Gem::Security::Exception chain ||= [] chain = chain.map{ |str| cert_class.new(str) } signer, ch_len = chain[-1], chain.size # make sure signature is valid if @verify_data # get digest algorithm (TODO: this should be configurable) dgst = @opt[:dgst_algo] # verify the data signature (this is the most important part, so don't # screw it up :D) v = signer.public_key.verify(dgst.new, signature, data) raise exc, "Invalid Gem Signature" unless v # make sure the signer is valid if @verify_signer # make sure the signing cert is valid right now v = signer.check_validity(nil, time) raise exc, "Invalid Signature: #{v[:desc]}" unless v[:is_valid] end end # make sure the certificate chain is valid if @verify_chain # iterate down over the chain and verify each certificate against it's # issuer (ch_len - 1).downto(1) do |i| issuer, cert = chain[i - 1, 2] v = cert.check_validity(issuer, time) raise exc, "%s: cert = '%s', error = '%s'" % [ 'Invalid Signing Chain', cert.subject, v[:desc] ] unless v[:is_valid] end # verify root of chain if @verify_root # make sure root is self-signed root = chain[0] raise exc, "%s: %s (subject = '%s', issuer = '%s')" % [ 'Invalid Signing Chain Root', 'Subject does not match Issuer for Gem Signing Chain', root.subject.to_s, root.issuer.to_s, ] unless root.issuer.to_s == root.subject.to_s # make sure root is valid v = root.check_validity(root, time) raise exc, "%s: cert = '%s', error = '%s'" % [ 'Invalid Signing Chain Root', root.subject, v[:desc] ] unless v[:is_valid] # verify that the chain root is trusted if @only_trusted # get digest algorithm, calculate checksum of root.subject algo = @opt[:dgst_algo] path = Gem::Security::Policy.trusted_cert_path(root, @opt) # check to make sure trusted path exists raise exc, "%s: cert = '%s', error = '%s'" % [ 'Untrusted Signing Chain Root', root.subject.to_s, "path \"#{path}\" does not exist", ] unless File.exist?(path) # load calculate digest from saved cert file save_cert = OpenSSL::X509::Certificate.new(File.read(path)) save_dgst = algo.digest(save_cert.public_key.to_s) # create digest of public key pkey_str = root.public_key.to_s cert_dgst = algo.digest(pkey_str) # now compare the two digests, raise exception # if they don't match raise exc, "%s: %s (saved = '%s', root = '%s')" % [ 'Invalid Signing Chain Root', "Saved checksum doesn't match root checksum", save_dgst, cert_dgst, ] unless save_dgst == cert_dgst end end # return the signing chain chain.map { |cert| cert.subject } end end
ruby
{ "resource": "" }
q1718
YAML.YamlNode.transform
train
def transform t = nil if @value.is_a? Hash t = {} @value.each { |k,v| t[ k ] = v[1].transform } elsif @value.is_a? Array t = [] @value.each { |v| t.push v.transform } else t = @value end YAML.transfer_method( @type_id, t ) end
ruby
{ "resource": "" }
q1719
RDoc.RubyParser.collect_first_comment
train
def collect_first_comment skip_tkspace res = '' first_line = true tk = get_tk while tk.kind_of?(TkCOMMENT) if first_line && /\A#!/ =~ tk.text skip_tkspace tk = get_tk elsif first_line && /\A#\s*-\*-/ =~ tk.text first_line = false skip_tkspace tk = get_tk else first_line = false res << tk.text << "\n" tk = get_tk if tk.kind_of? TkNL skip_tkspace(false) tk = get_tk end end end unget_tk(tk) res end
ruby
{ "resource": "" }
q1720
RDoc.RubyParser.parse_method_parameters
train
def parse_method_parameters(method) res = parse_method_or_yield_parameters(method) res = "(" + res + ")" unless res[0] == ?( method.params = res unless method.params if method.block_params.nil? skip_tkspace(false) read_documentation_modifiers(method, METHOD_MODIFIERS) end end
ruby
{ "resource": "" }
q1721
RDoc.RubyParser.skip_optional_do_after_expression
train
def skip_optional_do_after_expression skip_tkspace(false) tk = get_tk case tk when TkLPAREN, TkfLPAREN end_token = TkRPAREN else end_token = TkNL end nest = 0 @scanner.instance_eval{@continue = false} loop do puts("\nWhile: #{tk}, #{@scanner.continue} " + "#{@scanner.lex_state} #{nest}") if $DEBUG case tk when TkSEMICOLON break when TkLPAREN, TkfLPAREN nest += 1 when TkDO break if nest.zero? when end_token if end_token == TkRPAREN nest -= 1 break if @scanner.lex_state == EXPR_END and nest.zero? else break unless @scanner.continue end end tk = get_tk end skip_tkspace(false) if peek_tk.kind_of? TkDO get_tk end end
ruby
{ "resource": "" }
q1722
RDoc.RubyParser.get_class_specification
train
def get_class_specification tk = get_tk return "self" if tk.kind_of?(TkSELF) res = "" while tk.kind_of?(TkCOLON2) || tk.kind_of?(TkCOLON3) || tk.kind_of?(TkCONSTANT) res += tk.text tk = get_tk end unget_tk(tk) skip_tkspace(false) get_tkread # empty out read buffer tk = get_tk case tk when TkNL, TkCOMMENT, TkSEMICOLON unget_tk(tk) return res end res += parse_call_parameters(tk) res end
ruby
{ "resource": "" }
q1723
RDoc.RubyParser.get_constant
train
def get_constant res = "" skip_tkspace(false) tk = get_tk while tk.kind_of?(TkCOLON2) || tk.kind_of?(TkCOLON3) || tk.kind_of?(TkCONSTANT) res += tk.text tk = get_tk end # if res.empty? # warn("Unexpected token #{tk} in constant") # end unget_tk(tk) res end
ruby
{ "resource": "" }
q1724
RDoc.RubyParser.get_constant_with_optional_parens
train
def get_constant_with_optional_parens skip_tkspace(false) nest = 0 while (tk = peek_tk).kind_of?(TkLPAREN) || tk.kind_of?(TkfLPAREN) get_tk skip_tkspace(true) nest += 1 end name = get_constant while nest > 0 skip_tkspace(true) tk = get_tk nest -= 1 if tk.kind_of?(TkRPAREN) end name end
ruby
{ "resource": "" }
q1725
RDoc.RubyParser.read_directive
train
def read_directive(allowed) tk = get_tk puts "directive: #{tk.inspect}" if $DEBUG result = nil if tk.kind_of?(TkCOMMENT) if tk.text =~ /\s*:?(\w+):\s*(.*)/ directive = $1.downcase if allowed.include?(directive) result = [directive, $2] end end else unget_tk(tk) end result end
ruby
{ "resource": "" }
q1726
SOAP.WSDLDriverFactory.create_driver
train
def create_driver(servicename = nil, portname = nil) warn("WSDLDriverFactory#create_driver is depricated. Use create_rpc_driver instead.") port = find_port(servicename, portname) WSDLDriver.new(@wsdl, port, nil) end
ruby
{ "resource": "" }
q1727
Generators.MarkUp.markup
train
def markup(str, remove_para=false) return '' unless str unless defined? @markup @markup = SM::SimpleMarkup.new # class names, variable names, or instance variables @markup.add_special(/( \w+(::\w+)*[.\#]\w+(\([\.\w+\*\/\+\-\=\<\>]+\))? # A::B.meth(**) (for operator in Fortran95) | \#\w+(\([.\w\*\/\+\-\=\<\>]+\))? # meth(**) (for operator in Fortran95) | \b([A-Z]\w*(::\w+)*[.\#]\w+) # A::B.meth | \b([A-Z]\w+(::\w+)*) # A::B.. | \#\w+[!?=]? # #meth_name | \b\w+([_\/\.]+\w+)*[!?=]? # meth_name )/x, :CROSSREF) # external hyperlinks @markup.add_special(/((link:|https?:|mailto:|ftp:|www\.)\S+\w)/, :HYPERLINK) # and links of the form <text>[<url>] @markup.add_special(/(((\{.*?\})|\b\S+?)\[\S+?\.\S+?\])/, :TIDYLINK) # @markup.add_special(/\b(\S+?\[\S+?\.\S+?\])/, :TIDYLINK) end unless defined? @html_formatter @html_formatter = HyperlinkHtml.new(self.path, self) end # Convert leading comment markers to spaces, but only # if all non-blank lines have them if str =~ /^(?>\s*)[^\#]/ content = str else content = str.gsub(/^\s*(#+)/) { $1.tr('#',' ') } end res = @markup.convert(content, @html_formatter) if remove_para res.sub!(/^<p>/, '') res.sub!(/<\/p>$/, '') end res end
ruby
{ "resource": "" }
q1728
Generators.ContextUser.build_method_detail_list
train
def build_method_detail_list(section) outer = [] methods = @methods.sort for singleton in [true, false] for vis in [ :public, :protected, :private ] res = [] methods.each do |m| if m.section == section and m.document_self and m.visibility == vis and m.singleton == singleton row = {} if m.call_seq row["callseq"] = m.call_seq.gsub(/->/, '&rarr;') else row["name"] = CGI.escapeHTML(m.name) row["params"] = m.params end desc = m.description.strip row["m_desc"] = desc unless desc.empty? row["aref"] = m.aref row["visibility"] = m.visibility.to_s alias_names = [] m.aliases.each do |other| if other.viewer # won't be if the alias is private alias_names << { 'name' => other.name, 'aref' => other.viewer.as_href(path) } end end unless alias_names.empty? row["aka"] = alias_names end if @options.inline_source code = m.source_code row["sourcecode"] = code if code else code = m.src_url if code row["codeurl"] = code row["imgurl"] = m.img_url end end res << row end end if res.size > 0 outer << { "type" => vis.to_s.capitalize, "category" => singleton ? "Class" : "Instance", "methods" => res } end end end outer end
ruby
{ "resource": "" }
q1729
Generators.ContextUser.build_class_list
train
def build_class_list(level, from, section, infile=nil) res = "" prefix = "&nbsp;&nbsp;::" * level; from.modules.sort.each do |mod| next unless mod.section == section next if infile && !mod.defined_in?(infile) if mod.document_self res << prefix << "Module " << href(url(mod.viewer.path), "link", mod.full_name) << "<br />\n" << build_class_list(level + 1, mod, section, infile) end end from.classes.sort.each do |cls| next unless cls.section == section next if infile && !cls.defined_in?(infile) if cls.document_self res << prefix << "Class " << href(url(cls.viewer.path), "link", cls.full_name) << "<br />\n" << build_class_list(level + 1, cls, section, infile) end end res end
ruby
{ "resource": "" }
q1730
Generators.HTMLGenerator.load_html_template
train
def load_html_template template = @options.template unless template =~ %r{/|\\} template = File.join("rdoc/generators/template", @options.generator.key, template) end require template extend RDoc::Page rescue LoadError $stderr.puts "Could not find HTML template '#{template}'" exit 99 end
ruby
{ "resource": "" }
q1731
Generators.HTMLGenerator.write_style_sheet
train
def write_style_sheet template = TemplatePage.new(RDoc::Page::STYLE) unless @options.css File.open(CSS_NAME, "w") do |f| values = { "fonts" => RDoc::Page::FONTS } template.write_html_on(f, values) end end end
ruby
{ "resource": "" }
q1732
Generators.HTMLGenerator.main_url
train
def main_url main_page = @options.main_page ref = nil if main_page ref = AllReferences[main_page] if ref ref = ref.path else $stderr.puts "Could not find main page #{main_page}" end end unless ref for file in @files if file.document_self ref = file.path break end end end unless ref $stderr.puts "Couldn't find anything to document" $stderr.puts "Perhaps you've used :stopdoc: in all classes" exit(1) end ref end
ruby
{ "resource": "" }
q1733
Generators.HTMLGeneratorInOne.generate_xml
train
def generate_xml values = { 'charset' => @options.charset, 'files' => gen_into(@files), 'classes' => gen_into(@classes), 'title' => CGI.escapeHTML(@options.title), } # this method is defined in the template file write_extra_pages if defined? write_extra_pages template = TemplatePage.new(RDoc::Page::ONE_PAGE) if @options.op_name opfile = File.open(@options.op_name, "w") else opfile = $stdout end template.write_html_on(opfile, values) end
ruby
{ "resource": "" }
q1734
RDoc.Diagram.draw
train
def draw unless @options.quiet $stderr.print "Diagrams: " $stderr.flush end @info.each_with_index do |i, file_count| @done_modules = {} @local_names = find_names(i) @global_names = [] @global_graph = graph = DOT::Digraph.new('name' => 'TopLevel', 'fontname' => FONT, 'fontsize' => '8', 'bgcolor' => 'lightcyan1', 'compound' => 'true') # it's a little hack %) i'm too lazy to create a separate class # for default node graph << DOT::Node.new('name' => 'node', 'fontname' => FONT, 'color' => 'black', 'fontsize' => 8) i.modules.each do |mod| draw_module(mod, graph, true, i.file_relative_name) end add_classes(i, graph, i.file_relative_name) i.diagram = convert_to_png("f_#{file_count}", graph) # now go through and document each top level class and # module independently i.modules.each_with_index do |mod, count| @done_modules = {} @local_names = find_names(mod) @global_names = [] @global_graph = graph = DOT::Digraph.new('name' => 'TopLevel', 'fontname' => FONT, 'fontsize' => '8', 'bgcolor' => 'lightcyan1', 'compound' => 'true') graph << DOT::Node.new('name' => 'node', 'fontname' => FONT, 'color' => 'black', 'fontsize' => 8) draw_module(mod, graph, true) mod.diagram = convert_to_png("m_#{file_count}_#{count}", graph) end end $stderr.puts unless @options.quiet end
ruby
{ "resource": "" }
q1735
RDoc.Context.find_symbol
train
def find_symbol(symbol, method=nil) result = nil case symbol when /^::(.*)/ result = toplevel.find_symbol($1) when /::/ modules = symbol.split(/::/) unless modules.empty? module_name = modules.shift result = find_module_named(module_name) if result modules.each do |module_name| result = result.find_module_named(module_name) break unless result end end end else # if a method is specified, then we're definitely looking for # a module, otherwise it could be any symbol if method result = find_module_named(symbol) else result = find_local_symbol(symbol) if result.nil? if symbol =~ /^[A-Z]/ result = parent while result && result.name != symbol result = result.parent end end end end end if result && method if !result.respond_to?(:find_local_symbol) p result.name p method fail end result = result.find_local_symbol(method) end result end
ruby
{ "resource": "" }
q1736
ActiveSupport.MessageVerifier.secure_compare
train
def secure_compare(a, b) if a.length == b.length result = 0 for i in 0..(a.length - 1) result |= a[i] ^ b[i] end result == 0 else false end end
ruby
{ "resource": "" }
q1737
RSS.ListenerMixin.parse_pi_content
train
def parse_pi_content(content) params = {} content.scan(CONTENT_PATTERN) do |name, quote, value| params[name] = value end params end
ruby
{ "resource": "" }
q1738
RSS.Parser.normalize_rss
train
def normalize_rss(rss) return rss if maybe_xml?(rss) uri = to_uri(rss) if uri.respond_to?(:read) uri.read elsif !rss.tainted? and File.readable?(rss) File.open(rss) {|f| f.read} else rss end end
ruby
{ "resource": "" }
q1739
Rcov.RcovTask.define
train
def define lib_path = @libs.join(File::PATH_SEPARATOR) actual_name = Hash === name ? name.keys.first : name unless Rake.application.last_comment desc "Analyze code coverage with tests" + (@name==:rcov ? "" : " for #{actual_name}") end task @name do run_code = '' RakeFileUtils.verbose(@verbose) do run_code = case rcov_path when nil, '' "-S rcov" else %!"#{rcov_path}"! end ruby_opts = @ruby_opts.clone ruby_opts.push( "-I#{lib_path}" ) ruby_opts.push run_code ruby_opts.push( "-w" ) if @warning ruby ruby_opts.join(" ") + " " + option_list + %[ -o "#{@output_dir}" ] + file_list.collect { |fn| %["#{fn}"] }.join(' ') end end desc "Remove rcov products for #{actual_name}" task paste("clobber_", actual_name) do rm_r @output_dir rescue nil end clobber_task = paste("clobber_", actual_name) task :clobber => [clobber_task] task actual_name => clobber_task self end
ruby
{ "resource": "" }
q1740
RDoc.RDoc.update_output_dir
train
def update_output_dir(op_dir, time) File.open(output_flag_file(op_dir), "w") {|f| f.puts time.rfc2822 } end
ruby
{ "resource": "" }
q1741
RDoc.RDoc.normalized_file_list
train
def normalized_file_list(options, relative_files, force_doc = false, exclude_pattern = nil) file_list = [] relative_files.each do |rel_file_name| next if exclude_pattern && exclude_pattern =~ rel_file_name stat = File.stat(rel_file_name) case type = stat.ftype when "file" next if @last_created and stat.mtime < @last_created if force_doc or ::RDoc::Parser.can_parse(rel_file_name) then file_list << rel_file_name.sub(/^\.\//, '') end when "directory" next if rel_file_name == "CVS" || rel_file_name == ".svn" dot_doc = File.join(rel_file_name, DOT_DOC_FILENAME) if File.file?(dot_doc) file_list.concat(parse_dot_doc_file(rel_file_name, dot_doc, options)) else file_list.concat(list_files_in_directory(rel_file_name, options)) end else raise RDoc::Error, "I can't deal with a #{type} #{rel_file_name}" end end file_list end
ruby
{ "resource": "" }
q1742
RDoc.RDoc.list_files_in_directory
train
def list_files_in_directory(dir, options) files = Dir.glob File.join(dir, "*") normalized_file_list options, files, false, options.exclude end
ruby
{ "resource": "" }
q1743
RDoc.RDoc.parse_files
train
def parse_files(options) @stats = Stats.new options.verbosity files = options.files files = ["."] if files.empty? file_list = normalized_file_list(options, files, true, options.exclude) return [] if file_list.empty? file_info = [] file_list.each do |filename| @stats.add_file filename content = if RUBY_VERSION >= '1.9' then File.open(filename, "r:ascii-8bit") { |f| f.read } else File.read filename end if defined? Encoding then if /coding:\s*(\S+)/ =~ content[/\A(?:.*\n){0,2}/] if enc = ::Encoding.find($1) content.force_encoding(enc) end end end top_level = ::RDoc::TopLevel.new filename parser = ::RDoc::Parser.for top_level, filename, content, options, @stats file_info << parser.scan end file_info end
ruby
{ "resource": "" }
q1744
RDoc.RDoc.document
train
def document(argv) TopLevel::reset @options = Options.new GENERATORS @options.parse argv @last_created = nil unless @options.all_one_file then @last_created = setup_output_dir @options.op_dir, @options.force_update end start_time = Time.now file_info = parse_files @options @options.title = "RDoc Documentation" if file_info.empty? $stderr.puts "\nNo newer files." unless @options.quiet else @gen = @options.generator $stderr.puts "\nGenerating #{@gen.key.upcase}..." unless @options.quiet require @gen.file_name gen_class = ::RDoc::Generator.const_get @gen.class_name @gen = gen_class.for @options pwd = Dir.pwd Dir.chdir @options.op_dir unless @options.all_one_file begin Diagram.new(file_info, @options).draw if @options.diagram @gen.generate(file_info) update_output_dir(".", start_time) ensure Dir.chdir(pwd) end end unless @options.quiet puts @stats.print end end
ruby
{ "resource": "" }
q1745
RSS.Utils.new_with_value_if_need
train
def new_with_value_if_need(klass, value) if value.is_a?(klass) value else klass.new(value) end end
ruby
{ "resource": "" }
q1746
RDoc.Context.methods_matching
train
def methods_matching(methods, singleton = false) count = 0 @method_list.each do |m| if methods.include? m.name and m.singleton == singleton then yield m count += 1 end end return if count == methods.size || singleton # perhaps we need to look at attributes @attributes.each do |a| yield a if methods.include? a.name end end
ruby
{ "resource": "" }
q1747
RDoc.Context.find_module_named
train
def find_module_named(name) # First check the enclosed modules, then check the module itself, # then check the enclosing modules (this mirrors the check done by # the Ruby parser) res = @modules[name] || @classes[name] return res if res return self if self.name == name find_enclosing_module_named(name) end
ruby
{ "resource": "" }
q1748
RDoc.TopLevel.add_class_or_module
train
def add_class_or_module(collection, class_type, name, superclass) cls = collection[name] if cls then cls.superclass = superclass unless cls.module? puts "Reusing class/module #{cls.full_name}" if $DEBUG_RDOC else if class_type == NormalModule then all = @@all_modules else all = @@all_classes end cls = all[name] if !cls then cls = class_type.new name, superclass all[name] = cls unless @done_documenting else # If the class has been encountered already, check that its # superclass has been set (it may not have been, depending on # the context in which it was encountered). if class_type == NormalClass if !cls.superclass then cls.superclass = superclass end end end collection[name] = cls unless @done_documenting cls.parent = self end cls end
ruby
{ "resource": "" }
q1749
RDoc.ClassModule.superclass
train
def superclass raise NoMethodError, "#{full_name} is a module" if module? scope = self begin superclass = scope.classes.find { |c| c.name == @superclass } return superclass.full_name if superclass scope = scope.parent end until scope.nil? or TopLevel === scope @superclass end
ruby
{ "resource": "" }
q1750
Rack.Response.write
train
def write(str) s = str.to_s @length += Rack::Utils.bytesize(s) @writer.call s header["Content-Length"] = @length.to_s str end
ruby
{ "resource": "" }
q1751
REXML.Attribute.to_s
train
def to_s return @normalized if @normalized doctype = nil if @element doc = @element.document doctype = doc.doctype if doc end @normalized = Text::normalize( @unnormalized, doctype ) @unnormalized = nil @normalized end
ruby
{ "resource": "" }
q1752
REXML.Attribute.value
train
def value return @unnormalized if @unnormalized doctype = nil if @element doc = @element.document doctype = doc.doctype if doc end @unnormalized = Text::unnormalize( @normalized, doctype ) @normalized = nil @unnormalized end
ruby
{ "resource": "" }
q1753
Rake.TaskManager.resolve_args_with_dependencies
train
def resolve_args_with_dependencies(args, hash) # :nodoc: fail "Task Argument Error" if hash.size != 1 key, value = hash.map { |k, v| [k,v] }.first if args.empty? task_name = key arg_names = [] deps = value elsif key == :needs task_name = args.shift arg_names = args deps = value else task_name = args.shift arg_names = key deps = value end deps = [deps] unless deps.respond_to?(:to_ary) [task_name, arg_names, deps] end
ruby
{ "resource": "" }
q1754
Rake.Application.top_level
train
def top_level standard_exception_handling do if options.show_tasks display_tasks_and_comments elsif options.show_prereqs display_prerequisites else top_level_tasks.each { |task_name| invoke_task(task_name) } end end end
ruby
{ "resource": "" }
q1755
Generators.RIGenerator.method_list
train
def method_list(cls) list = cls.method_list unless @options.show_all list = list.find_all do |m| m.visibility == :public || m.visibility == :protected || m.force_documentation end end c = [] i = [] list.sort.each do |m| if m.singleton c << m else i << m end end return c,i end
ruby
{ "resource": "" }
q1756
Rcov.DifferentialAnalyzer.reset
train
def reset @@mutex.synchronize do if self.class.hook_level == 0 # Unfortunately there's no way to report this as covered with rcov: # if we run the tests under rcov self.class.hook_level will be >= 1 ! # It is however executed when we run the tests normally. Rcov::RCOV__.send(@reset_meth) @start_raw_data = data_default @end_raw_data = data_default else @start_raw_data = @end_raw_data = raw_data_absolute end @raw_data_relative = data_default @aggregated_data = data_default end end
ruby
{ "resource": "" }
q1757
Net.FTP.putbinaryfile
train
def putbinaryfile(localfile, remotefile = File.basename(localfile), blocksize = DEFAULT_BLOCKSIZE, &block) # :yield: data if @resume begin rest_offset = size(remotefile) rescue Net::FTPPermError rest_offset = nil end else rest_offset = nil end f = open(localfile) begin f.binmode storbinary("STOR " + remotefile, f, blocksize, rest_offset, &block) ensure f.close end end
ruby
{ "resource": "" }
q1758
RI.ClassEntry.load_from
train
def load_from(dir) Dir.foreach(dir) do |name| next if name =~ /^\./ # convert from external to internal form, and # extract the instance/class flag if name =~ /^(.*?)-(c|i).yaml$/ external_name = $1 is_class_method = $2 == "c" internal_name = RiWriter.external_to_internal(external_name) list = is_class_method ? @class_methods : @instance_methods path = File.join(dir, name) list << MethodEntry.new(path, internal_name, is_class_method, self) else full_name = File.join(dir, name) if File.directory?(full_name) inf_class = @inferior_classes.find {|c| c.name == name } if inf_class inf_class.add_path(full_name) else inf_class = ClassEntry.new(full_name, name, self) @inferior_classes << inf_class end inf_class.load_from(full_name) end end end end
ruby
{ "resource": "" }
q1759
RI.ClassEntry.recursively_find_methods_matching
train
def recursively_find_methods_matching(name, is_class_method) res = local_methods_matching(name, is_class_method) @inferior_classes.each do |c| res.concat(c.recursively_find_methods_matching(name, is_class_method)) end res end
ruby
{ "resource": "" }
q1760
RI.ClassEntry.all_method_names
train
def all_method_names res = @class_methods.map {|m| m.full_name } @instance_methods.each {|m| res << m.full_name} res end
ruby
{ "resource": "" }
q1761
RI.ClassEntry.local_methods_matching
train
def local_methods_matching(name, is_class_method) list = case is_class_method when nil then @class_methods + @instance_methods when true then @class_methods when false then @instance_methods else fail "Unknown is_class_method: #{is_class_method.inspect}" end list.find_all {|m| m.name; m.name[name]} end
ruby
{ "resource": "" }
q1762
RDoc::Generator.MarkUp.markup
train
def markup(str, remove_para = false) return '' unless str # Convert leading comment markers to spaces, but only if all non-blank # lines have them if str =~ /^(?>\s*)[^\#]/ then content = str else content = str.gsub(/^\s*(#+)/) { $1.tr '#', ' ' } end res = formatter.convert content if remove_para then res.sub!(/^<p>/, '') res.sub!(/<\/p>$/, '') end res end
ruby
{ "resource": "" }
q1763
RDoc::Generator.Context.as_href
train
def as_href(from_path) if @options.all_one_file "#" + path else RDoc::Markup::ToHtml.gen_relative_url from_path, path end end
ruby
{ "resource": "" }
q1764
RDoc::Generator.Context.collect_methods
train
def collect_methods list = @context.method_list unless @options.show_all then list = list.select do |m| m.visibility == :public or m.visibility == :protected or m.force_documentation end end @methods = list.collect do |m| RDoc::Generator::Method.new m, self, @options end end
ruby
{ "resource": "" }
q1765
RDoc::Generator.Context.add_table_of_sections
train
def add_table_of_sections toc = [] @context.sections.each do |section| if section.title then toc << { 'secname' => section.title, 'href' => section.sequence } end end @values['toc'] = toc unless toc.empty? end
ruby
{ "resource": "" }
q1766
RDoc::Generator.Class.http_url
train
def http_url(full_name, prefix) path = full_name.dup path.gsub!(/<<\s*(\w*)/, 'from-\1') if path['<<'] ::File.join(prefix, path.split("::")) + ".html" end
ruby
{ "resource": "" }
q1767
FFI.ConstGenerator.to_ruby
train
def to_ruby @constants.sort_by { |name,| name }.map do |name, constant| if constant.value.nil? then "# #{name} not available" else constant.to_ruby end end.join "\n" end
ruby
{ "resource": "" }
q1768
RI.ModuleDescription.merge_in
train
def merge_in(old) merge(@class_methods, old.class_methods) merge(@instance_methods, old.instance_methods) merge(@attributes, old.attributes) merge(@constants, old.constants) merge(@includes, old.includes) if @comment.nil? || @comment.empty? @comment = old.comment else unless old.comment.nil? or old.comment.empty? then @comment << SM::Flow::RULE.new @comment.concat old.comment end end end
ruby
{ "resource": "" }
q1769
IRB.WorkSpace.filter_backtrace
train
def filter_backtrace(bt) case IRB.conf[:CONTEXT_MODE] when 0 return nil if bt =~ /\(irb_local_binding\)/ when 1 if(bt =~ %r!/tmp/irb-binding! or bt =~ %r!irb/.*\.rb! or bt =~ /irb\.rb/) return nil end when 2 return nil if bt =~ /irb\/.*\.rb/ when 3 return nil if bt =~ /irb\/.*\.rb/ bt.sub!(/:\s*in `irb_binding'/){""} end bt end
ruby
{ "resource": "" }
q1770
RI.RiReader.get_method
train
def get_method(method_entry) path = method_entry.path_name File.open(path) { |f| RI::Description.deserialize(f) } end
ruby
{ "resource": "" }
q1771
RI.RiReader.get_class
train
def get_class(class_entry) result = nil for path in class_entry.path_names path = RiWriter.class_desc_path(path, class_entry) desc = File.open(path) {|f| RI::Description.deserialize(f) } if result result.merge_in(desc) else result = desc end end result end
ruby
{ "resource": "" }
q1772
RI.Options.parse
train
def parse(args) old_argv = ARGV.dup ARGV.replace(args) begin go = GetoptLong.new(*OptionList.options) go.quiet = true go.each do |opt, arg| case opt when "--help" then OptionList.usage when "--version" then show_version when "--list-names" then @list_names = true when "--no-pager" then @use_stdout = true when "--classes" then @list_classes = true when "--java" then @java_classes = true when "--system" then @use_system = true when "--site" then @use_site = true when "--home" then @use_home = true when "--gems" then @use_gems = true when "--doc-dir" if File.directory?(arg) @doc_dirs << arg else $stderr.puts "Invalid directory: #{arg}" exit 1 end when "--format" @formatter = RI::TextFormatter.for(arg) unless @formatter $stderr.print "Invalid formatter (should be one of " $stderr.puts RI::TextFormatter.list + ")" exit 1 end when "--width" begin @width = Integer(arg) rescue $stderr.puts "Invalid width: '#{arg}'" exit 1 end end end rescue GetoptLong::InvalidOption, GetoptLong::MissingArgument => error OptionList.error(error.message) end end
ruby
{ "resource": "" }
q1773
RDoc.RDoc.parse_files
train
def parse_files(options) file_info = [] files = options.files files = ["."] if files.empty? file_list = normalized_file_list(options, files, true) file_list.each do |fn| $stderr.printf("\n%35s: ", File.basename(fn)) unless options.quiet content = File.open(fn, "r") {|f| f.read} top_level = TopLevel.new(fn) parser = ParserFactory.parser_for(top_level, fn, content, options, @stats) file_info << parser.scan @stats.num_files += 1 end file_info end
ruby
{ "resource": "" }
q1774
JdbcSpec.MissingFunctionalityHelper.alter_table
train
def alter_table(table_name, options = {}) #:nodoc: table_name = table_name.to_s.downcase altered_table_name = "altered_#{table_name}" caller = lambda {|definition| yield definition if block_given?} transaction do # A temporary table might improve performance here, but # it doesn't seem to maintain indices across the whole move. move_table(table_name, altered_table_name, options) move_table(altered_table_name, table_name, &caller) end end
ruby
{ "resource": "" }
q1775
YAML.BaseNode.select
train
def select( ypath_str ) matches = match_path( ypath_str ) # # Create a new generic view of the elements selected # if matches result = [] matches.each { |m| result.push m.last } YAML.transfer( 'seq', result ) end end
ruby
{ "resource": "" }
q1776
YAML.BaseNode.select!
train
def select!( ypath_str ) matches = match_path( ypath_str ) # # Create a new generic view of the elements selected # if matches result = [] matches.each { |m| result.push m.last.transform } result end end
ruby
{ "resource": "" }
q1777
YAML.BaseNode.search
train
def search( ypath_str ) matches = match_path( ypath_str ) if matches matches.collect { |m| path = [] m.each_index { |i| path.push m[i] if ( i % 2 ).zero? } "/" + path.compact.join( "/" ) } end end
ruby
{ "resource": "" }
q1778
YAML.BaseNode.match_path
train
def match_path( ypath_str ) depth = 0 matches = [] YPath.each_path( ypath_str ) do |ypath| seg = match_segment( ypath, 0 ) matches += seg if seg end matches.uniq end
ruby
{ "resource": "" }
q1779
YAML.BaseNode.match_segment
train
def match_segment( ypath, depth ) deep_nodes = [] seg = ypath.segments[ depth ] if seg == "/" unless String === @value idx = -1 @value.collect { |v| idx += 1 if Hash === @value match_init = [v[0].transform, v[1]] match_deep = v[1].match_segment( ypath, depth ) else match_init = [idx, v] match_deep = v.match_segment( ypath, depth ) end if match_deep match_deep.each { |m| deep_nodes.push( match_init + m ) } end } end depth += 1 seg = ypath.segments[ depth ] end match_nodes = case seg when "." [[nil, self]] when ".." [["..", nil]] when "*" if @value.is_a? Enumerable idx = -1 @value.collect { |h| idx += 1 if Hash === @value [h[0].transform, h[1]] else [idx, h] end } end else if seg =~ /^"(.*)"$/ seg = $1 elsif seg =~ /^'(.*)'$/ seg = $1 end if ( v = at( seg ) ) [[ seg, v ]] end end return deep_nodes unless match_nodes pred = ypath.predicates[ depth ] if pred case pred when /^\.=/ pred = $' # ' match_nodes.reject! { |n| n.last.value != pred } else match_nodes.reject! { |n| n.last.at( pred ).nil? } end end return match_nodes + deep_nodes unless ypath.segments.length > depth + 1 #puts "DEPTH: #{depth + 1}" deep_nodes = [] match_nodes.each { |n| if n[1].is_a? BaseNode match_deep = n[1].match_segment( ypath, depth + 1 ) if match_deep match_deep.each { |m| deep_nodes.push( n + m ) } end else deep_nodes = [] end } deep_nodes = nil if deep_nodes.length == 0 deep_nodes end
ruby
{ "resource": "" }
q1780
YAML.BaseNode.[]
train
def []( *key ) if Hash === @value v = @value.detect { |k,| k.transform == key.first } v[1] if v elsif Array === @value @value.[]( *key ) end end
ruby
{ "resource": "" }
q1781
SM.ToLaTeX.escape
train
def escape(str) # $stderr.print "FE: ", str s = str. # sub(/\s+$/, ''). gsub(/([_\${}&%#])/, "#{BS}\\1"). gsub(/\\/, BACKSLASH). gsub(/\^/, HAT). gsub(/~/, TILDE). gsub(/</, LESSTHAN). gsub(/>/, GREATERTHAN). gsub(/,,/, ",{},"). gsub(/\`/, BACKQUOTE) # $stderr.print "-> ", s, "\n" s end
ruby
{ "resource": "" }
q1782
FFI.Library.attach_function
train
def attach_function(mname, a2, a3, a4=nil, a5 = nil) cname, arg_types, ret_type, opts = (a4 && (a2.is_a?(String) || a2.is_a?(Symbol))) ? [ a2, a3, a4, a5 ] : [ mname.to_s, a2, a3, a4 ] # Convert :foo to the native type arg_types.map! { |e| find_type(e) } options = Hash.new options[:convention] = defined?(@ffi_convention) ? @ffi_convention : :default options[:type_map] = defined?(@ffi_typedefs) ? @ffi_typedefs : nil options[:enums] = defined?(@ffi_enum_map) ? @ffi_enum_map : nil options.merge!(opts) if opts.is_a?(Hash) # Try to locate the function in any of the libraries invokers = [] load_error = nil ffi_libraries.each do |lib| begin invokers << FFI.create_invoker(lib, cname.to_s, arg_types, find_type(ret_type), options) rescue LoadError => ex load_error = ex end if invokers.empty? end invoker = invokers.compact.shift raise load_error if load_error && invoker.nil? #raise FFI::NotFoundError.new(cname.to_s, *libraries) unless invoker invoker.attach(self, mname.to_s) invoker # Return a version that can be called via #call end
ruby
{ "resource": "" }
q1783
ActiveSupport.Dependencies.qualified_const_defined?
train
def qualified_const_defined?(path) raise NameError, "#{path.inspect} is not a valid constant name!" unless /^(::)?([A-Z]\w*)(::[A-Z]\w*)*$/ =~ path names = path.to_s.split('::') names.shift if names.first.empty? # We can't use defined? because it will invoke const_missing for the parent # of the name we are checking. names.inject(Object) do |mod, name| return false unless uninherited_const_defined?(mod, name) mod.const_get name end return true end
ruby
{ "resource": "" }
q1784
ActiveSupport.Dependencies.search_for_file
train
def search_for_file(path_suffix) path_suffix = path_suffix + '.rb' unless path_suffix.ends_with? '.rb' load_paths.each do |root| path = File.join(root, path_suffix) return path if File.file? path end nil # Gee, I sure wish we had first_match ;-) end
ruby
{ "resource": "" }
q1785
ActiveSupport.Dependencies.autoload_module!
train
def autoload_module!(into, const_name, qualified_name, path_suffix) return nil unless base_path = autoloadable_module?(path_suffix) mod = Module.new into.const_set const_name, mod autoloaded_constants << qualified_name unless load_once_paths.include?(base_path) return mod end
ruby
{ "resource": "" }
q1786
ActiveSupport.Dependencies.qualified_name_for
train
def qualified_name_for(mod, name) mod_name = to_constant_name mod (%w(Object Kernel).include? mod_name) ? name.to_s : "#{mod_name}::#{name}" end
ruby
{ "resource": "" }
q1787
ActiveSupport.Dependencies.load_missing_constant
train
def load_missing_constant(from_mod, const_name) log_call from_mod, const_name if from_mod == Kernel if ::Object.const_defined?(const_name) log "Returning Object::#{const_name} for Kernel::#{const_name}" return ::Object.const_get(const_name) else log "Substituting Object for Kernel" from_mod = Object end end # If we have an anonymous module, all we can do is attempt to load from Object. from_mod = Object if from_mod.name.blank? unless qualified_const_defined?(from_mod.name) && from_mod.name.constantize.object_id == from_mod.object_id raise ArgumentError, "A copy of #{from_mod} has been removed from the module tree but is still active!" end raise ArgumentError, "#{from_mod} is not missing constant #{const_name}!" if uninherited_const_defined?(from_mod, const_name) qualified_name = qualified_name_for from_mod, const_name path_suffix = qualified_name.underscore name_error = NameError.new("uninitialized constant #{qualified_name}") file_path = search_for_file(path_suffix) if file_path && ! loaded.include?(File.expand_path(file_path)) # We found a matching file to load require_or_load file_path raise LoadError, "Expected #{file_path} to define #{qualified_name}" unless uninherited_const_defined?(from_mod, const_name) return from_mod.const_get(const_name) elsif mod = autoload_module!(from_mod, const_name, qualified_name, path_suffix) return mod elsif (parent = from_mod.parent) && parent != from_mod && ! from_mod.parents.any? { |p| uninherited_const_defined?(p, const_name) } # If our parents do not have a constant named +const_name+ then we are free # to attempt to load upwards. If they do have such a constant, then this # const_missing must be due to from_mod::const_name, which should not # return constants from from_mod's parents. begin return parent.const_missing(const_name) rescue NameError => e raise unless e.missing_name? qualified_name_for(parent, const_name) raise name_error end else raise name_error end end
ruby
{ "resource": "" }
q1788
ActiveSupport.Dependencies.remove_unloadable_constants!
train
def remove_unloadable_constants! autoloaded_constants.each { |const| remove_constant const } autoloaded_constants.clear explicitly_unloadable_constants.each { |const| remove_constant const } end
ruby
{ "resource": "" }
q1789
ActiveSupport.Dependencies.autoloaded?
train
def autoloaded?(desc) # No name => anonymous module. return false if desc.is_a?(Module) && desc.name.blank? name = to_constant_name desc return false unless qualified_const_defined? name return autoloaded_constants.include?(name) end
ruby
{ "resource": "" }
q1790
ActiveSupport.Dependencies.mark_for_unload
train
def mark_for_unload(const_desc) name = to_constant_name const_desc if explicitly_unloadable_constants.include? name return false else explicitly_unloadable_constants << name return true end end
ruby
{ "resource": "" }
q1791
YAML.BaseEmitter.indent_text
train
def indent_text( text, mod, first_line = true ) return "" if text.to_s.empty? spacing = indent( mod ) text = text.gsub( /\A([^\n])/, "#{ spacing }\\1" ) if first_line return text.gsub( /\n^([^\n])/, "\n#{spacing}\\1" ) end
ruby
{ "resource": "" }
q1792
YAML.BaseEmitter.indent
train
def indent( mod = nil ) #p [ self.id, level, mod, :INDENT ] if level <= 0 mod ||= 0 else mod ||= options(:Indent) mod += ( level - 1 ) * options(:Indent) end return " " * mod end
ruby
{ "resource": "" }
q1793
Net.FTP.getbinaryfile
train
def getbinaryfile(remotefile, localfile = File.basename(remotefile), blocksize = DEFAULT_BLOCKSIZE, &block) # :yield: data if @resume rest_offset = File.size?(localfile) f = open(localfile, "a") else rest_offset = nil f = open(localfile, "w") end begin f.binmode retrbinary("RETR " + remotefile, blocksize, rest_offset) do |data| f.write(data) yield(data) if block end ensure f.close end end
ruby
{ "resource": "" }
q1794
Rinda.RingServer.do_write
train
def do_write(msg) Thread.new do begin tuple, sec = Marshal.load(msg) @ts.write(tuple, sec) rescue end end end
ruby
{ "resource": "" }
q1795
Rinda.RingFinger.lookup_ring
train
def lookup_ring(timeout=5, &block) return lookup_ring_any(timeout) unless block_given? msg = Marshal.dump([[:lookup_ring, DRbObject.new(block)], timeout]) @broadcast_list.each do |it| soc = UDPSocket.open begin soc.setsockopt(Socket::SOL_SOCKET, Socket::SO_BROADCAST, true) soc.send(msg, 0, it, @port) rescue nil ensure soc.close end end sleep(timeout) end
ruby
{ "resource": "" }
q1796
Generators.CHMGenerator.create_project_file
train
def create_project_file template = TemplatePage.new(RDoc::Page::HPP_FILE) values = { "title" => @options.title, "opname" => @op_name } files = [] @files.each do |f| files << { "html_file_name" => f.path } end values['all_html_files'] = files File.open(@project_name, "w") do |f| template.write_html_on(f, values) end end
ruby
{ "resource": "" }
q1797
Generators.CHMGenerator.create_contents_and_index
train
def create_contents_and_index contents = [] index = [] (@files+@classes).sort.each do |entry| content_entry = { "c_name" => entry.name, "ref" => entry.path } index << { "name" => entry.name, "aref" => entry.path } internals = [] methods = entry.build_method_summary_list(entry.path) content_entry["methods"] = methods unless methods.empty? contents << content_entry index.concat methods end values = { "contents" => contents } template = TemplatePage.new(RDoc::Page::CONTENTS) File.open("contents.hhc", "w") do |f| template.write_html_on(f, values) end values = { "index" => index } template = TemplatePage.new(RDoc::Page::CHM_INDEX) File.open("index.hhk", "w") do |f| template.write_html_on(f, values) end end
ruby
{ "resource": "" }
q1798
Rinda.TupleEntry.get_renewer
train
def get_renewer(it) case it when Numeric, true, nil return it, nil else begin return it.renew, it rescue Exception return it, nil end end end
ruby
{ "resource": "" }
q1799
Rinda.TupleBag.push
train
def push(tuple) key = bin_key(tuple) @hash[key] ||= TupleBin.new @hash[key].add(tuple) end
ruby
{ "resource": "" }