_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
30
4.3k
language
stringclasses
1 value
meta_information
dict
q16900
Logging.ColorScheme.[]=
train
def []=( color_tag, constants ) @scheme[to_key(color_tag)] = constants.respond_to?(:map) ?
ruby
{ "resource": "" }
q16901
Logging.ColorScheme.to_constant
train
def to_constant( v ) v = v.to_s.upcase ColorScheme.const_get(v) if (ColorScheme.const_defined?(v,
ruby
{ "resource": "" }
q16902
Logging.Appender.encoding=
train
def encoding=( value ) if value.nil? @encoding = nil else
ruby
{ "resource": "" }
q16903
Logging.Appender.allow
train
def allow( event ) return nil if @level > event.level @filters.each do |filter| break
ruby
{ "resource": "" }
q16904
Logging.MappedDiagnosticContext.context
train
def context c = Thread.current.thread_variable_get(NAME) if c.nil? c = if Thread.current.thread_variable_get(STACK_NAME) flatten(stack) else Hash.new
ruby
{ "resource": "" }
q16905
Logging.MappedDiagnosticContext.stack
train
def stack s = Thread.current.thread_variable_get(STACK_NAME) if s.nil? s = [{}]
ruby
{ "resource": "" }
q16906
Logging.MappedDiagnosticContext.sanitize
train
def sanitize( hash, target = {} ) unless hash.is_a?(Hash) raise ArgumentError, "Expecting a Hash but received a #{hash.class.name}" end
ruby
{ "resource": "" }
q16907
Logging.NestedDiagnosticContext.context
train
def context c = Thread.current.thread_variable_get(NAME) if c.nil? c = Array.new
ruby
{ "resource": "" }
q16908
Logging::Layouts.Parseable.iso8601_format
train
def iso8601_format( time ) value = apply_utc_offset(time) str = value.strftime('%Y-%m-%dT%H:%M:%S') str << ('.%06d' % value.usec)
ruby
{ "resource": "" }
q16909
CfnDsl.JSONable.as_json
train
def as_json(_options = {}) hash = {} instance_variables.each do |var| name = var[1..-1] if name =~ /^__/ # if a variable starts with double underscore, strip one off name = name[1..-1] elsif name =~ /^_/
ruby
{ "resource": "" }
q16910
OpenTok.Broadcasts.find
train
def find(broadcast_id) raise ArgumentError, "broadcast_id not provided" if broadcast_id.to_s.empty?
ruby
{ "resource": "" }
q16911
OpenTok.Broadcasts.stop
train
def stop(broadcast_id) raise ArgumentError, "broadcast_id not provided" if broadcast_id.to_s.empty?
ruby
{ "resource": "" }
q16912
OpenTok.OpenTok.create_session
train
def create_session(opts={}) # normalize opts so all keys are symbols and only include valid_opts valid_opts = [ :media_mode, :location, :archive_mode ] opts = opts.inject({}) do |m,(k,v)| if valid_opts.include? k.to_sym m[k.to_sym] = v end m end # keep o...
ruby
{ "resource": "" }
q16913
OpenTok.Streams.all
train
def all(session_id) raise ArgumentError, 'session_id not provided' if session_id.to_s.empty?
ruby
{ "resource": "" }
q16914
OpenTok.Archives.find
train
def find(archive_id) raise ArgumentError, "archive_id not provided" if archive_id.to_s.empty?
ruby
{ "resource": "" }
q16915
OpenTok.Archives.all
train
def all(options = {}) raise ArgumentError, "Limit is invalid" unless options[:count].nil? or (0..1000).include? options[:count] archive_list_json =
ruby
{ "resource": "" }
q16916
OpenTok.Archives.stop_by_id
train
def stop_by_id(archive_id) raise ArgumentError, "archive_id not provided" if archive_id.to_s.empty? archive_json =
ruby
{ "resource": "" }
q16917
OpenTok.Archives.delete_by_id
train
def delete_by_id(archive_id) raise ArgumentError, "archive_id not provided" if archive_id.to_s.empty? response =
ruby
{ "resource": "" }
q16918
EmailSpec.Helpers.find_email
train
def find_email(address, opts={}) address = convert_address(address) if opts[:with_subject] expected_subject = (opts[:with_subject].is_a?(String) ? Regexp.escape(opts[:with_subject]) : opts[:with_subject]) mailbox_for(address).find { |m| m.subject =~ Regexp.new(expected_subject) }
ruby
{ "resource": "" }
q16919
Ferro.Router.path_to_parts
train
def path_to_parts(path) path. downcase. split('/').
ruby
{ "resource": "" }
q16920
Ferro.Router.navigated
train
def navigated url = get_location @params = [] idx = match(path_to_parts(decode(url.pathname)), decode(url.search)) if idx
ruby
{ "resource": "" }
q16921
Ferro.Router.match
train
def match(path, search) matches = get_matches(path) if matches.length > 0 match = matches.sort { |m| m[1] }.first @params = match[2]
ruby
{ "resource": "" }
q16922
Ferro.Router.get_matches
train
def get_matches(path) matches = [] @routes.each_with_index do |route, i| score, pars = score_route(route[:parts], path)
ruby
{ "resource": "" }
q16923
Ferro.Router.score_route
train
def score_route(parts, path) score = 0 pars = {} if parts.length == path.length parts.each_with_index do |part, i| if part[0] == ':' score += 1 pars["#{part[1..-1]}"]
ruby
{ "resource": "" }
q16924
Ferro.Router.add_search_to_params
train
def add_search_to_params(search) if !search.empty? pars = search[1..-1].split('&')
ruby
{ "resource": "" }
q16925
Ferro.Factory.dasherize
train
def dasherize(class_name) return class_name if class_name !~ /[A-Z:_]/ c = class_name.to_s.gsub('::', '') (c[0]
ruby
{ "resource": "" }
q16926
Ferro.Factory.composite_state
train
def composite_state(class_name, state) if @compositor list = @compositor.css_classes_for("#{class_name}::#{state}") return
ruby
{ "resource": "" }
q16927
Ferro.Factory.composite_classes
train
def composite_classes(target, element, add_superclass) if @compositor composite_for(target.class.name, element) if add_superclass
ruby
{ "resource": "" }
q16928
Ferro.Compositor.css_classes_for_map
train
def css_classes_for_map(classname, mapping) css = mapping[classname] css.class == String
ruby
{ "resource": "" }
q16929
Ferro.Compositor.switch_theme
train
def switch_theme(root_element, theme) old_map = @mapping new_map = map(theme) root_element.each_child do |e| old_classes = css_classes_for_map e.class.name, old_map new_classes = css_classes_for_map e.class.name, new_map
ruby
{ "resource": "" }
q16930
Ferro.Elementary._stylize
train
def _stylize styles = style if styles.class == Hash set_attribute( 'style',
ruby
{ "resource": "" }
q16931
Ferro.Elementary.add_child
train
def add_child(name, element_class, options = {}) sym = symbolize(name) raise "Child '#{sym}' already defined" if @children.has_key?(sym) raise
ruby
{ "resource": "" }
q16932
Ferro.Elementary.each_child
train
def each_child(&block) if block_given? block.call self @children.each do |_, child|
ruby
{ "resource": "" }
q16933
Ferro.I18n._replace_options
train
def _replace_options(string, options) # Unescape the string so we can use the returned string # to set an elements inner html. s = string.gsub('&lt;', '<').gsub('&gt;', '>') if options # But escape option values to prevent code injection s.gsub(/%\{(\w+)\}/) do |m| key...
ruby
{ "resource": "" }
q16934
Ferro.BaseElement.option_replace
train
def option_replace(key, default = nil) value = @options[key] || default @options.delete(key)
ruby
{ "resource": "" }
q16935
Ferro.BaseElement.update_state
train
def update_state(state, active) if !active.nil? @states.each do |s, v| v[1] = active if s
ruby
{ "resource": "" }
q16936
Ferro.BaseElement.toggle_state
train
def toggle_state(state) @states.select { |s, _| s == state
ruby
{ "resource": "" }
q16937
Mailman.Router.route
train
def route(message) @params.clear @message = message result = nil if @bounce_block and message.respond_to?(:bounced?) and message.bounced? return instance_exec(&@bounce_block) end routes.each do |route| break if result = route.match!(message) end if resu...
ruby
{ "resource": "" }
q16938
Mailman.Route.match!
train
def match!(message) params = {} args = [] @conditions.each do |condition| if result = condition.match(message) params.merge!(result[0]) args += result[1] else
ruby
{ "resource": "" }
q16939
Mailman.Application.run
train
def run Mailman.logger.info "Mailman v#{Mailman::VERSION} started" if config.rails_root rails_env = File.join(config.rails_root, 'config', 'environment.rb') if File.exist?(rails_env) && !(defined?(::Rails) && ::Rails.env) Mailman.logger.info "Rails root found in #{config.rails_roo...
ruby
{ "resource": "" }
q16940
Mailman.Application.polling_loop
train
def polling_loop(connection) if polling? polling_msg = "Polling enabled. Checking every #{config.poll_interval} seconds." else polling_msg = "Polling disabled. Checking for messages once." end Mailman.logger.info(polling_msg) tries ||= 5 loop do begin ...
ruby
{ "resource": "" }
q16941
Hypernova.ControllerHelpers.hypernova_batch_render
train
def hypernova_batch_render(job) if @hypernova_batch.nil? raise NilBatchError.new('called hypernova_batch_render without calling '\ 'hypernova_batch_before. Check your around_filter for :hypernova_render_support') end batch_token
ruby
{ "resource": "" }
q16942
Hypernova.ControllerHelpers.render_react_component
train
def render_react_component(component, data = {}) begin new_data = get_view_data(component, data) rescue StandardError => e on_error(e) new_data = data end job
ruby
{ "resource": "" }
q16943
Hypernova.ControllerHelpers.hypernova_batch_after
train
def hypernova_batch_after if @hypernova_batch.nil? raise NilBatchError.new('called hypernova_batch_after without calling '\ 'hypernova_batch_before. Check your around_filter for :hypernova_render_support') end return if @hypernova_batch.empty? jobs = @hypernova_batch.jobs ...
ruby
{ "resource": "" }
q16944
Hypernova.Batch.jobs_hash
train
def jobs_hash hash = {} jobs.each_with_index
ruby
{ "resource": "" }
q16945
RSpec.Its.its
train
def its(attribute, *options, &block) its_caller = caller.select {|file_line| file_line !~ %r(/lib/rspec/its) } describe(attribute.to_s, :caller => its_caller) do let(:__its_subject) do if Array === attribute if Hash === subject attribute.inject(subject) {|inner, a...
ruby
{ "resource": "" }
q16946
Hue.Light.refresh
train
def refresh json = JSON(Net::HTTP.get(URI.parse(
ruby
{ "resource": "" }
q16947
Spectator.Timer.record
train
def record(nanos) return if nanos < 0 @count.add_and_get(1) @total_time.add_and_get(nanos)
ruby
{ "resource": "" }
q16948
Spectator.MeterId.with_tag
train
def with_tag(key, value) new_tags = @tags.dup
ruby
{ "resource": "" }
q16949
Spectator.MeterId.key
train
def key if @key.nil? hash_key = @name.to_s @key = hash_key keys = @tags.keys keys.sort keys.each do |k| v = tags[k]
ruby
{ "resource": "" }
q16950
Spectator.DistributionSummary.record
train
def record(amount) return if amount < 0 @count.add_and_get(1) @total_amount.add_and_get(amount)
ruby
{ "resource": "" }
q16951
Spectator.DistributionSummary.measure
train
def measure cnt = Measure.new(@id.with_stat('count'), @count.get_and_set(0)) tot = Measure.new(@id.with_stat('totalAmount'), @total_amount.get_and_set(0)) tot_sq = Measure.new(@id.with_stat('totalOfSquares'),
ruby
{ "resource": "" }
q16952
Spectator.Http.post_json
train
def post_json(endpoint, payload) s = payload.to_json uri = URI(endpoint) http = Net::HTTP.new(uri.host, uri.port) req = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json') req.body = s begin res = http.request(req)
ruby
{ "resource": "" }
q16953
Spectator.Publisher.stop
train
def stop unless @started Spectator.logger.info('Attemping to stop Spectator ' \ 'without a previous call to start') return end @should_stop = true Spectator.logger.info('Stopping spectator')
ruby
{ "resource": "" }
q16954
Spectator.Publisher.op_for_measurement
train
def op_for_measurement(measure) stat = measure.id.tags.fetch(:statistic, :unknown)
ruby
{ "resource": "" }
q16955
Spectator.Publisher.should_send
train
def should_send(measure) op = op_for_measurement(measure) return measure.value > 0 if op == ADD_OP
ruby
{ "resource": "" }
q16956
Spectator.Publisher.build_string_table
train
def build_string_table(measurements) common_tags = @registry.common_tags table = {} common_tags.each do |k, v| table[k] = 0 table[v] = 0 end table[:name] = 0
ruby
{ "resource": "" }
q16957
Spectator.Publisher.payload_for_measurements
train
def payload_for_measurements(measurements) table = build_string_table(measurements) payload = [] payload.push(table.length) strings = table.keys.sort payload.concat(strings)
ruby
{ "resource": "" }
q16958
Spectator.Publisher.send_metrics_now
train
def send_metrics_now ms = registry_measurements if ms.empty? Spectator.logger.debug 'No measurements to send' else uri = @registry.config[:uri]
ruby
{ "resource": "" }
q16959
Transitions.Event.timestamp=
train
def timestamp=(values) values.each do |value| case value when String, Symbol, TrueClass
ruby
{ "resource": "" }
q16960
Transitions.Event.timestamp_attribute_name
train
def timestamp_attribute_name(obj, next_state, user_timestamp) user_timestamp == true ?
ruby
{ "resource": "" }
q16961
RailsEmailPreview.EmailsController.show
train
def show prevent_browser_caching cms_edit_links! with_email_locale do if @preview.respond_to?(:preview_mail) @mail, body = mail_and_body
ruby
{ "resource": "" }
q16962
RailsEmailPreview.EmailsController.show_headers
train
def show_headers mail = with_email_locale { mail_and_body.first } render partial:
ruby
{ "resource": "" }
q16963
RailsEmailPreview.EmailsController.show_body
train
def show_body prevent_browser_caching cms_edit_links! with_email_locale do _, body = mail_and_body
ruby
{ "resource": "" }
q16964
Taps.Utils.incorrect_blobs
train
def incorrect_blobs(db, table) return [] if (db.url =~ /mysql:\/\//).nil? columns = [] db.schema(table).each do |data| column, cdata = data
ruby
{ "resource": "" }
q16965
Taps.Utils.server_error_handling
train
def server_error_handling(&blk) begin blk.call rescue Sequel::DatabaseError => e if e.message =~ /duplicate key value/i raise
ruby
{ "resource": "" }
q16966
Taps.DataStream.fetch_rows
train
def fetch_rows state[:chunksize] = fetch_chunksize ds = table.order(*order_by).limit(state[:chunksize], state[:offset]) log.debug "DataStream#fetch_rows SQL -> #{ds.sql}" rows = Taps::Utils.format_data(ds.all, :string_columns =>
ruby
{ "resource": "" }
q16967
Taps.DataStream.fetch_remote_in_server
train
def fetch_remote_in_server(params) json = self.class.parse_json(params[:json]) encoded_data = params[:encoded_data] rows = parse_encoded_data(encoded_data, json[:checksum]) @complete = rows == { }
ruby
{ "resource": "" }
q16968
Cinch.Handler.stop
train
def stop @bot.loggers.debug "[Stopping handler] Stopping all threads of handler #{self}: #{@thread_group.list.size} threads..." @thread_group.list.each do |thread| Thread.new do @bot.loggers.debug "[Ending thread] Waiting 10 seconds for #{thread} to finish..."
ruby
{ "resource": "" }
q16969
Cinch.Handler.call
train
def call(message, captures, arguments) bargs = captures + arguments thread = Thread.new { @bot.loggers.debug "[New thread] For #{self}: #{Thread.current} -- #{@thread_group.list.size} in total." begin if @execute_in_callback
ruby
{ "resource": "" }
q16970
Cinch.Syncable.wait_until_synced
train
def wait_until_synced(attr) attr = attr.to_sym waited = 0 while true return if attribute_synced?(attr) waited += 1 if waited % 100 == 0 bot.loggers.warn "A synced attribute ('%s' for %s) has not been available for %d seconds, still waiting" % [attr, self.inspect, wai...
ruby
{ "resource": "" }
q16971
Cinch.Configuration.load
train
def load(new_config, from_default = false) if from_default @table = self.class.default_config end new_config.each do |option, value| if value.is_a?(Hash) if self[option].is_a?(Configuration) self[option].load(value) else
ruby
{ "resource": "" }
q16972
Cinch.UserList.find
train
def find(nick) if nick == @bot.nick return @bot end downcased_nick
ruby
{ "resource": "" }
q16973
Cinch.User.refresh
train
def refresh return if @in_whois @data.keys.each do |attr| unsync attr end @in_whois = true if @bot.irc.network.whois_only_one_argument?
ruby
{ "resource": "" }
q16974
Cinch.User.mask
train
def mask(s = "%n!%u@%h") s = s.gsub(/%(.)/) { case $1 when "n" @name when "u" self.user when "h" self.host
ruby
{ "resource": "" }
q16975
Cinch.User.monitor
train
def monitor if @bot.irc.isupport["MONITOR"] > 0 @bot.irc.send "MONITOR + #@name" else refresh @monitored_timer = Timer.new(@bot, interval: 30) {
ruby
{ "resource": "" }
q16976
Cinch.User.online=
train
def online=(bool) notify = self.__send__("online?_unsynced") != bool && @monitored sync(:online?, bool, true) return unless notify if bool
ruby
{ "resource": "" }
q16977
Cinch.IRC.start
train
def start setup if connect @sasl_remaining_methods = @bot.config.sasl.mechanisms.reverse send_cap_ls send_login reading_thread = start_reading_thread sending_thread = start_sending_thread
ruby
{ "resource": "" }
q16978
Cinch.Logger.log
train
def log(messages, event = :debug, level = event) return unless will_log?(level) @mutex.synchronize do Array(messages).each do |message|
ruby
{ "resource": "" }
q16979
Cinch.ChannelList.find_ensured
train
def find_ensured(name) downcased_name = name.irc_downcase(@bot.irc.isupport["CASEMAPPING"])
ruby
{ "resource": "" }
q16980
Cinch.Channel.topic=
train
def topic=(new_topic) if new_topic.size > @bot.irc.isupport["TOPICLEN"] && @bot.strict?
ruby
{ "resource": "" }
q16981
Cinch.Channel.kick
train
def kick(user, reason = nil) if reason.to_s.size > @bot.irc.isupport["KICKLEN"] && @bot.strict?
ruby
{ "resource": "" }
q16982
Cinch.Channel.join
train
def join(key = nil) if key.nil? and self.key != true key = self.key end
ruby
{ "resource": "" }
q16983
Cinch.Target.send
train
def send(text, notice = false) # TODO deprecate `notice` argument, put splitting into own # method text = text.to_s split_start = @bot.config.message_split_start || "" split_end = @bot.config.message_split_end || "" command = notice ? "NOTICE" : "PRIVMSG" prefix = ":#{@bot....
ruby
{ "resource": "" }
q16984
Cinch.Bot.start
train
def start(plugins = true) @reconnects = 0 @plugins.register_plugins(@config.plugins.plugins) if plugins begin @user_list.each do |user| user.in_whois = false user.unsync_all end # reset state of all users @channel_list.each do |channel| channel.u...
ruby
{ "resource": "" }
q16985
Cinch.Bot.part
train
def part(channel, reason = nil) channel
ruby
{ "resource": "" }
q16986
Cinch.Bot.generate_next_nick!
train
def generate_next_nick!(base = nil) nicks = @config.nicks || [] if base # if `base` is not in our list of nicks to try, assume that it's # custom and just append an underscore if !nicks.include?(base) new_nick = base + "_" else # if we have a base, try t...
ruby
{ "resource": "" }
q16987
Garage::Representer.ClassMethods.metadata
train
def metadata {:definitions => representer_attrs.grep(Definition).map {|definition| definition.name}, :links =>
ruby
{ "resource": "" }
q16988
Garage.ControllerHelper.requested_by?
train
def requested_by?(resource) user = resource.respond_to?(:owner) ? resource.owner : resource case when current_resource_owner.nil? false when !user.is_a?(current_resource_owner.class)
ruby
{ "resource": "" }
q16989
Loaf.OptionsValidator.valid?
train
def valid?(options) valid_options = Loaf::Configuration::VALID_ATTRIBUTES options.each_key do |key| unless valid_options.include?(key)
ruby
{ "resource": "" }
q16990
Loaf.Configuration.to_hash
train
def to_hash VALID_ATTRIBUTES.reduce({})
ruby
{ "resource": "" }
q16991
Loaf.ViewExtensions.breadcrumb
train
def breadcrumb(name, url, options = {}) _breadcrumbs
ruby
{ "resource": "" }
q16992
Loaf.ViewExtensions.breadcrumb_trail
train
def breadcrumb_trail(options = {}) return enum_for(:breadcrumb_trail) unless block_given? valid?(options) options = Loaf.configuration.to_hash.merge(options) _breadcrumbs.each do |crumb| name
ruby
{ "resource": "" }
q16993
Loaf.ViewExtensions._expand_url
train
def _expand_url(url) case url when String, Symbol respond_to?(url) ? send(url) : url when Proc
ruby
{ "resource": "" }
q16994
Loaf.Translation.find_title
train
def find_title(title, options = {}) return title if title.nil? || title.empty? options[:scope] ||= translation_scope
ruby
{ "resource": "" }
q16995
BeakerHostGenerator.Parser.tokenize_layout
train
def tokenize_layout(layout_spec) # Here we allow dashes in certain parts of the spec string # i.e. "centos6-64m{hostname=foo-bar}-debian8-32" # by first replacing all occurrences of - with | that exist within # the braces {...}. # # So we'd end up with: # "centos6-64m{hostnam...
ruby
{ "resource": "" }
q16996
BeakerHostGenerator.Parser.settings_string_to_map
train
def settings_string_to_map(host_settings) stringscan = StringScanner.new(host_settings) object = nil object_depth = [] current_depth = 0 # This loop scans until the next delimiter character is found. When # the next delimiter is recognized, there is enough context in the # su...
ruby
{ "resource": "" }
q16997
BeakerHostGenerator.Data.get_platform_info
train
def get_platform_info(bhg_version, platform, hypervisor) info = get_osinfo(bhg_version)[platform]
ruby
{ "resource": "" }
q16998
BeakerHostGenerator.AbsSupport.extract_templates
train
def extract_templates(config) templates_hosts = config['HOSTS'].values.group_by { |h| h['template'] } templates_hosts.each
ruby
{ "resource": "" }
q16999
BeakerHostGenerator.Generator.generate
train
def generate(layout, options) layout = prepare(layout) tokens = tokenize_layout(layout) config = {}.deep_merge(BASE_CONFIG) nodeid = Hash.new(1) ostype = nil bhg_version = options[:osinfo_version] || 0 tokens.each do |token| if is_ostype_token?(token, bhg_version) ...
ruby
{ "resource": "" }