_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q22700
Openapi3Parser.Document.errors
train
def errors reference_factories.inject(factory.errors) do |memo, f| Validation::ErrorCollection.combine(memo, f.errors) end end
ruby
{ "resource": "" }
q22701
Openapi3Parser.Source.register_reference
train
def register_reference(given_reference, factory, context) reference = Reference.new(given_reference) ReferenceResolver.new( reference, factory, context ).tap do |resolver| next if resolver.in_root_source? reference_register.register(resolver.reference_factory) end end
ruby
{ "resource": "" }
q22702
Openapi3Parser.Source.data_at_pointer
train
def data_at_pointer(json_pointer) return data if json_pointer.empty? data.dig(*json_pointer) if data.respond_to?(:dig) end
ruby
{ "resource": "" }
q22703
Blogo.Paginator.pages
train
def pages @pages ||= begin from = @page - (@size / 2).ceil from = 1 if from < 1 upto = from + @size - 1 # Correct +from+ and +to+ if +to+ is more than number of pages if upto > pages_count from -= (upto - pages_count) from = 1 if from < 1 upto = pages_count end (from..upto).to_a end end
ruby
{ "resource": "" }
q22704
Danger.DangerMention.run
train
def run(max_reviewers = 3, file_blacklist = [], user_blacklist = []) files = select_files(file_blacklist) return if files.empty? authors = {} compose_urls(files).each do |url| result = parse_blame(url) authors.merge!(result) { |_, m, n| m + n } end reviewers = find_reviewers(authors, user_blacklist, max_reviewers) if reviewers.count > 0 reviewers = reviewers.map { |r| '@' + r } result = format('By analyzing the blame information on this pull '\ 'request, we identified %s to be potential reviewer%s.', reviewers.join(', '), reviewers.count > 1 ? 's' : '') markdown result end end
ruby
{ "resource": "" }
q22705
LinkedList.List.push
train
def push(node) node = Node(node) @head ||= node if @tail @tail.next = node node.prev = @tail end @tail = node @length += 1 self end
ruby
{ "resource": "" }
q22706
LinkedList.List.unshift
train
def unshift(node) node = Node(node) @tail ||= node node.next = @head @head.prev = node if @head @head = node @length += 1 self end
ruby
{ "resource": "" }
q22707
LinkedList.List.insert
train
def insert(to_add, after: nil, before: nil) if after && before || !after && !before raise ArgumentError, 'either :after or :before keys should be passed' end matcher = after || before matcher_proc = if matcher.is_a?(Proc) __to_matcher(&matcher) else __to_matcher(matcher) end node = each_node.find(&matcher_proc) return unless node new_node = after ? insert_after_node(to_add, node) : insert_before_node(to_add, node) new_node.data end
ruby
{ "resource": "" }
q22708
LinkedList.List.insert_after_node
train
def insert_after_node(data, node) Node(data).tap do |new_node| new_node.prev = node new_node.next = node.next if node.next node.next.prev = new_node else @tail = new_node end node.next = new_node @length += 1 end end
ruby
{ "resource": "" }
q22709
LinkedList.List.insert_before_node
train
def insert_before_node(data, node) Node(data).tap do |new_node| new_node.next = node new_node.prev = node.prev if node.prev node.prev.next = new_node else @head = new_node end node.prev = new_node @length += 1 end end
ruby
{ "resource": "" }
q22710
LinkedList.List.delete
train
def delete(val = nil, &block) if val.respond_to?(:to_node) node = val.to_node __unlink_node(node) return node.data end each_node.find(&__to_matcher(val, &block)).tap do |node_to_delete| return unless node_to_delete __unlink_node(node_to_delete) end.data end
ruby
{ "resource": "" }
q22711
LinkedList.List.delete_all
train
def delete_all(val = nil, &block) each_node.select(&__to_matcher(val, &block)).each do |node_to_delete| next unless node_to_delete __unlink_node(node_to_delete) end.map(&:data) end
ruby
{ "resource": "" }
q22712
Merb.SessionStoreContainer.regenerate
train
def regenerate store.delete_session(self.session_id) self.session_id = Merb::SessionMixin.rand_uuid store.store_session(self.session_id, self) end
ruby
{ "resource": "" }
q22713
Generators.ContextUser.collect_methods
train
def collect_methods list = @context.method_list unless @options.show_all list = list.find_all {|m| m.visibility == :public || m.visibility == :protected || m.force_documentation } end @methods = list.collect {|m| HtmlMethod.new(m, self, @options) } end
ruby
{ "resource": "" }
q22714
Generators.HtmlMethod.markup_code
train
def markup_code(tokens) src = "" tokens.each do |t| next unless t # p t.class # style = STYLE_MAP[t.class] style = case t when RubyToken::TkCONSTANT then "ruby-constant" when RubyToken::TkKW then "ruby-keyword kw" when RubyToken::TkIVAR then "ruby-ivar" when RubyToken::TkOp then "ruby-operator" when RubyToken::TkId then "ruby-identifier" when RubyToken::TkNode then "ruby-node" when RubyToken::TkCOMMENT then "ruby-comment cmt" when RubyToken::TkREGEXP then "ruby-regexp re" when RubyToken::TkSTRING then "ruby-value str" when RubyToken::TkVal then "ruby-value" else nil end text = CGI.escapeHTML(t.text) if style src << "<span class=\"#{style}\">#{text}</span>" else src << text end end add_line_numbers(src) src end
ruby
{ "resource": "" }
q22715
Merb.Mailer.net_smtp
train
def net_smtp smtp = Net::SMTP.new(config[:host], config[:port].to_i) if config[:tls] if smtp.respond_to?(:enable_starttls) # 1.9.x smtp.enable_starttls elsif smtp.respond_to?(:enable_tls) && smtp.respond_to?(:use_tls?) smtp.enable_tls(OpenSSL::SSL::VERIFY_NONE) # 1.8.x with tlsmail else raise 'Unable to enable TLS, for Ruby 1.8.x install tlsmail' end end smtp.start(config[:domain], config[:user], config[:pass], config[:auth]) { |smtp| to = @mail.to.is_a?(String) ? @mail.to.split(/[,;]/) : @mail.to smtp.send_message(@mail.to_s, @mail.from.first, to) } end
ruby
{ "resource": "" }
q22716
Merb.Worker.process_queue
train
def process_queue begin while blk = Merb::Dispatcher.work_queue.pop # we've been blocking on the queue waiting for an item sleeping. # when someone pushes an item it wakes up this thread so we # immediately pass execution to the scheduler so we don't # accidentally run this block before the action finishes # it's own processing Thread.pass blk.call break if Merb::Dispatcher.work_queue.empty? && Merb.exiting end rescue Exception => e Merb.logger.warn! %Q!Worker Thread Crashed with Exception:\n#{Merb.exception(e)}\nRestarting Worker Thread! retry end end
ruby
{ "resource": "" }
q22717
Merb.Request.handle
train
def handle @start = env["merb.request_start"] = Time.now Merb.logger.info { "Started request handling: #{start.to_s}" } find_route! return rack_response if handled? klass = controller Merb.logger.debug { "Routed to: #{klass::_filter_params(params).inspect}" } unless klass < Controller raise NotFound, "Controller '#{klass}' not found.\n" \ "If Merb tries to find a controller for static files, " \ "you may need to check your Rackup file, see the Problems " \ "section at: http://wiki.merbivore.com/pages/rack-middleware" end if klass.abstract? raise NotFound, "The '#{klass}' controller has no public actions" end dispatch_action(klass, params[:action]) rescue Object => exception dispatch_exception(exception) end
ruby
{ "resource": "" }
q22718
Merb.Request.dispatch_action
train
def dispatch_action(klass, action_name, status=200) @env["merb.status"] = status @env["merb.action_name"] = action_name if Dispatcher.use_mutex @@mutex.synchronize { klass.call(env) } else klass.call(env) end end
ruby
{ "resource": "" }
q22719
Merb.Request.dispatch_exception
train
def dispatch_exception(exception) if(exception.is_a?(Merb::ControllerExceptions::Base) && !exception.is_a?(Merb::ControllerExceptions::ServerError)) Merb.logger.info(Merb.exception(exception)) else Merb.logger.error(Merb.exception(exception)) end exceptions = env["merb.exceptions"] = [exception] begin e = exceptions.first if action_name = e.action_name dispatch_action(Exceptions, action_name, e.class.status) else dispatch_action(Dispatcher::DefaultException, :index, e.class.status) end rescue Object => dispatch_issue if e.same?(dispatch_issue) || exceptions.size > 5 dispatch_action(Dispatcher::DefaultException, :index, e.class.status) else Merb.logger.error("Dispatching #{e.class} raised another error.") Merb.logger.error(Merb.exception(dispatch_issue)) exceptions.unshift dispatch_issue retry end end end
ruby
{ "resource": "" }
q22720
Merb.ControllerMixin.render_chunked
train
def render_chunked(&blk) must_support_streaming! headers['Transfer-Encoding'] = 'chunked' Proc.new { |response| @response = response response.send_status_no_connection_close('') response.send_header blk.call response.write("0\r\n\r\n") } end
ruby
{ "resource": "" }
q22721
Merb.ControllerMixin.render_then_call
train
def render_then_call(str, &blk) Proc.new do |response| response.write(str) blk.call end end
ruby
{ "resource": "" }
q22722
Merb.ControllerMixin.send_file
train
def send_file(file, opts={}) opts.update(Merb::Const::DEFAULT_SEND_FILE_OPTIONS.merge(opts)) disposition = opts[:disposition].dup || 'attachment' disposition << %(; filename="#{opts[:filename] ? opts[:filename] : File.basename(file)}") headers.update( 'Content-Type' => opts[:type].strip, # fixes a problem with extra '\r' with some browsers 'Content-Disposition' => disposition, 'Content-Transfer-Encoding' => 'binary' ) Proc.new do |response| file = File.open(file, 'rb') while chunk = file.read(16384) response.write chunk end file.close end end
ruby
{ "resource": "" }
q22723
Merb.ControllerMixin.send_data
train
def send_data(data, opts={}) opts.update(Merb::Const::DEFAULT_SEND_FILE_OPTIONS.merge(opts)) disposition = opts[:disposition].dup || 'attachment' disposition << %(; filename="#{opts[:filename]}") if opts[:filename] headers.update( 'Content-Type' => opts[:type].strip, # fixes a problem with extra '\r' with some browsers 'Content-Disposition' => disposition, 'Content-Transfer-Encoding' => 'binary' ) data end
ruby
{ "resource": "" }
q22724
Merb.ControllerMixin.stream_file
train
def stream_file(opts={}, &stream) opts.update(Merb::Const::DEFAULT_SEND_FILE_OPTIONS.merge(opts)) disposition = opts[:disposition].dup || 'attachment' disposition << %(; filename="#{opts[:filename]}") headers.update( 'Content-Type' => opts[:type].strip, # fixes a problem with extra '\r' with some browsers 'Content-Disposition' => disposition, 'Content-Transfer-Encoding' => 'binary', # Rack specification requires header values to respond to :each 'CONTENT-LENGTH' => opts[:content_length].to_s ) Proc.new do |response| stream.call(response) end end
ruby
{ "resource": "" }
q22725
Merb.ControllerMixin.set_cookie
train
def set_cookie(name, value, expires) options = expires.is_a?(Hash) ? expires : {:expires => expires} cookies.set_cookie(name, value, options) end
ruby
{ "resource": "" }
q22726
Merb.ControllerMixin.handle_redirect_messages
train
def handle_redirect_messages(url, opts={}) opts = opts.dup # check opts for message shortcut keys (and assign them to message) [:notice, :error, :success].each do |message_key| if opts[message_key] opts[:message] ||= {} opts[:message][message_key] = opts[message_key] end end # append message query param if message is passed if opts[:message] notice = Merb::Parse.escape([Marshal.dump(opts[:message])].pack("m")) u = ::URI.parse(url) u.query = u.query ? "#{u.query}&_message=#{notice}" : "_message=#{notice}" url = u.to_s end url end
ruby
{ "resource": "" }
q22727
Merb.AbstractController._call_filters
train
def _call_filters(filter_set) (filter_set || []).each do |filter, rule| if _call_filter_for_action?(rule, action_name) && _filter_condition_met?(rule) case filter when Symbol, String if rule.key?(:with) args = rule[:with] send(filter, *args) else send(filter) end when Proc then self.instance_eval(&filter) end end end return :filter_chain_completed end
ruby
{ "resource": "" }
q22728
Merb.AbstractController.absolute_url
train
def absolute_url(*args) # FIXME: arrgh, why request.protocol returns http://? # :// is not part of protocol name options = extract_options_from_args!(args) || {} protocol = options.delete(:protocol) host = options.delete(:host) raise ArgumentError, "The :protocol option must be specified" unless protocol raise ArgumentError, "The :host option must be specified" unless host args << options protocol + "://" + host + url(*args) end
ruby
{ "resource": "" }
q22729
Merb.AbstractController.capture
train
def capture(*args, &block) ret = nil captured = send("capture_#{@_engine}", *args) do |*args| ret = yield *args end # return captured value only if it is not empty captured.empty? ? ret.to_s : captured end
ruby
{ "resource": "" }
q22730
MerbExceptions.ExceptionsHelper.notify_of_exceptions
train
def notify_of_exceptions if Merb::Plugins.config[:exceptions][:environments].include?(Merb.env) begin request = self.request details = {} details['exceptions'] = request.exceptions details['params'] = params details['params'] = self.class._filter_params(params) details['environment'] = request.env.merge( 'process' => $$ ) details['url'] = "#{request.protocol}#{request.env["HTTP_HOST"]}#{request.uri}" MerbExceptions::Notification.new(details).deliver! rescue Exception => e exceptions = request.exceptions << e Merb.logger.fatal!("Exception Notification Failed:\n" + (exceptions).inspect) File.open(Merb.root / 'log' / 'notification_errors.log', 'a') do |log| log.puts("Exception Notification Failed:") exceptions.each do |e| log.puts(Merb.exception(e)) end end end end end
ruby
{ "resource": "" }
q22731
Merb::Cache.FileStore.writable?
train
def writable?(key, parameters = {}, conditions = {}) case key when String, Numeric, Symbol !conditions.has_key?(:expire_in) else nil end end
ruby
{ "resource": "" }
q22732
Merb::Cache.FileStore.read
train
def read(key, parameters = {}) if exists?(key, parameters) read_file(pathify(key, parameters)) end end
ruby
{ "resource": "" }
q22733
Merb::Cache.FileStore.write
train
def write(key, data = nil, parameters = {}, conditions = {}) if writable?(key, parameters, conditions) if File.file?(path = pathify(key, parameters)) write_file(path, data) else create_path(path) && write_file(path, data) end end end
ruby
{ "resource": "" }
q22734
Merb::Cache.FileStore.fetch
train
def fetch(key, parameters = {}, conditions = {}, &blk) read(key, parameters) || (writable?(key, parameters, conditions) && write(key, value = blk.call, parameters, conditions) && value) end
ruby
{ "resource": "" }
q22735
Merb::Cache.FileStore.read_file
train
def read_file(path) data = nil File.open(path, "r") do |file| file.flock(File::LOCK_EX) data = file.read file.flock(File::LOCK_UN) end data end
ruby
{ "resource": "" }
q22736
Merb::Cache.FileStore.write_file
train
def write_file(path, data) File.open(path, "w+") do |file| file.flock(File::LOCK_EX) file.write(data) file.flock(File::LOCK_UN) end true end
ruby
{ "resource": "" }
q22737
Merb::Cache.AdhocStore.write
train
def write(key, data = nil, parameters = {}, conditions = {}) @stores.capture_first {|s| s.write(key, data, parameters, conditions)} end
ruby
{ "resource": "" }
q22738
Merb::Cache.AdhocStore.write_all
train
def write_all(key, data = nil, parameters = {}, conditions = {}) @stores.map {|s| s.write_all(key, data, parameters, conditions)}.all? end
ruby
{ "resource": "" }
q22739
Merb::Cache.AdhocStore.fetch
train
def fetch(key, parameters = {}, conditions = {}, &blk) read(key, parameters) || @stores.capture_first {|s| s.fetch(key, parameters, conditions, &blk)} || blk.call end
ruby
{ "resource": "" }
q22740
Merb::Cache.AdhocStore.delete
train
def delete(key, parameters = {}) @stores.map {|s| s.delete(key, parameters)}.any? end
ruby
{ "resource": "" }
q22741
Merb.Authentication.user=
train
def user=(user) session[:user] = nil && return if user.nil? session[:user] = store_user(user) @user = session[:user] ? user : session[:user] end
ruby
{ "resource": "" }
q22742
Merb.Authentication.authenticate!
train
def authenticate!(request, params, *rest) opts = rest.last.kind_of?(Hash) ? rest.pop : {} rest = rest.flatten strategies = if rest.empty? if request.session[:authentication_strategies] request.session[:authentication_strategies] else Merb::Authentication.default_strategy_order end else request.session[:authentication_strategies] ||= [] request.session[:authentication_strategies] << rest request.session[:authentication_strategies].flatten!.uniq! request.session[:authentication_strategies] end msg = opts[:message] || error_message user = nil # This one should find the first one that matches. It should not run antother strategies.detect do |s| s = Merb::Authentication.lookup_strategy[s] # Get the strategy from string or class unless s.abstract? strategy = s.new(request, params) user = strategy.run! if strategy.halted? self.headers, self.status, self.body = [strategy.headers, strategy.status, strategy.body] halt! return end user end end # Check after callbacks to make sure the user is still cool user = run_after_authentication_callbacks(user, request, params) if user # Finally, Raise an error if there is no user found, or set it in the session if there is. raise Merb::Controller::Unauthenticated, msg unless user session[:authentication_strategies] = nil # clear the session of Failed Strategies if login is successful self.user = user end
ruby
{ "resource": "" }
q22743
Merb.Cookies.extract_headers
train
def extract_headers(controller_defaults = {}) defaults = @_cookie_defaults.merge(controller_defaults) cookies = [] self.each do |name, value| # Only set cookies that marked for inclusion in the response header. next unless @_options_lookup[name] options = defaults.merge(@_options_lookup[name]) if (expiry = options["expires"]).respond_to?(:gmtime) options["expires"] = expiry.gmtime.strftime(Merb::Const::COOKIE_EXPIRATION_FORMAT) end secure = options.delete("secure") http_only = options.delete("http_only") kookie = "#{name}=#{Merb::Parse.escape(value)}; " # WebKit in particular doens't like empty cookie options - skip them. options.each { |k, v| kookie << "#{k}=#{v}; " unless v.blank? } kookie << 'secure; ' if secure kookie << 'HttpOnly; ' if http_only cookies << kookie.rstrip end cookies.empty? ? {} : { 'Set-Cookie' => cookies } end
ruby
{ "resource": "" }
q22744
Merb::Cache.MemcachedStore.read
train
def read(key, parameters = {}) begin @memcached.get(normalize(key, parameters)) rescue Memcached::NotFound, Memcached::Stored nil end end
ruby
{ "resource": "" }
q22745
Merb::Cache.MemcachedStore.write
train
def write(key, data = nil, parameters = {}, conditions = {}) if writable?(key, parameters, conditions) begin @memcached.set(normalize(key, parameters), data, expire_time(conditions)) true rescue nil end end end
ruby
{ "resource": "" }
q22746
Merb.AssetsMixin.extract_required_files
train
def extract_required_files(files, options = {}) return [] if files.nil? || files.empty? seen = [] files.inject([]) do |extracted, req_js| include_files, include_options = if req_js.last.is_a?(Hash) [req_js[0..-2], options.merge(req_js.last)] else [req_js, options] end seen += (includes = include_files - seen) extracted << (includes + [include_options]) unless includes.empty? extracted end end
ruby
{ "resource": "" }
q22747
Merb.MemorySessionStore.reap_expired_sessions
train
def reap_expired_sessions @timestamps.each do |session_id,stamp| delete_session(session_id) if (stamp + @session_ttl) < Time.now end GC.start end
ruby
{ "resource": "" }
q22748
Merb.CookieSession.to_cookie
train
def to_cookie unless self.empty? data = self.serialize value = Merb::Parse.escape "#{data}--#{generate_digest(data)}" if value.size > MAX msg = "Cookies have limit of 4K. Session contents: #{data.inspect}" Merb.logger.error!(msg) raise CookieOverflow, msg end value end end
ruby
{ "resource": "" }
q22749
Merb.CookieSession.secure_compare
train
def secure_compare(a, b) if a.length == b.length # unpack to forty characters. # needed for 1.8 and 1.9 compat a_bytes = a.unpack('C*') b_bytes = b.unpack('C*') result = 0 for i in 0..(a_bytes.length - 1) result |= a_bytes[i] ^ b_bytes[i] end result == 0 else false end end
ruby
{ "resource": "" }
q22750
Merb.CookieSession.unmarshal
train
def unmarshal(cookie) if cookie.blank? {} else data, digest = Merb::Parse.unescape(cookie).split('--') return {} if data.blank? || digest.blank? unless secure_compare(generate_digest(data), digest) clear unless Merb::Config[:ignore_tampered_cookies] raise TamperedWithCookie, "Maybe the site's session_secret_key has changed?" end end unserialize(data) end end
ruby
{ "resource": "" }
q22751
Merb.Request.controller
train
def controller unless params[:controller] raise ControllerExceptions::NotFound, "Route matched, but route did not specify a controller.\n" + "Did you forgot to add :controller => \"people\" or :controller " + "segment to route definition?\nHere is what's specified:\n" + route.inspect end path = [params[:namespace], params[:controller]].compact.join(Merb::Const::SLASH) controller = path.snake_case.to_const_string begin Object.full_const_get(controller) rescue NameError => e msg = "Controller class not found for controller `#{path}'" Merb.logger.warn!(msg) raise ControllerExceptions::NotFound, msg end end
ruby
{ "resource": "" }
q22752
Merb.Request.body_params
train
def body_params @body_params ||= begin if content_type && content_type.match(Merb::Const::FORM_URL_ENCODED_REGEXP) # or content_type.nil? Merb::Parse.query(raw_post) end end end
ruby
{ "resource": "" }
q22753
Merb.AuthenticatedHelper.ensure_authenticated
train
def ensure_authenticated(*strategies) session.authenticate!(request, params, *strategies) unless session.authenticated? auth = session.authentication if auth.halted? self.headers.merge!(auth.headers) self.status = auth.status throw :halt, auth.body end session.user end
ruby
{ "resource": "" }
q22754
MultipartParser.Parser.callback
train
def callback(event, buffer = nil, start = nil, the_end = nil) return if !start.nil? && start == the_end if @callbacks.has_key? event @callbacks[event].call(buffer, start, the_end) end end
ruby
{ "resource": "" }
q22755
Merb.ResponderMixin.content_type=
train
def content_type=(type) unless Merb.available_mime_types.has_key?(type) raise Merb::ControllerExceptions::NotAcceptable.new("Unknown content_type for response: #{type}") end @_content_type = type mime = Merb.available_mime_types[type] headers["Content-Type"] = mime[:content_type] # merge any format specific response headers mime[:response_headers].each { |k,v| headers[k] ||= v } # if given, use a block to finetune any runtime headers mime[:response_block].call(self) if mime[:response_block] @_content_type end
ruby
{ "resource": "" }
q22756
Merb.MailController.render_mail
train
def render_mail(options = @method) @_missing_templates = false # used to make sure that at least one template was found # If the options are not a hash, normalize to an action hash options = {:action => {:html => options, :text => options}} if !options.is_a?(Hash) # Take care of the options opts_hash = {} opts = options.dup actions = opts.delete(:action) if opts[:action].is_a?(Hash) templates = opts.delete(:template) if opts[:template].is_a?(Hash) # Prepare the options hash for each format # We need to delete anything relating to the other format here # before we try to render the template. [:html, :text].each do |fmt| opts_hash[fmt] = opts.delete(fmt) opts_hash[fmt] ||= actions[fmt] if actions && actions[fmt] opts_hash[:template] = templates[fmt] if templates && templates[fmt] end # Send the result to the mailer { :html => "rawhtml=", :text => "text="}.each do |fmt,meth| begin local_opts = opts.merge(:format => fmt) local_opts.merge!(:layout => false) if opts_hash[fmt].is_a?(String) clear_content value = render opts_hash[fmt], local_opts @mail.send(meth,value) unless value.nil? || value.empty? rescue Merb::ControllerExceptions::TemplateNotFound => e # An error should be logged if no template is found instead of an error raised if @_missing_templates Merb.logger.error(e.message) else @_missing_templates = true end end end @mail end
ruby
{ "resource": "" }
q22757
Danger.DangerLgtm.check_lgtm
train
def check_lgtm(image_url: nil, https_image_only: false) return unless status_report[:errors].length.zero? && status_report[:warnings].length.zero? image_url ||= fetch_image_url(https_image_only: https_image_only) markdown( markdown_template(image_url) ) end
ruby
{ "resource": "" }
q22758
MARC.REXMLReader.each
train
def each unless block_given? return self.enum_for(:each) else while @parser.has_next? event = @parser.pull # if it's the start of a record element if event.start_element? and strip_ns(event[0]) == 'record' yield build_record end end end end
ruby
{ "resource": "" }
q22759
MARC.REXMLReader.build_record
train
def build_record record = MARC::Record.new data_field = nil control_field = nil subfield = nil text = '' attrs = nil if Module.constants.index('Nokogiri') and @parser.is_a?(Nokogiri::XML::Reader) datafield = nil cursor = nil open_elements = [] @parser.each do | node | if node.value? && cursor if cursor.is_a?(Symbol) and cursor == :leader record.leader = node.value else cursor.value = node.value end cursor = nil end next unless node.namespace_uri == @ns if open_elements.index(node.local_name.downcase) open_elements.delete(node.local_name.downcase) next else open_elements << node.local_name.downcase end case node.local_name.downcase when "leader" cursor = :leader when "controlfield" record << datafield if datafield datafield = nil control_field = MARC::ControlField.new(node.attribute('tag')) record << control_field cursor = control_field when "datafield" record << datafield if datafield datafield = nil data_field = MARC::DataField.new(node.attribute('tag'), node.attribute('ind1'), node.attribute('ind2')) datafield = data_field when "subfield" raise "No datafield to add to" unless datafield subfield = MARC::Subfield.new(node.attribute('code')) datafield.append(subfield) cursor = subfield when "record" record << datafield if datafield return record end #puts node.name end else while @parser.has_next? event = @parser.pull if event.text? text += REXML::Text::unnormalize(event[0]) next end if event.start_element? text = '' attrs = event[1] case strip_ns(event[0]) when 'controlfield' text = '' control_field = MARC::ControlField.new(attrs['tag']) when 'datafield' text = '' data_field = MARC::DataField.new(attrs['tag'], attrs['ind1'], attrs['ind2']) when 'subfield' text = '' subfield = MARC::Subfield.new(attrs['code']) end end if event.end_element? case strip_ns(event[0]) when 'leader' record.leader = text when 'record' return record when 'controlfield' control_field.value = text record.append(control_field) when 'datafield' record.append(data_field) when 'subfield' subfield.value = text data_field.append(subfield) end end end end end
ruby
{ "resource": "" }
q22760
Lgtm.ErrorHandleable.validate_response
train
def validate_response(response) case response when *SERVER_ERRORS raise ::Lgtm::Errors::UnexpectedError when *CLIENT_ERRORS raise ::Lgtm::Errors::UnexpectedError end end
ruby
{ "resource": "" }
q22761
MARC.FieldMap.reindex
train
def reindex @tags = {} self.each_with_index do |field, i| @tags[field.tag] ||= [] @tags[field.tag] << i end @clean = true end
ruby
{ "resource": "" }
q22762
MARC.Record.fields
train
def fields(filter=nil) unless filter # Since we're returning the FieldMap object, which the caller # may mutate, we precautionarily mark dirty -- unless it's frozen # immutable. @fields.clean = false unless @fields.frozen? return @fields end @fields.reindex unless @fields.clean flds = [] if filter.is_a?(String) && @fields.tags[filter] @fields.tags[filter].each do |idx| flds << @fields[idx] end elsif filter.is_a?(Array) || filter.is_a?(Range) @fields.each_by_tag(filter) do |tag| flds << tag end end flds end
ruby
{ "resource": "" }
q22763
Ribose.FileUploader.create
train
def create upload_meta = prepare_to_upload response = upload_to_aws_s3(upload_meta) notify_ribose_file_upload_endpoint(response, upload_meta.fields.key) end
ruby
{ "resource": "" }
q22764
Ribose.Request.request
train
def request(options = {}) parsable = extract_config_option(:parse) != false options[:query] = extract_config_option(:query) || {} response = agent.call(http_method, api_endpoint, data, options) parsable == true ? response.data : response end
ruby
{ "resource": "" }
q22765
MARC.DataField.to_hash
train
def to_hash field_hash = {@tag=>{'ind1'=>@indicator1,'ind2'=>@indicator2,'subfields'=>[]}} self.each do |subfield| field_hash[@tag]['subfields'] << {subfield.code=>subfield.value} end field_hash end
ruby
{ "resource": "" }
q22766
CacheQL.ResolveWrapper.call
train
def call(obj, args, ctx) cache_key = [CacheQL::Railtie.config.global_key, obj.cache_key, ctx.field.name] CacheQL::Railtie.config.cache.fetch(cache_key, expires_in: CacheQL::Railtie.config.expires_range.sample.minutes) do @resolver_func.call(obj, args, ctx) end end
ruby
{ "resource": "" }
q22767
Transflow.Transaction.call
train
def call(input, options = {}) handler = handler_steps(options).map(&method(:step)).reduce(:>>) handler.call(input) rescue StepError => err raise TransactionFailedError.new(self, err) end
ruby
{ "resource": "" }
q22768
Namey.Parser.create_table
train
def create_table(name) if ! db.tables.include?(name.to_sym) db.create_table name do String :name, :size => 15 Float :freq index :freq end end end
ruby
{ "resource": "" }
q22769
Namey.Parser.cleanup_surname
train
def cleanup_surname(name) if name.length > 4 name.gsub!(/^Mc(\w+)/) { |s| "Mc#{$1.capitalize}" } name.gsub!(/^Mac(\w+)/) { |s| "Mac#{$1.capitalize}" } name.gsub!(/^Mac(\w+)/) { |s| "Mac#{$1.capitalize}" } name.gsub!(/^Osh(\w+)/) { |s| "O'sh#{$1}" } name.gsub!(/^Van(\w+)/) { |s| "Van#{$1.capitalize}" } name.gsub!(/^Von(\w+)/) { |s| "Von#{$1.capitalize}" } # name.gsub!(/^Dev(\w+)/) { |s| "DeV#{$1}" } end name end
ruby
{ "resource": "" }
q22770
Hexdump.Dumper.each_word
train
def each_word(data,&block) return enum_for(:each_word,data) unless block unless data.respond_to?(:each_byte) raise(ArgumentError,"the data to hexdump must define #each_byte") end if @word_size > 1 word = 0 count = 0 init_shift = if @endian == :big ((@word_size - 1) * 8) else 0 end shift = init_shift data.each_byte do |b| word |= (b << shift) if @endian == :big shift -= 8 else shift += 8 end count += 1 if count >= @word_size yield word word = 0 count = 0 shift = init_shift end end # yield the remaining word yield word if count > 0 else data.each_byte(&block) end end
ruby
{ "resource": "" }
q22771
Hexdump.Dumper.each
train
def each(data) return enum_for(:each,data) unless block_given? index = 0 count = 0 numeric = [] printable = [] each_word(data) do |word| numeric << format_numeric(word) printable << format_printable(word) count += 1 if count >= @width yield index, numeric, printable numeric.clear printable.clear index += (@width * @word_size) count = 0 end end if count > 0 # yield the remaining data yield index, numeric, printable end end
ruby
{ "resource": "" }
q22772
Hexdump.Dumper.dump
train
def dump(data,output=$stdout) unless output.respond_to?(:<<) raise(ArgumentError,"output must support the #<< method") end bytes_segment_width = ((@width * @format_width) + @width) line_format = "%.8x %-#{bytes_segment_width}s |%s|\n" index = 0 count = 0 numeric = '' printable = '' each_word(data) do |word| numeric << format_numeric(word) << ' ' printable << format_printable(word) count += 1 if count >= @width output << sprintf(line_format,index,numeric,printable) numeric = '' printable = '' index += (@width * @word_size) count = 0 end end if count > 0 # output the remaining line output << sprintf(line_format,index,numeric,printable) end end
ruby
{ "resource": "" }
q22773
Hexdump.Dumper.format_printable
train
def format_printable(word) if @word_size == 1 PRINTABLE[word] elsif (RUBY_VERSION > '1.9.' && (word >= -2 && word <= 0x7fffffff)) begin word.chr(Encoding::UTF_8) rescue RangeError UNPRINTABLE end else UNPRINTABLE end end
ruby
{ "resource": "" }
q22774
VR::Col::Ren.CellRendererCombo.set_model
train
def set_model(vr_combo) # :nodoc: self.model = Gtk::ListStore.new(String) vr_combo.selections.each { |s| r = self.model.append ; r[0] = s } self.text_column = 0 end
ruby
{ "resource": "" }
q22775
VR.FileTreeView.refresh
train
def refresh(flags={}) @root = flags[:root] if flags[:root] open_folders = flags[:open_folders] ? flags[:open_folders] : get_open_folders() model.clear @root_iter = add_file(@root, nil) open_folders([@root_iter[:path]]) open_folders(open_folders) end
ruby
{ "resource": "" }
q22776
VR.FileTreeView.open_folders
train
def open_folders(folder_paths) model.each do |model, path, iter| if folder_paths.include?(iter[id(:path)]) fill_folder(iter) # expand_row(path, false) # self__row_expanded(self, iter, path) end end end
ruby
{ "resource": "" }
q22777
VR.FileTreeView.add_file
train
def add_file(filename, parent = @root_iter) my_path = File.dirname(filename) model.each do |model, path, iter| return if iter[id(:path)] == filename # duplicate parent = iter if iter[id(:path)] == my_path end fn = filename.gsub("\\", "/") parent[id(:empty)] = false unless parent.nil? child = add_row(parent) child[:pix] = @icons.get_icon(File.directory?(fn) ? "x.folder" : fn) if @icons child[:file_name] = File.basename(fn) child[:path] = fn if File.directory?(fn) child[:sort_on] = "0" + child[:file_name] child[:empty] = true add_row(child) # dummy record so expander appears else child[id(:sort_on)] = "1" + child[id(:file_name)] end return child end
ruby
{ "resource": "" }
q22778
Namey.Generator.generate
train
def generate(params = {}) params = { :type => random_gender, :frequency => :common, :with_surname => true }.merge(params) if ! ( params[:min_freq] || params[:max_freq] ) params[:min_freq], params[:max_freq] = frequency_values(params[:frequency]) else # # do some basic data validation in case someone is being a knucklehead # params[:min_freq] = params[:min_freq].to_i params[:max_freq] = params[:max_freq].to_i params[:max_freq] = params[:min_freq] + 1 if params[:max_freq] <= params[:min_freq] # max_freq needs to be at least 4 to get any results back, # because the most common male name only rates 3.3 # JAMES 3.318 3.318 1 params[:max_freq] = 4 if params[:max_freq] < 4 end name = get_name(params[:type], params[:min_freq], params[:max_freq]) # add surname if needed if params[:type] != :surname && params[:with_surname] == true name = "#{name} #{get_name(:surname, params[:min_freq], params[:max_freq])}" end name end
ruby
{ "resource": "" }
q22779
Namey.Generator.random_sort
train
def random_sort(set) set.order do # this is a bit of a hack obviously, but it checks the sort of # data engine being used to figure out how to randomly sort if set.class.name !~ /mysql/i random.function else rand.function end end end
ruby
{ "resource": "" }
q22780
Namey.Generator.get_name
train
def get_name(src, min_freq = 0, max_freq = 100) tmp = random_sort(@db[src.to_sym].filter{(freq >= min_freq) & (freq <= max_freq)}) tmp.count > 0 ? tmp.first[:name] : nil end
ruby
{ "resource": "" }
q22781
Twitch::V2.Videos.top
train
def top(options = {}, &block) params = {} if options[:game] params[:game] = options[:game] end period = options[:period] || :week if ![:week, :month, :all].include?(period) raise ArgumentError, 'period' end params[:period] = period.to_s return @query.connection.accumulate( :path => 'videos/top', :params => params, :json => 'videos', :create => -> hash { Video.new(hash, @query) }, :limit => options[:limit], :offset => options[:offset], &block ) end
ruby
{ "resource": "" }
q22782
Twitch::V2.Videos.for_channel
train
def for_channel(channel, options = {}) if channel.respond_to?(:name) channel_name = channel.name else channel_name = channel.to_s end params = {} type = options[:type] || :highlights if !type.nil? if ![:broadcasts, :highlights].include?(type) raise ArgumentError, 'type' end params[:broadcasts] = (type == :broadcasts) end name = CGI.escape(channel_name) return @query.connection.accumulate( :path => "channels/#{name}/videos", :params => params, :json => 'videos', :create => -> hash { Video.new(hash, @query) }, :limit => options[:limit], :offset => options[:offset] ) end
ruby
{ "resource": "" }
q22783
Twitch::V2.User.following
train
def following(options = {}, &block) name = CGI.escape(@name) return @query.connection.accumulate( :path => "users/#{name}/follows/channels", :json => 'follows', :sub_json => 'channel', :create => -> hash { Channel.new(hash, @query) }, :limit => options[:limit], :offset => options[:offset], &block ) end
ruby
{ "resource": "" }
q22784
RSpec::Puppet::Augeas.Fixtures.load_fixtures
train
def load_fixtures(resource, file) if block_given? Dir.mktmpdir("rspec-puppet-augeas") do |dir| prepare_fixtures(dir, resource, file) yield dir end else dir = Dir.mktmpdir("rspec-puppet-augeas") prepare_fixtures(dir, resource, file) dir end end
ruby
{ "resource": "" }
q22785
RSpec::Puppet::Augeas.Fixtures.apply
train
def apply(resource, logs) logs.clear Puppet::Util::Log.newdestination(Puppet::Test::LogCollector.new(logs)) Puppet::Util::Log.level = 'debug' confdir = Dir.mktmpdir oldconfdir = Puppet[:confdir] Puppet[:confdir] = confdir [:require, :before, :notify, :subscribe].each { |p| resource.delete p } catalog = Puppet::Resource::Catalog.new catalog.add_resource resource catalog = catalog.to_ral if resource.is_a? Puppet::Resource txn = catalog.apply Puppet::Util::Log.close_all txn ensure if confdir Puppet[:confdir] = oldconfdir FileUtils.rm_rf(confdir) end end
ruby
{ "resource": "" }
q22786
Twitch::V2.Channel.followers
train
def followers(options = {}, &block) name = CGI.escape(@name) return @query.connection.accumulate( :path => "channels/#{name}/follows", :json => 'follows', :sub_json => 'user', :create => -> hash { User.new(hash, @query) }, :limit => options[:limit], :offset => options[:offset], &block ) end
ruby
{ "resource": "" }
q22787
Twitch::V2.Games.find
train
def find(options) raise ArgumentError, 'options' if options.nil? raise ArgumentError, 'name' if options[:name].nil? params = { :query => options[:name], :type => 'suggest' } if options[:live] params.merge!(:live => true) end return @query.connection.accumulate( :path => 'search/games', :params => params, :json => 'games', :create => GameSuggestion, :limit => options[:limit] ) end
ruby
{ "resource": "" }
q22788
RSpec::Puppet::Augeas.Resource.idempotent
train
def idempotent @logs_idempotent = [] root = load_fixtures(resource, {"." => "#{@root}/."}) oldroot = resource[:root] resource[:root] = root @txn_idempotent = apply(resource, @logs_idempotent) FileUtils.rm_r root resource[:root] = oldroot @txn_idempotent end
ruby
{ "resource": "" }
q22789
Twitch::V2.Streams.all
train
def all(options = {}, &block) return @query.connection.accumulate( :path => 'streams', :json => 'streams', :create => -> hash { Stream.new(hash, @query) }, :limit => options[:limit], :offset => options[:offset], &block ) end
ruby
{ "resource": "" }
q22790
Twitch::V2.Streams.find
train
def find(options, &block) check = options.dup check.delete(:limit) check.delete(:offset) raise ArgumentError, 'options' if check.empty? params = {} channels = options[:channel] if channels if !channels.respond_to?(:map) raise ArgumentError, ':channel' end params[:channel] = channels.map { |channel| if channel.respond_to?(:name) channel.name else channel.to_s end }.join(',') end game = options[:game] if game if game.respond_to?(:name) params[:game] = game.name else params[:game] = game.to_s end end if options[:hls] params[:hls] = true end if options[:embeddable] params[:embeddable] = true end return @query.connection.accumulate( :path => 'streams', :params => params, :json => 'streams', :create => -> hash { Stream.new(hash, @query) }, :limit => options[:limit], :offset => options[:offset], &block ) end
ruby
{ "resource": "" }
q22791
Souyuz.Runner.apk_file
train
def apk_file build_path = Souyuz.project.options[:output_path] assembly_name = Souyuz.project.options[:assembly_name] Souyuz.cache[:build_apk_path] = "#{build_path}/#{assembly_name}.apk" "#{build_path}/#{assembly_name}.apk" end
ruby
{ "resource": "" }
q22792
Souyuz.Runner.package_path
train
def package_path build_path = Souyuz.project.options[:output_path] assembly_name = Souyuz.project.options[:assembly_name] # in the upcomming switch we determin the output path of iOS ipa files # those change in the Xamarin.iOS Cycle 9 release # see https://developer.xamarin.com/releases/ios/xamarin.ios_10/xamarin.ios_10.4/ if File.exist? "#{build_path}/#{assembly_name}.ipa" # after Xamarin.iOS Cycle 9 package_path = build_path else # before Xamarin.iOS Cycle 9 package_path = Dir.glob("#{build_path}/#{assembly_name} *").sort.last end package_path end
ruby
{ "resource": "" }
q22793
OnStomp::Interfaces::UriConfigurable.ClassMethods.attr_configurable_single
train
def attr_configurable_single *args, &block trans = attr_configurable_wrap lambda { |v| v.is_a?(Array) ? v.first : v }, block attr_configurable(*args, &trans) end
ruby
{ "resource": "" }
q22794
OnStomp::Interfaces::UriConfigurable.ClassMethods.attr_configurable_arr
train
def attr_configurable_arr *args, &block trans = attr_configurable_wrap lambda { |v| Array(v) }, block attr_configurable(*args, &trans) end
ruby
{ "resource": "" }
q22795
OnStomp::Interfaces::UriConfigurable.ClassMethods.attr_configurable_int
train
def attr_configurable_int *args, &block trans = attr_configurable_wrap lambda { |v| v.to_i }, block attr_configurable_single(*args, &trans) end
ruby
{ "resource": "" }
q22796
Soapforce.SObject.method_missing
train
def method_missing(method, *args, &block) # Check string keys first, original and downcase string_method = method.to_s if raw_hash.key?(string_method) return self[string_method] elsif raw_hash.key?(string_method.downcase) return self[string_method.downcase] end if string_method =~ /[A-Z+]/ string_method = string_method.snakecase end index = string_method.downcase.to_sym # Check symbol key and return local hash entry. return self[index] if raw_hash.has_key?(index) # Then delegate to hash object. if raw_hash.respond_to?(method) return raw_hash.send(method, *args) end # Finally return nil. nil end
ruby
{ "resource": "" }
q22797
Layer.User.blocks
train
def blocks RelationProxy.new(self, Block, [Operations::Create, Operations::List, Operations::Delete]) do def from_response(response, client) response['url'] ||= "#{base.url}#{resource_type.url}/#{response['user_id']}" super end def create(attributes, client = self.client) response = client.post(url, attributes) from_response({ 'user_id' => attributes['user_id'] }, client) end end end
ruby
{ "resource": "" }
q22798
Layer.User.identity
train
def identity SingletonRelationProxy.new(self, Layer::Identity) do def from_response(response, client) response['url'] ||= "#{base.url}#{resource_type.url}" super end def create(attributes, client = self.client) client.post(url, attributes) fetch end def delete(client = self.client) client.delete(url) end end end
ruby
{ "resource": "" }
q22799
Layer.Conversation.messages
train
def messages RelationProxy.new(self, Message, [Operations::Create, Operations::Paginate, Operations::Find, Operations::Delete, Operations::Destroy]) end
ruby
{ "resource": "" }