_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q19200
Ferret::Index.Index.highlight
train
def highlight(query, doc_id, options = {}) @dir.synchronize do ensure_searcher_open() @searcher.highlight(do_process_query(query), doc_id, options[:field]||@options[:default_field], options) end end
ruby
{ "resource": "" }
q19201
Ferret::Index.Index.term_vector
train
def term_vector(id, field) @dir.synchronize do ensure_reader_open() if id.kind_of?(String) or id.kind_of?(Symbol) term_doc_enum = @reader.term_docs_for(@id_field, id.to_s) if term_doc_enum.next? id = term_doc_enum.doc else return nil ...
ruby
{ "resource": "" }
q19202
Ferret::Index.Index.query_delete
train
def query_delete(query) @dir.synchronize do ensure_writer_open() ensure_searcher_open() query = do_process_query(query) @searcher.search_each(query, :limit => :all) do |doc, score| @reader.delete(doc) end flush() if @auto_flush end end
ruby
{ "resource": "" }
q19203
Ferret::Index.Index.update
train
def update(id, new_doc) @dir.synchronize do ensure_writer_open() delete(id) if id.is_a?(String) or id.is_a?(Symbol) @writer.commit else ensure_writer_open() end @writer << new_doc flush() if @auto_flush end end
ruby
{ "resource": "" }
q19204
Ferret::Index.Index.batch_update
train
def batch_update(docs) @dir.synchronize do ids = nil case docs when Array ids = docs.collect{|doc| doc[@id_field].to_s} if ids.include?(nil) raise ArgumentError, "all documents must have an #{@id_field} " "field when doing a...
ruby
{ "resource": "" }
q19205
Ferret::Index.Index.query_update
train
def query_update(query, new_val) @dir.synchronize do ensure_writer_open() ensure_searcher_open() docs_to_add = [] query = do_process_query(query) @searcher.search_each(query, :limit => :all) do |id, score| document = @searcher[id].load if new_val.is_a?(H...
ruby
{ "resource": "" }
q19206
Ferret::Index.Index.explain
train
def explain(query, doc) @dir.synchronize do ensure_searcher_open() query = do_process_query(query) return @searcher.explain(query, doc) end end
ruby
{ "resource": "" }
q19207
Ferret::Index.Index.ensure_reader_open
train
def ensure_reader_open(get_latest = true) raise "tried to use a closed index" if not @open if @reader if get_latest latest = false begin latest = @reader.latest? rescue Lock::LockError sleep(@options[:lock_retry_time]) # sleep for...
ruby
{ "resource": "" }
q19208
Ferret::Browser.ViewHelper.truncate
train
def truncate(str, len = 80) if str and str.length > len and (add = str[len..-1].index(' ')) str = str[0, len + add] + '&#8230;' end str end
ruby
{ "resource": "" }
q19209
Ferret::Browser.Controller.paginate
train
def paginate(idx, max, url, &b) return '' if max == 0 url = url.gsub(%r{^/?(.*?)/?$}, '\1') b ||= lambda{} link = lambda {|*args| i, title, text = args "<a href=\"/#{url}/#{i}#{'?' + @query_string if @query_string}\" " + "#{'onclick="return false;"' if (i == idx)} " + ...
ruby
{ "resource": "" }
q19210
Rubyvis::SvgScene.PathBasis.weight
train
def weight(w) OpenStruct.new({ :x=> w[0] * p0.left + w[1] * p1.left + w[2] * p2.left + w[3] * p3.left, :y=> w[0] * p0.top + w[1] * p1.top + w[2] * p2.top + w[3] * p3.top }) end
ruby
{ "resource": "" }
q19211
ESpeak.Speech.save
train
def save(filename) speech = bytes_wav res = IO.popen(lame_command(filename, command_options), 'r+') do |process| process.write(speech) process.close_write process.read end res.to_s end
ruby
{ "resource": "" }
q19212
ESpeak.Speech.bytes
train
def bytes() speech = bytes_wav res = IO.popen(std_lame_command(command_options), 'r+') do |process| process.write(speech) process.close_write process.read end res.to_s end
ruby
{ "resource": "" }
q19213
Rubyvis.Flatten.array
train
def array @entries=[] @stack=[] if @leaf recurse(@map,0) return @entries end visit(@map,0) @entries.map {|stack| m={} @keys.each_with_index {|k,i| v=stack[i] m[k.name]=k.value ? k.value.js_call(self,v) : v } m ...
ruby
{ "resource": "" }
q19214
Rubyvis.Image.bind
train
def bind mark_bind bind=self.binds mark=self begin binds.image = mark._image end while(!binds.image and (mark==mark.proto)) end
ruby
{ "resource": "" }
q19215
Rubyvis.Scale::Quantitative.scale
train
def scale(x) return nil if x.nil? x=x.to_f j=Rubyvis.search(@d, x) j=-j-2 if (j<0) j=[0,[@i.size-1,j].min].max # p @l # puts "Primero #{j}: #{@f.call(x) - @l[j]}" # puts "Segundo #{(@l[j + 1] - @l[j])}" @i[j].call((@f.call(x) - @l[j]) .quo(@l[j + 1] - @l[j])); e...
ruby
{ "resource": "" }
q19216
Rubyvis.Scale::Log.ticks
train
def ticks(subdivisions=nil) d = domain n = d[0] < 0 subdivisions||=@b span=@b.to_f / subdivisions # puts "dom: #{d[0]} -> #{n}" i = (n ? -log(-d[0]) : log(d[0])).floor j = (n ? -log(-d[1]) : log(d[1])).ceil ticks = []; if n ticks.push(-pow(-i)) ...
ruby
{ "resource": "" }
q19217
MotionKit.Parent.try
train
def try(*method_chain) obj = self.element method_chain.each do |m| # We'll break out and return nil if any part of the chain # doesn't respond properly. (obj = nil) && break unless obj.respond_to?(m) obj = obj.send(m) end obj end
ruby
{ "resource": "" }
q19218
MotionKit.BaseLayoutClassMethods.memoize
train
def memoize(klass) @memoize ||= {} @memoize[klass] ||= begin while klass break if registered_class = target_klasses[klass] klass = klass.superclass end @memoize[klass] = registered_class if registered_class end @memoize[klass] end
ruby
{ "resource": "" }
q19219
MotionKit.TreeLayout.create
train
def create(element, element_id=nil, &block) element = initialize_element(element, element_id) style_and_context(element, element_id, &block) element end
ruby
{ "resource": "" }
q19220
MotionKit.TreeLayout.reapply
train
def reapply(&block) raise ArgumentError.new('Block required') unless block raise InvalidDeferredError.new('reapply must be run inside of a context') unless @context if reapply? yield end block = block.weak! parent_layout.reapply_blocks << [@context, block] return self...
ruby
{ "resource": "" }
q19221
MotionKit.TreeLayout.get_view
train
def get_view(element_id) element = get(element_id) if element.is_a?(Layout) element = element.view end element end
ruby
{ "resource": "" }
q19222
MotionKit.TreeLayout.last_view
train
def last_view(element_id) element = last(element_id) if element.is_a?(Layout) element = element.view end element end
ruby
{ "resource": "" }
q19223
MotionKit.TreeLayout.all_views
train
def all_views(element_id) element = all(element_id) if element.is_a?(Layout) element = element.view end element end
ruby
{ "resource": "" }
q19224
MotionKit.TreeLayout.nth_view
train
def nth_view(element_id, index) element = nth(element_id) if element.is_a?(Layout) element = element.view end element end
ruby
{ "resource": "" }
q19225
MotionKit.TreeLayout.forget
train
def forget(element_id) unless is_parent_layout? return parent_layout.remove(element_id) end removed = nil context(self.view) do removed = all(element_id) @elements[element_id] = nil end removed end
ruby
{ "resource": "" }
q19226
MotionKit.TreeLayout.forget_tree
train
def forget_tree(element_id, view) removed = forget_view(element_id, view) if view.subviews view.subviews.each do | sub | if (sub_ids = sub.motion_kit_meta[:motion_kit_ids]) sub_ids.each do | sub_id | forget_tree(sub_id, sub) || [] end end ...
ruby
{ "resource": "" }
q19227
MotionKit.TreeLayout.build_view
train
def build_view # Only in the 'layout' method will we allow default container to be # created automatically (when 'add' is called) @assign_root = true prev_should_run = @should_run_deferred @should_run_deferred = true layout unless @view if @assign_root create_...
ruby
{ "resource": "" }
q19228
MotionKit.TreeLayout.initialize_element
train
def initialize_element(elem, element_id) if elem.is_a?(Class) && elem < TreeLayout layout = elem.new elem = layout.view elsif elem.is_a?(Class) elem = elem.new elsif elem.is_a?(TreeLayout) layout = elem elem = elem.view end if layout if elem...
ruby
{ "resource": "" }
q19229
MotionKit.TreeLayout.style_and_context
train
def style_and_context(element, element_id, &block) style_method = "#{element_id}_style" if parent_layout.respond_to?(style_method) || block_given? parent_layout.context(element) do if parent_layout.respond_to?(style_method) parent_layout.send(style_method) end ...
ruby
{ "resource": "" }
q19230
MotionKit.BaseLayout.context
train
def context(new_target, &block) return new_target unless block # this little line is incredibly important; the context is only set on # the top-level Layout object. # mp "MOTIONKIT CONTEXT is #{new_target} meta: #{new_target.motion_kit_meta}" return parent_layout.context(new_target, &bloc...
ruby
{ "resource": "" }
q19231
MotionKit.MenuLayout.root
train
def root(element, element_id=nil, &block) if element && element.is_a?(NSString) element = NSMenu.alloc.initWithTitle(element) end super(element, element_id, &block) end
ruby
{ "resource": "" }
q19232
MotionKit.MenuLayout.add
train
def add(title_or_item, element_id=nil, options={}, &block) if element_id.is_a?(NSDictionary) options = element_id element_id = nil end if title_or_item.is_a?(NSMenuItem) item = title_or_item menu = nil retval = item elsif title_or_item.is_a?(NSMenu) ...
ruby
{ "resource": "" }
q19233
Expeditor.Command.start_with_retry
train
def start_with_retry(current_thread: false, **retryable_options) unless started? @retryable_options.set(retryable_options) start(current_thread: current_thread) end self end
ruby
{ "resource": "" }
q19234
Expeditor.Command.on_complete
train
def on_complete(&block) on do |_, value, reason| block.call(reason == nil, value, reason) end end
ruby
{ "resource": "" }
q19235
Expeditor.Command.on_success
train
def on_success(&block) on do |_, value, reason| block.call(value) unless reason end end
ruby
{ "resource": "" }
q19236
Expeditor.Command.on_failure
train
def on_failure(&block) on do |_, _, reason| block.call(reason) if reason end end
ruby
{ "resource": "" }
q19237
Expeditor.Command.prepare
train
def prepare(executor = @service.executor) @normal_future = initial_normal(executor, &@normal_block) @normal_future.add_observer do |_, value, reason| if reason # failure if @fallback_block future = RichFuture.new(executor: executor) do success, value, reason = Con...
ruby
{ "resource": "" }
q19238
Expeditor.Command.initial_normal
train
def initial_normal(executor, &block) future = RichFuture.new(executor: executor) do args = wait_dependencies timeout_block(args, &block) end future.add_observer do |_, _, reason| metrics(reason) end future end
ruby
{ "resource": "" }
q19239
GDB.EvalContext.invoke_pry
train
def invoke_pry org = Pry.config.history.file # this has no effect if gdb is launched by pry Pry.config.history.file = '~/.gdb-pry_history' $stdin.cooked { pry } Pry.config.history.file = org end
ruby
{ "resource": "" }
q19240
GDB.GDB.text_base
train
def text_base check_alive! base = Integer(execute('info proc stat').scan(/Start of text: (.*)/).flatten.first) execute("set $text = #{base}") base end
ruby
{ "resource": "" }
q19241
GDB.GDB.read_memory
train
def read_memory(addr, num_elements, options = {}, &block) check_alive! # this would set @pid options[:as] = block if block_given? MemoryIO.attach(@pid).read(addr, num_elements, **options) end
ruby
{ "resource": "" }
q19242
GDB.GDB.write_memory
train
def write_memory(addr, objects, options = {}, &block) check_alive! # this would set @pid options[:as] = block if block_given? MemoryIO.attach(@pid).write(addr, objects, **options) end
ruby
{ "resource": "" }
q19243
Danger.DangerRubocop.lint
train
def lint(config = nil) config = config.is_a?(Hash) ? config : { files: config } files = config[:files] force_exclusion = config[:force_exclusion] || false report_danger = config[:report_danger] || false inline_comment = config[:inline_comment] || false fail_on_inline_comment = confi...
ruby
{ "resource": "" }
q19244
Beefcake.Generator.name_for
train
def name_for(b, mod, val) b.name_for(mod, val).to_s.gsub(/.*_/, "").downcase end
ruby
{ "resource": "" }
q19245
LiterateRandomizer.SourceParser.scrub_sentence
train
def scrub_sentence(sentence) sentence.split(/([\s]|--)+/).collect {|a| scrub_word(a)}.select {|a| a.length>0} end
ruby
{ "resource": "" }
q19246
LiterateRandomizer.MarkovModel.next_word
train
def next_word(word,randomizer=@randomizer) return if !markov_chains[word] sum = @markov_weighted_sum[word] random = randomizer.rand(sum)+1 partial_sum = 0 (markov_chains[word].find do |w, count| partial_sum += count w!=word && partial_sum >= random end||[]).first end
ruby
{ "resource": "" }
q19247
LiterateRandomizer.Randomizer.extend_trailing_preposition
train
def extend_trailing_preposition(max_words,words) while words.length < max_words && words[-1] && words[-1][PREPOSITION_REGEX] words << model.next_word(words[-1],randomizer) end words end
ruby
{ "resource": "" }
q19248
LiterateRandomizer.Randomizer.sentence
train
def sentence(options={}) word = options[:first_word] || self.first_word num_words_option = options[:words] || (3..15) count = Util.rand_count(num_words_option,randomizer) punctuation = options[:punctuation] || self.punctuation words = count.times.collect do word.tap {word = model.next_word(wo...
ruby
{ "resource": "" }
q19249
LiterateRandomizer.Randomizer.paragraph
train
def paragraph(options={}) count = Util.rand_count(options[:sentences] || (5..15),randomizer) count.times.collect do |i| op = options.clone op.delete :punctuation unless i==count-1 op.delete :first_word unless i==0 sentence op end.join(" ") end
ruby
{ "resource": "" }
q19250
LiterateRandomizer.Randomizer.paragraphs
train
def paragraphs(options={}) count = Util.rand_count(options[:paragraphs] || (3..5),randomizer) join_str = options[:join] res = count.times.collect do |i| op = options.clone op.delete :punctuation unless i==count-1 op.delete :first_word unless i==0 paragraph op end join_str!=...
ruby
{ "resource": "" }
q19251
GLib.ArrayMethods.index
train
def index(idx) unless (0...length).cover? idx raise IndexError, "Index #{idx} outside of bounds 0..#{length - 1}" end ptr = GirFFI::InOutPointer.new element_type, data_ptr + idx * element_size ptr.to_ruby_value end
ruby
{ "resource": "" }
q19252
Rack.Tracer.call
train
def call(env) method = env[REQUEST_METHOD] context = @tracer.extract(OpenTracing::FORMAT_RACK, env) if @trust_incoming_span scope = @tracer.start_active_span( method, child_of: context, tags: { 'component' => 'rack', 'span.kind' => 'server', 'http...
ruby
{ "resource": "" }
q19253
Minimart.Cli.mirror
train
def mirror Minimart::Commands::Mirror.new(options).execute! rescue Minimart::Error::BaseError => e Minimart::Error.handle_exception(e) end
ruby
{ "resource": "" }
q19254
Minimart.Cli.web
train
def web Minimart::Commands::Web.new(options).execute! rescue Minimart::Error::BaseError => e Minimart::Error.handle_exception(e) end
ruby
{ "resource": "" }
q19255
EM::FTPD.Authentication.cmd_pass
train
def cmd_pass(param) send_response "202 User already logged in" and return unless @user.nil? send_param_required and return if param.nil? send_response "530 password with no username" and return if @requested_user.nil? # return an error message if: # - the specified username isn't in our ...
ruby
{ "resource": "" }
q19256
EM::FTPD.Files.cmd_dele
train
def cmd_dele(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? path = build_path(param) @driver.delete_file(path) do |result| if result send_response "250 File deleted" else send_action_not_taken end ...
ruby
{ "resource": "" }
q19257
EM::FTPD.Files.cmd_retr
train
def cmd_retr(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? path = build_path(param) @driver.get_file(path) do |data| if data send_response "150 Data transfer starting #{data.size} bytes" send_outofband_data(data, ...
ruby
{ "resource": "" }
q19258
EM::FTPD.Files.cmd_size
train
def cmd_size(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? @driver.bytes(build_path(param)) do |bytes| if bytes send_response "213 #{bytes}" else send_response "450 file not available" end end e...
ruby
{ "resource": "" }
q19259
EM::FTPD.Files.cmd_stor
train
def cmd_stor(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? path = build_path(param) if @driver.respond_to?(:put_file_streamed) cmd_stor_streamed(path) elsif @driver.respond_to?(:put_file) cmd_stor_tempfile(path) e...
ruby
{ "resource": "" }
q19260
EM::FTPD.Directories.cmd_nlst
train
def cmd_nlst(param) send_unauthorised and return unless logged_in? send_response "150 Opening ASCII mode data connection for file list" @driver.dir_contents(build_path(param)) do |files| send_outofband_data(files.map(&:name)) end end
ruby
{ "resource": "" }
q19261
EM::FTPD.Directories.cmd_list
train
def cmd_list(param) send_unauthorised and return unless logged_in? send_response "150 Opening ASCII mode data connection for file list" param = '' if param.to_s == '-a' @driver.dir_contents(build_path(param)) do |files| now = Time.now lines = files.map { |item| sizest...
ruby
{ "resource": "" }
q19262
EM::FTPD.Directories.cmd_rmd
train
def cmd_rmd(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? @driver.delete_dir(build_path(param)) do |result| if result send_response "250 Directory deleted." else send_action_not_taken end end en...
ruby
{ "resource": "" }
q19263
EM::FTPD.Server.parse_request
train
def parse_request(data) data.strip! space = data.index(" ") if space cmd = data[0, space] param = data[space+1, data.length - space] param = nil if param.strip.size == 0 else cmd = data param = nil end [cmd.downcase, param] end
ruby
{ "resource": "" }
q19264
EM::FTPD.Server.cmd_help
train
def cmd_help(param) send_response "214- The following commands are recognized." commands = COMMANDS str = "" commands.sort.each_slice(3) { |slice| str += " " + slice.join("\t\t") + LBRK } send_response str, true send_response "214 End of list." end
ruby
{ "resource": "" }
q19265
EM::FTPD.Server.cmd_pasv
train
def cmd_pasv(param) send_unauthorised and return unless logged_in? host, port = start_passive_socket p1, p2 = *port.divmod(256) send_response "227 Entering Passive Mode (" + host.split(".").join(",") + ",#{p1},#{p2})" end
ruby
{ "resource": "" }
q19266
EM::FTPD.Server.cmd_port
train
def cmd_port(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? nums = param.split(',') port = nums[4].to_i * 256 + nums[5].to_i host = nums[0..3].join('.') close_datasocket puts "connecting to client #{host} on #{port}" @...
ruby
{ "resource": "" }
q19267
EM::FTPD.Server.cmd_type
train
def cmd_type(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? if param.upcase.eql?("A") send_response "200 Type set to ASCII" elsif param.upcase.eql?("I") send_response "200 Type set to binary" else send_response "50...
ruby
{ "resource": "" }
q19268
EM::FTPD.Server.send_outofband_data
train
def send_outofband_data(data, restart_pos = 0) wait_for_datasocket do |datasocket| if datasocket.nil? send_response "425 Error establishing connection" else if data.is_a?(Array) data = data.join(LBRK) << LBRK end data = StringIO.new(data) if data...
ruby
{ "resource": "" }
q19269
EM::FTPD.Server.wait_for_datasocket
train
def wait_for_datasocket(interval = 0.1, &block) if @datasocket.nil? && interval < 25 if EM.reactor_running? EventMachine.add_timer(interval) { wait_for_datasocket(interval * 2, &block) } else sleep interval wait_for_datasocket(interval * 2, &block) end ...
ruby
{ "resource": "" }
q19270
EM::FTPD.Server.receive_outofband_data
train
def receive_outofband_data(&block) wait_for_datasocket do |datasocket| if datasocket.nil? send_response "425 Error establishing connection" yield false else # let the client know we're ready to start send_response "150 Data transfer starting" dat...
ruby
{ "resource": "" }
q19271
CensusApi.Client.where
train
def where(options={}) options.merge!(key: @api_key, vintage: @api_vintage) fail "Client requires a dataset (#{DATASETS})." if @dataset.nil? [:fields, :level].each do |f| fail ArgumentError, "#{f} is a requied parameter" if options[f].nil? end options[:within] = [options[:within]] u...
ruby
{ "resource": "" }
q19272
DNSBL.Client.add_dnsbl
train
def add_dnsbl(name,domain,type='ip',codes={"0"=>"OK","127.0.0.2"=>"Blacklisted"}) @dnsbls[name] = codes @dnsbls[name]['domain'] = domain @dnsbls[name]['type'] = type end
ruby
{ "resource": "" }
q19273
DNSBL.Client._encode_query
train
def _encode_query(item,itemtype,domain,apikey=nil) label = nil if itemtype == 'ip' label = item.split(/\./).reverse.join(".") elsif itemtype == 'domain' label = normalize(item) end lookup = "#{label}.#{domain}" if apikey lookup = "#{apikey}.#{lookup}" end txid = lookup.sum message...
ruby
{ "resource": "" }
q19274
DNSBL.Client.lookup
train
def lookup(item) # if item is an array, use it, otherwise make it one items = item if item.is_a? String items = [item] end # place the results in the results array results = [] # for each ip or hostname items.each do |item| # sent is used to determine when we have all the answers sen...
ruby
{ "resource": "" }
q19275
DNSBL.Client._decode_response
train
def _decode_response(buf) reply = Resolv::DNS::Message.decode(buf) results = [] reply.each_answer do |name,ttl,data| if name.to_s =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(.+)$/ ip = [$4,$3,$2,$1].join(".") domain = $5 @dnsbls.each do |dnsblname, config| next unless data.is_a? ...
ruby
{ "resource": "" }
q19276
DNSBL.Client.__phpot_decoder
train
def __phpot_decoder(ip) octets = ip.split(/\./) if octets.length != 4 or octets[0] != "127" return "invalid response" elsif octets[3] == "0" search_engines = ["undocumented", "AltaVista", "Ask", "Baidu", "Excite", "Google", "Looksmart", "Lycos", "MSN", "Yahoo", "Cuil", "InfoSeek", "Miscellaneous"] ...
ruby
{ "resource": "" }
q19277
Flt.Support.FlagValues
train
def FlagValues(*params) if params.size==1 && params.first.kind_of?(FlagValues) params.first else FlagValues.new(*params) end end
ruby
{ "resource": "" }
q19278
Flt.Support.Flags
train
def Flags(*params) if params.size==1 && params.first.kind_of?(Flags) params.first else Flags.new(*params) end end
ruby
{ "resource": "" }
q19279
Flt.Tolerance.integer
train
def integer(x) # return integer?(x) ? x.round : nil r = x.round ((x-r).abs <= relative_to(x)) ? r : nil end
ruby
{ "resource": "" }
q19280
Gopher.DSL.mount
train
def mount(path, opts = {}) route, folder = path.first # # if path has more than the one option (:route => :folder), # then incorporate the rest of the hash into our opts # if path.size > 1 other_opts = path.dup other_opts.delete(route) opts = opts.merge(other...
ruby
{ "resource": "" }
q19281
Gopher.Response.size
train
def size case self.body when String then self.body.length when StringIO then self.body.length when File then self.body.size else 0 end end
ruby
{ "resource": "" }
q19282
Gopher.Server.run!
train
def run! EventMachine::run do Signal.trap("INT") { puts "It's a trap!" EventMachine.stop } Signal.trap("TERM") { puts "It's a trap!" EventMachine.stop } EventMachine.kqueue = true if EventMachine.kqueue? EventMachine.epoll = ...
ruby
{ "resource": "" }
q19283
Gopher.Application.should_reload?
train
def should_reload? ! last_reload.nil? && self.scripts.any? do |f| File.mtime(f) > last_reload end end
ruby
{ "resource": "" }
q19284
Gopher.Application.reload_stale
train
def reload_stale reload_check = should_reload? self.last_reload = Time.now return if ! reload_check reset! self.scripts.each do |f| debug_log "reload #{f}" load f end end
ruby
{ "resource": "" }
q19285
Gopher.Application.mount
train
def mount(path, opts = {}, klass = Gopher::Handlers::DirectoryHandler) debug_log "MOUNT #{path} #{opts.inspect}" opts[:mount_point] = path handler = klass.new(opts) handler.application = self # # add a route for the mounted class # route(globify(path)) do # when...
ruby
{ "resource": "" }
q19286
Gopher.Application.lookup
train
def lookup(selector) unless routes.nil? routes.each do |pattern, keys, block| if match = pattern.match(selector) match = match.to_a url = match.shift params = to_params_hash(keys, match) # # @todo think about this # ...
ruby
{ "resource": "" }
q19287
Gopher.Application.dispatch
train
def dispatch(req) debug_log(req) response = Response.new @request = req if ! @request.valid? response.body = handle_invalid_request response.code = :error else begin debug_log("do lookup for #{@request.selector}") @params, block = lookup(@reque...
ruby
{ "resource": "" }
q19288
Gopher.Application.find_template
train
def find_template(t) x = menus[t] if x return x, Gopher::Rendering::Menu end x = text_templates[t] if x return x, Gopher::Rendering::Text end end
ruby
{ "resource": "" }
q19289
Gopher.Application.render
train
def render(template, *arguments) # # find the right renderer we need # block, handler = find_template(template) raise TemplateNotFound if block.nil? ctx = handler.new(self) ctx.params = @params ctx.request = @request ctx.instance_exec(*arguments, &block) end
ruby
{ "resource": "" }
q19290
Gopher.Application.compile!
train
def compile!(path, &block) method_name = path route_method = Application.generate_method(method_name, &block) pattern, keys = compile path [ pattern, keys, route_method ] end
ruby
{ "resource": "" }
q19291
Gopher.Application.init_access_log
train
def init_access_log return if access_log_dest.nil? log = ::Logging.logger['access_log'] pattern = ::Logging.layouts.pattern(:pattern => ACCESS_LOG_PATTERN) log.add_appenders( ::Logging.appenders.rolling_file(access_log_dest, :level => :debug, :age => 'daily', ...
ruby
{ "resource": "" }
q19292
Gopher.Application.access_log
train
def access_log(request, response) return if access_log_dest.nil? @@access_logger ||= init_access_log code = response.respond_to?(:code) ? response.code.to_s : "success" size = response.respond_to?(:size) ? response.size : response.length output = [request.ip_address, request.selector, req...
ruby
{ "resource": "" }
q19293
Gopher.Application.to_params_hash
train
def to_params_hash(keys,values) hash = {} keys.size.times { |i| hash[ keys[i].to_sym ] = values[i] } hash end
ruby
{ "resource": "" }
q19294
Gopher.Dispatcher.call!
train
def call!(request) operation = proc { app.dispatch(request) } callback = proc {|result| send_response result close_connection_after_writing } # # if we don't want to block on slow calls, use EM#defer # @see http://eventmachine.rubyforge.org/EventMachine...
ruby
{ "resource": "" }
q19295
Gopher.Dispatcher.send_response
train
def send_response(response) case response when Gopher::Response then send_response(response.body) when String then send_data(response + end_of_transmission) when StringIO then send_data(response.read + end_of_transmission) when File while chunk = response.read(8192) do se...
ruby
{ "resource": "" }
q19296
Appsignal.AuthCheck.perform_with_result
train
def perform_with_result status = perform result = case status when "200" "AppSignal has confirmed authorization!" when "401" "API key not valid with AppSignal..." else "Could not confirm authorization: " \ "#{status.nil? ? "nil" : sta...
ruby
{ "resource": "" }
q19297
Appsignal.Config.maintain_backwards_compatibility
train
def maintain_backwards_compatibility(configuration) configuration.tap do |config| DEPRECATED_CONFIG_KEY_MAPPING.each do |old_key, new_key| old_config_value = config.delete(old_key) next unless old_config_value deprecation_message \ "Old configuration key found. Pl...
ruby
{ "resource": "" }
q19298
Appsignal.Transaction.background_queue_start
train
def background_queue_start env = environment return unless env queue_start = env[:queue_start] return unless queue_start (queue_start.to_f * 1000.0).to_i end
ruby
{ "resource": "" }
q19299
Appsignal.Transaction.http_queue_start
train
def http_queue_start env = environment return unless env env_var = env["HTTP_X_QUEUE_START".freeze] || env["HTTP_X_REQUEST_START".freeze] return unless env_var cleaned_value = env_var.tr("^0-9".freeze, "".freeze) return if cleaned_value.empty? value = cleaned_value.to_i ...
ruby
{ "resource": "" }