_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q23100
Dare.Window.add_keyboard_event_listeners
train
def add_keyboard_event_listeners Element.find("html").on :keydown do |event| @keys[get_key_id(event)] = true end Element.find("html").on :keyup do |event| @keys[get_key_id(event)] = false end ::Window.on :blur do |event| @keys.fill false end end
ruby
{ "resource": "" }
q23101
POI.Worksheet.[]
train
def [](row_index) if Fixnum === row_index rows[row_index] else ref = org.apache.poi.ss.util.CellReference.new(row_index) cell = rows[ref.row][ref.col] cell && cell.value ? cell.value : cell end end
ruby
{ "resource": "" }
q23102
IniParse.Generator.section
train
def section(name, opts = {}) if @in_section # Nesting sections is bad, mmmkay? raise LineNotAllowed, "You can't nest sections in INI files." end # Add to a section if it already exists if @document.has_section?(name.to_s()) @context = @document[name.to_s()] else @context = Lines::Section.new(name, line_options(opts)) @document.lines << @context end if block_given? begin @in_section = true with_options(opts) { yield self } @context = @document blank() ensure @in_section = false end end end
ruby
{ "resource": "" }
q23103
IniParse.Generator.option
train
def option(key, value, opts = {}) @context.lines << Lines::Option.new( key, value, line_options(opts) ) rescue LineNotAllowed # Tried to add an Option to a Document. raise NoSectionError, 'Your INI document contains an option before the first section is ' \ 'declared which is not allowed.' end
ruby
{ "resource": "" }
q23104
IniParse.Generator.comment
train
def comment(comment, opts = {}) @context.lines << Lines::Comment.new( line_options(opts.merge(:comment => comment)) ) end
ruby
{ "resource": "" }
q23105
IniParse.Generator.with_options
train
def with_options(opts = {}) # :nodoc: opts = opts.dup opts.delete(:comment) @opt_stack.push( @opt_stack.last.merge(opts)) yield self @opt_stack.pop end
ruby
{ "resource": "" }
q23106
Yt.Response.videos_for
train
def videos_for(items, key, options) items.body['items'].map{|item| item['id'] = item[key]['videoId']} if options[:parts] == %i(id) items else options[:ids] = items.body['items'].map{|item| item['id']} options[:offset] = nil get('/youtube/v3/videos', resource_params(options)).tap do |response| response.body['nextPageToken'] = items.body['nextPageToken'] end end end
ruby
{ "resource": "" }
q23107
GoogleAnalytics.InstanceMethods.ga_track_event
train
def ga_track_event(category, action, label = nil, value = nil) ga_events.push(GoogleAnalytics::Event.new(category, action, label, value)) end
ruby
{ "resource": "" }
q23108
IniParse.Document.to_ini
train
def to_ini string = @lines.to_a.map { |line| line.to_ini }.join($/) string = "#{ string }\n" unless string[-1] == "\n" string end
ruby
{ "resource": "" }
q23109
IniParse.Document.to_hash
train
def to_hash result = {} @lines.entries.each do |section| result[section.key] ||= {} section.entries.each do |option| opts = Array(option) val = opts.map { |o| o.respond_to?(:value) ? o.value : o } val = val.size > 1 ? val : val.first result[section.key][opts.first.key] = val end end result end
ruby
{ "resource": "" }
q23110
IniParse.Document.save
train
def save(path = nil) @path = path if path raise IniParseError, 'No path given to Document#save' if @path !~ /\S/ File.open(@path, 'w') { |f| f.write(self.to_ini) } end
ruby
{ "resource": "" }
q23111
POI.Workbook.[]
train
def [](reference) if Fixnum === reference return worksheets[reference] end if sheet = worksheets.detect{|e| e.name == reference} return sheet.poi_worksheet.nil? ? nil : sheet end cell = cell(reference) if Array === cell cell.collect{|e| e.value} elsif Hash === cell values = {} cell.each_pair{|column_name, cells| values[column_name] = cells.collect{|e| e.value}} values else cell.value end end
ruby
{ "resource": "" }
q23112
IniParse.Parser.parse
train
def parse IniParse::Generator.gen do |generator| @source.split("\n", -1).each do |line| generator.send(*Parser.parse_line(line)) end end end
ruby
{ "resource": "" }
q23113
IniParse.LineCollection.[]=
train
def []=(key, value) key = key.to_s if has_key?(key) @lines[ @indicies[key] ] = value else @lines << value @indicies[key] = @lines.length - 1 end end
ruby
{ "resource": "" }
q23114
IniParse.LineCollection.each
train
def each(include_blank = false) @lines.each do |line| if include_blank || ! (line.is_a?(Array) ? line.empty? : line.blank?) yield(line) end end end
ruby
{ "resource": "" }
q23115
IniParse.LineCollection.delete
train
def delete(key) key = key.key if key.respond_to?(:key) unless (idx = @indicies[key]).nil? @indicies.delete(key) @indicies.each { |k,v| @indicies[k] = v -= 1 if v > idx } @lines.delete_at(idx) end end
ruby
{ "resource": "" }
q23116
IniParse.OptionCollection.<<
train
def <<(line) if line.kind_of?(IniParse::Lines::Section) raise IniParse::LineNotAllowed, "You can't add a Section to an OptionCollection." end if line.blank? || (! has_key?(line.key)) super # Adding a new option, comment or blank line. else self[line.key] = [self[line.key], line].flatten end self end
ruby
{ "resource": "" }
q23117
IniParse.OptionCollection.keys
train
def keys map { |line| line.kind_of?(Array) ? line.first.key : line.key } end
ruby
{ "resource": "" }
q23118
Exchange.Helper.assure_time
train
def assure_time arg=nil, opts={} if arg arg.kind_of?(Time) ? arg : Time.gm(*arg.split('-')) elsif opts[:default] Time.send(opts[:default]) end end
ruby
{ "resource": "" }
q23119
TranslationCenter.CenterController.set_language_from
train
def set_language_from session[:lang_from] = params[:lang].to_sym I18n.locale = session[:lang_from] render nothing: true end
ruby
{ "resource": "" }
q23120
TranslationCenter.CenterController.set_language_to
train
def set_language_to session[:lang_to] = params[:lang].to_sym respond_to do |format| format.html { redirect_to root_url } format.js { render nothing: true } end end
ruby
{ "resource": "" }
q23121
TranslationCenter.ActivityQuery.translation_ids
train
def translation_ids query = Translation.all query = query.where(lang: lang) unless lang.blank? query = query.joins(:translation_key).where("translation_center_translation_keys.name LIKE ?", "%#{translation_key_name}%") unless translation_key_name.blank? if translator_identifier translator_class = TranslationCenter::CONFIG['translator_type'].camelize.constantize translators_ids = translator_class.where("#{TranslationCenter::CONFIG['identifier_type']} LIKE ? ", "%#{translator_identifier}%").map(&:id) query = query.where(translator_id: translators_ids) end query.map(&:id) end
ruby
{ "resource": "" }
q23122
TranslationCenter.TranslationKey.add_category
train
def add_category category_name = self.name.to_s.split('.').first # if one word then add to general category category_name = self.name.to_s.split('.').size == 1 ? 'general' : self.name.to_s.split('.').first self.category = TranslationCenter::Category.where(name: category_name).first_or_create self.last_accessed = Time.now end
ruby
{ "resource": "" }
q23123
TranslationCenter.TranslationKey.update_status
train
def update_status(lang) if self.translations.in(lang).blank? self.update_attribute("#{lang}_status", UNTRANSLATED) elsif !self.translations.in(lang).accepted.blank? self.update_attribute("#{lang}_status", TRANSLATED) else self.update_attribute("#{lang}_status", PENDING) end end
ruby
{ "resource": "" }
q23124
TranslationCenter.TranslationKey.create_default_translation
train
def create_default_translation translation = self.translations.build(value: self.name.to_s.split('.').last.titleize, lang: :en, status: 'accepted') translation.translator = TranslationCenter.prepare_translator translation.save end
ruby
{ "resource": "" }
q23125
TranslationCenter.TranslationKey.add_to_hash
train
def add_to_hash(all_translations, lang) levels = self.name.split('.') add_to_hash_rec(all_translations, levels, lang.to_s) end
ruby
{ "resource": "" }
q23126
Exchange.Typecasting.money
train
def money *attributes options = attributes.last.is_a?(Hash) ? attributes.pop : {} attributes.each do |attribute| # Get the attribute typecasted into money # @return [Exchange::Money] an instance of money # install_money_getter attribute, options # Set the attribute either with money or just any data # Implicitly converts values given that are not in the same currency as the currency option evaluates to # @param [Exchange::Money, String, Numberic] data The data to set the attribute to # install_money_setter attribute, options end # Evaluates options given either as symbols or as procs # @param [Symbol, Proc] option The option to evaluate # install_money_option_eval # Evaluates whether an error should be raised because there is no currency present # @param [Symbol] currency The currency, if given # install_currency_error_tester end
ruby
{ "resource": "" }
q23127
Capybara.BootstrapDatepicker.select_date
train
def select_date(value, datepicker: :bootstrap, format: nil, from: nil, xpath: nil, **args) fail "Must pass a hash containing 'from' or 'xpath'" if from.nil? && xpath.nil? value = value.respond_to?(:to_date) ? value.to_date : Date.parse(value) date_input = xpath ? find(:xpath, xpath, **args) : find_field(from, **args) case datepicker when :bootstrap select_bootstrap_date date_input, value else select_simple_date date_input, value, format end first(:xpath, '//body').click end
ruby
{ "resource": "" }
q23128
Capybara.BootstrapDatepicker.select_simple_date
train
def select_simple_date(date_input, value, format = nil) value = value.strftime format unless format.nil? date_input.set "#{value}\e" end
ruby
{ "resource": "" }
q23129
Capybara.BootstrapDatepicker.select_bootstrap_date
train
def select_bootstrap_date(date_input, value) date_input.click picker = Picker.new picker.goto_decade_panel picker.navigate_through_decades value.year picker.find_year(value.year).click picker.find_month(value.month).click picker.find_day(value.day).click fail if Date.parse(date_input.value) != value end
ruby
{ "resource": "" }
q23130
Exchange.Configurable.subclass_with_constantize
train
def subclass_with_constantize self.subclass = parent_module.const_get camelize(self.subclass_without_constantize) unless !self.subclass_without_constantize || self.subclass_without_constantize.is_a?(Class) subclass_without_constantize end
ruby
{ "resource": "" }
q23131
Exchange.ISO.assert_currency!
train
def assert_currency! arg defines?(arg) ? (country_map[arg] || arg) : raise(Exchange::NoCurrencyError.new("#{arg} is not a currency nor a country code matchable to a currency")) end
ruby
{ "resource": "" }
q23132
Exchange.ISO.instantiate
train
def instantiate amount, currency if amount.is_a?(BigDecimal) amount else BigDecimal.new(amount.to_s, precision_for(amount, currency)) end end
ruby
{ "resource": "" }
q23133
Exchange.ISO.stringify
train
def stringify amount, currency, opts={} definition = definitions[currency] separators = definition[:separators] || {} format = "%.#{definition[:minor_unit]}f" string = format % amount major, minor = string.split('.') major.gsub!(/(\d)(?=(\d\d\d)+(?!\d))/) { $1 + separators[:major] } if separators[:major] && opts[:format] != :plain string = minor ? major + (opts[:format] == :plain || !separators[:minor] ? '.' : separators[:minor]) + minor : major pre = [[:amount, :plain].include?(opts[:format]) && '', opts[:format] == :symbol && definition[:symbol], currency.to_s.upcase + ' '].detect{|a| a.is_a?(String)} "#{pre}#{string}" end
ruby
{ "resource": "" }
q23134
Exchange.ISO.symbolize_keys
train
def symbolize_keys hsh new_hsh = Hash.new hsh.each_pair do |k,v| v = symbolize_keys v if v.is_a?(Hash) new_hsh[k.downcase.to_sym] = v end new_hsh end
ruby
{ "resource": "" }
q23135
Exchange.ISO.precision_for
train
def precision_for amount, currency defined_minor_precision = definitions[currency][:minor_unit] match = amount.to_s.match(/^-?(\d*)\.?(\d*)e?(-?\d+)?$/).to_a[1..3] given_major_precision, given_minor_precision = precision_from_match *match given_major_precision + [defined_minor_precision, given_minor_precision].max end
ruby
{ "resource": "" }
q23136
ActsAsTranslator.InstanceMethods.translation_for
train
def translation_for(key, lang) self.translations.find_or_initialize_by(translation_key_id: key.id, lang: lang.to_s, translator_type: self.class.name) end
ruby
{ "resource": "" }
q23137
TranslationCenter.Category.complete_percentage_in
train
def complete_percentage_in(lang) if self.keys.blank? 100 else accepted_keys = accepted_keys(lang) 100 * accepted_keys.count / self.keys.count end end
ruby
{ "resource": "" }
q23138
Exchange.Money.to
train
def to other, options={} other = ISO.assert_currency!(other) if api_supports_currency?(currency) && api_supports_currency?(other) opts = { :at => time, :from => self }.merge(options) Money.new(api.new.convert(value, currency, other, opts), other, opts) elsif fallback! to other, options else raise_no_rate_error(other) end rescue ExternalAPI::APIError if fallback! to other, options else raise end end
ruby
{ "resource": "" }
q23139
Exchange.Money.fallback!
train
def fallback! fallback = Exchange.configuration.api.fallback new_api = fallback.index(api) ? fallback[fallback.index(api) + 1] : fallback.first if new_api @api = new_api return true end return false end
ruby
{ "resource": "" }
q23140
TranslationCenter.Translation.accept
train
def accept # If translation is accepted do nothing unless self.accepted? self.translation_key.accepted_translation_in(self.lang) .try(:update_attribute, :status, TranslationKey::PENDING) # reload the translation key as it has changed self.translation_key.reload self.update_attribute(:status, ACCEPTED) end end
ruby
{ "resource": "" }
q23141
TranslationCenter.Translation.one_translation_per_lang_per_key
train
def one_translation_per_lang_per_key translation_exists = Translation.exists?( lang: self.lang, translator_id: self.translator.id, translator_type: self.translator.class.name, translation_key_id: self.key.id ) unless translation_exists true else false self.errors.add(:lang, I18n.t('.one_translation_per_lang_per_key')) end end
ruby
{ "resource": "" }
q23142
PointlessFeedback.ApplicationHelper.method_missing
train
def method_missing(method, *args, &block) if main_app_url_helper?(method) main_app.send(method, *args) else super end end
ruby
{ "resource": "" }
q23143
SWF.DecisionTaskHandler.tags
train
def tags runner.tag_lists[decision_task.workflow_execution] ||= begin collision = 0 begin decision_task.workflow_execution.tags rescue => e collision += 1 if collision < 10 max_slot_delay = 2**collision - 1 sleep(slot_time * rand(0 .. max_slot_delay)) retry end end end
ruby
{ "resource": "" }
q23144
AlexaRubykit.Response.say_response
train
def say_response(speech, end_session = true, ssml = false) output_speech = add_speech(speech,ssml) { :outputSpeech => output_speech, :shouldEndSession => end_session } end
ruby
{ "resource": "" }
q23145
AlexaRubykit.Response.say_response_with_reprompt
train
def say_response_with_reprompt(speech, reprompt_speech, end_session = true, speech_ssml = false, reprompt_ssml = false) output_speech = add_speech(speech,speech_ssml) reprompt_speech = add_reprompt(reprompt_speech,reprompt_ssml) { :outputSpeech => output_speech, :reprompt => reprompt_speech, :shouldEndSession => end_session } end
ruby
{ "resource": "" }
q23146
AlexaRubykit.Response.build_response
train
def build_response(session_end = true) response_object = build_response_object(session_end) response = Hash.new response[:version] = @version response[:sessionAttributes] = @session_attributes unless @session_attributes.empty? response[:response] = response_object response.to_json end
ruby
{ "resource": "" }
q23147
AlexaRubykit.IntentRequest.add_hash_slots
train
def add_hash_slots(slots) raise ArgumentError, 'Slots can\'t be empty' slots.each do |slot| @slots[:slot[:name]] = Slot.new(slot[:name], slot[:value]) end @slots end
ruby
{ "resource": "" }
q23148
AlexaRubykit.IntentRequest.add_slot
train
def add_slot(name, value) slot = Slot.new(name, value) @slots[:name] = slot slot end
ruby
{ "resource": "" }
q23149
ActiveJob.Execution.perform_now
train
def perform_now deserialize_arguments_if_needed run_callbacks :perform do perform(*arguments) end rescue => exception rescue_with_handler(exception) || raise(exception) end
ruby
{ "resource": "" }
q23150
Rack.Ratelimit.apply_rate_limit?
train
def apply_rate_limit?(env) @exceptions.none? { |e| e.call(env) } && @conditions.all? { |c| c.call(env) } end
ruby
{ "resource": "" }
q23151
Rack.Ratelimit.seconds_until_epoch
train
def seconds_until_epoch(epoch) sec = (epoch - Time.now.to_f).ceil sec = 0 if sec < 0 sec end
ruby
{ "resource": "" }
q23152
ActiveJob.Enqueuing.enqueue
train
def enqueue(options={}) self.scheduled_at = options[:wait].seconds.from_now.to_f if options[:wait] self.scheduled_at = options[:wait_until].to_f if options[:wait_until] self.queue_name = self.class.queue_name_from_part(options[:queue]) if options[:queue] run_callbacks :enqueue do if self.scheduled_at self.class.queue_adapter.enqueue_at self, self.scheduled_at else self.class.queue_adapter.enqueue self end end self end
ruby
{ "resource": "" }
q23153
TournamentSystem.Driver.create_match
train
def create_match(home_team, away_team) home_team, away_team = away_team, home_team unless home_team raise 'Invalid match' unless home_team build_match(home_team, away_team) end
ruby
{ "resource": "" }
q23154
TournamentSystem.Driver.loss_count_hash
train
def loss_count_hash @loss_count_hash ||= matches.each_with_object(Hash.new(0)) { |match, hash| hash[get_match_loser(match)] += 1 } end
ruby
{ "resource": "" }
q23155
SurveyGizmo::API.Answer.to_hash
train
def to_hash { response_id: response_id, question_id: question_id, option_id: option_id, question_pipe: question_pipe, submitted_at: submitted_at, survey_id: survey_id, other_text: other_text, answer_text: option_id || other_text ? nil : answer_text }.reject { |k, v| v.nil? } end
ruby
{ "resource": "" }
q23156
Smalruby.Color.rgb_to_hsl
train
def rgb_to_hsl(red, green, blue) red = round_rgb_color(red) green = round_rgb_color(green) blue = round_rgb_color(blue) color_max = [red, green, blue].max color_min = [red, green, blue].min color_range = color_max - color_min if color_range == 0 return [0, 0, (color_max * 100.0 / 255).to_i] end color_range = color_range.to_f hue = (case color_max when red then HUE_PER_6 * ((green - blue) / color_range) when green then HUE_PER_6 * ((blue - red) / color_range) + HUE_PER_6 * 2 else HUE_PER_6 * ((red - green) / color_range) + HUE_PER_6 * 4 end) cnt = color_range / 2.0 if cnt <= 127 saturation = color_range / (color_max + color_min) * 100 else saturation = color_range / (510 - color_max - color_min) * 100 end lightness = (color_max + color_min) / 2.0 / 255.0 * 100 [hue.round, saturation.round, lightness.round] end
ruby
{ "resource": "" }
q23157
Smalruby.Color.hsl_to_rgb
train
def hsl_to_rgb(h, s, l) h %= 201 s %= 101 l %= 101 if l <= 49 color_max = 255.0 * (l + l * (s / 100.0)) / 100.0 color_min = 255.0 * (l - l * (s / 100.0)) / 100.0 else color_max = 255.0 * (l + (100 - l) * (s / 100.0)) / 100.0 color_min = 255.0 * (l - (100 - l) * (s / 100.0)) / 100.0 end if h < HUE_PER_6 base = h elsif h < HUE_PER_6 * 3 base = (h - HUE_PER_6 * 2).abs elsif h < HUE_PER_6 * 5 base = (h - HUE_PER_6 * 4).abs else base = (200 - h) end base = base / HUE_PER_6 * (color_max - color_min) + color_min divide = (h / HUE_PER_6).to_i red, green, blue = (case divide when 0 then [color_max, base, color_min] when 1 then [base, color_max, color_min] when 2 then [color_min, color_max, base] when 3 then [color_min, base, color_max] when 4 then [base, color_min, color_max] else [color_max, color_min, base] end) [red.round, green.round, blue.round] end
ruby
{ "resource": "" }
q23158
Racker.Template.to_packer
train
def to_packer # Create the new smash packer = Smash.new # Variables packer['variables'] = self['variables'].dup unless self['variables'].nil? || self['variables'].empty? # Builders packer['builders'] = [] unless self['builders'].nil? || self['builders'].empty? logger.info("Processing builders...") self['builders'].each do |name,config| logger.info("Processing builder: #{name} with type: #{config['type']}") # Get the builder for this config builder = get_builder(config['type']) # Have the builder convert the config to packer format packer['builders'] << builder.to_packer(name, config.dup) end # Provisioners packer['provisioners'] = [] unless self['provisioners'].nil? || self['provisioners'].empty? logger.info("Processing provisioners...") self['provisioners'].sort.map do |index, provisioners| provisioners.each do |name,config| logger.debug("Processing provisioner: #{name}") packer['provisioners'] << config.dup end end # Post-Processors packer['post-processors'] = [] unless self['postprocessors'].nil? || self['postprocessors'].empty? logger.info("Processing post-processors...") self['postprocessors'].each do |name,config| logger.debug("Processing post-processor: #{name}") packer['post-processors'] << config.dup unless config.nil? end packer end
ruby
{ "resource": "" }
q23159
SurveyGizmo.Resource.route_params
train
def route_params params = { id: id } self.class.routes.values.each do |route| route.gsub(/:(\w+)/) do |m| m = m.delete(':').to_sym params[m] = self.send(m) end end params end
ruby
{ "resource": "" }
q23160
Smalruby.Character.pen_color=
train
def pen_color=(val) if val.is_a?(Numeric) val %= 201 _, s, l = Color.rgb_to_hsl(*pen_color) val = Color.hsl_to_rgb(val, s, l) end @pen_color = val end
ruby
{ "resource": "" }
q23161
Smalruby.Character.change_pen_color_by
train
def change_pen_color_by(val) h, s, l = Color.rgb_to_hsl(*pen_color) @pen_color = Color.hsl_to_rgb(h + val, s, l) end
ruby
{ "resource": "" }
q23162
Smalruby.Character.pen_shade=
train
def pen_shade=(val) val %= 101 h, s, = *Color.rgb_to_hsl(*pen_color) @pen_color = Color.hsl_to_rgb(h, s, val) end
ruby
{ "resource": "" }
q23163
WillPaginate.ViewHelpers.page_entries_info
train
def page_entries_info(collection, options = {}) entry_name = options[:entry_name] || (collection.empty?? 'entry' : collection.first.class.name.underscore.sub('_', ' ')) if collection.total_pages < 2 case collection.size when 0; "No #{entry_name.pluralize} found" when 1; "Displaying <b>1</b> #{entry_name}" else; "Displaying <b>all #{collection.size}</b> #{entry_name.pluralize}" end else %{Displaying #{entry_name.pluralize} <b>%d&nbsp;-&nbsp;%d</b> of <b>%d</b> in total} % [ collection.offset + 1, collection.offset + collection.length, collection.total_entries ] end end
ruby
{ "resource": "" }
q23164
WillPaginate.LinkRenderer.to_html
train
def to_html links = @options[:page_links] ? windowed_links : [] # previous/next buttons links.unshift page_link_or_span(@collection.previous_page, 'disabled prev_page', @options[:prev_label]) links.push page_link_or_span(@collection.next_page, 'disabled next_page', @options[:next_label]) html = links.join(@options[:separator]) @options[:container] ? @template.content_tag(:div, html, html_attributes) : html end
ruby
{ "resource": "" }
q23165
WillPaginate.LinkRenderer.html_attributes
train
def html_attributes return @html_attributes if @html_attributes @html_attributes = @options.except *(WillPaginate::ViewHelpers.pagination_options.keys - [:class]) # pagination of Post models will have the ID of "posts_pagination" if @options[:container] and @options[:id] === true @html_attributes[:id] = @collection.first.class.name.underscore.pluralize + '_pagination' end @html_attributes end
ruby
{ "resource": "" }
q23166
WillPaginate.LinkRenderer.windowed_links
train
def windowed_links prev = nil visible_page_numbers.inject [] do |links, n| # detect gaps: links << gap_marker if prev and n > prev + 1 links << page_link_or_span(n, 'current') prev = n links end end
ruby
{ "resource": "" }
q23167
WillPaginate.LinkRenderer.stringified_merge
train
def stringified_merge(target, other) other.each do |key, value| key = key.to_s # this line is what it's all about! existing = target[key] if value.is_a?(Hash) and (existing.is_a?(Hash) or existing.nil?) stringified_merge(existing || (target[key] = {}), value) else target[key] = value end end end
ruby
{ "resource": "" }
q23168
TaxCloud.TaxCodeGroup.tax_codes
train
def tax_codes @tax_codes ||= begin response = TaxCloud.client.request :get_ti_cs_by_group, tic_group: group_id tax_codes = TaxCloud::Responses::TaxCodesByGroup.parse response Hash[tax_codes.map { |tic| [tic.ticid, tic] }] end end
ruby
{ "resource": "" }
q23169
TaxCloud.Transaction.authorized
train
def authorized(options = {}) options = { date_authorized: Date.today }.merge(options) request_params = { 'customerID' => customer_id, 'cartID' => cart_id, 'orderID' => order_id, 'dateAuthorized' => xml_date(options[:date_authorized]) } response = TaxCloud.client.request :authorized, request_params TaxCloud::Responses::Authorized.parse response end
ruby
{ "resource": "" }
q23170
TaxCloud.Transaction.returned
train
def returned(options = {}) options = { returned_date: Date.today }.merge(options) request_params = { 'orderID' => order_id, 'cartItems' => { 'CartItem' => cart_items.map(&:to_hash) }, 'returnedDate' => xml_date(options[:returned_date]) } response = TaxCloud.client.request :returned, request_params TaxCloud::Responses::Returned.parse response end
ruby
{ "resource": "" }
q23171
Paperclip.Geometry.to_s
train
def to_s s = "" s << width.to_i.to_s if width > 0 s << "x#{height.to_i}" if height > 0 s << modifier.to_s s end
ruby
{ "resource": "" }
q23172
Paperclip.Shoulda.should_have_attached_file
train
def should_have_attached_file name klass = self.name.gsub(/Test$/, '').constantize matcher = have_attached_file name should matcher.description do assert_accepts(matcher, klass) end end
ruby
{ "resource": "" }
q23173
Paperclip.Shoulda.should_validate_attachment_presence
train
def should_validate_attachment_presence name klass = self.name.gsub(/Test$/, '').constantize matcher = validate_attachment_presence name should matcher.description do assert_accepts(matcher, klass) end end
ruby
{ "resource": "" }
q23174
Paperclip.Shoulda.stub_paperclip_s3
train
def stub_paperclip_s3(model, attachment, extension) definition = model.gsub(" ", "_").classify.constantize. attachment_definitions[attachment.to_sym] path = "http://s3.amazonaws.com/:id/#{definition[:path]}" path.gsub!(/:([^\/\.]+)/) do |match| "([^\/\.]+)" end begin FakeWeb.register_uri(:put, Regexp.new(path), :body => "OK") rescue NameError raise NameError, "the stub_paperclip_s3 shoulda macro requires the fakeweb gem." end end
ruby
{ "resource": "" }
q23175
Danger.DangerJira.check
train
def check(key: nil, url: nil, emoji: ":link:", search_title: true, search_commits: false, fail_on_warning: false, report_missing: true, skippable: true) throw Error("'key' missing - must supply JIRA issue key") if key.nil? throw Error("'url' missing - must supply JIRA installation URL") if url.nil? return if skippable && should_skip_jira?(search_title: search_title) jira_issues = find_jira_issues( key: key, search_title: search_title, search_commits: search_commits ) if !jira_issues.empty? jira_urls = jira_issues.map { |issue| link(href: ensure_url_ends_with_slash(url), issue: issue) }.join(", ") message("#{emoji} #{jira_urls}") elsif report_missing msg = "This PR does not contain any JIRA issue keys in the PR title or commit messages (e.g. KEY-123)" if fail_on_warning fail(msg) else warn(msg) end end end
ruby
{ "resource": "" }
q23176
Paperclip.Thumbnail.make
train
def make src = @file dst = Tempfile.new([@basename, @format ? ".#{@format}" : '']) dst.binmode begin parameters = [] parameters << source_file_options parameters << ":source" parameters << transformation_command parameters << convert_options parameters << ":dest" parameters = parameters.flatten.compact.join(" ").strip.squeeze(" ") success = Paperclip.run("convert", parameters, :source => "#{File.expand_path(src.path)}[0]", :dest => File.expand_path(dst.path)) rescue PaperclipCommandLineError => e raise PaperclipError, "There was an error processing the thumbnail for #{@basename}" if @whiny end dst end
ruby
{ "resource": "" }
q23177
Paperclip.Thumbnail.transformation_command
train
def transformation_command scale, crop = @current_geometry.transformation_to(@target_geometry, crop?) trans = [] trans << "-resize" << %["#{scale}"] unless scale.nil? || scale.empty? trans << "-crop" << %["#{crop}"] << "+repage" if crop trans end
ruby
{ "resource": "" }
q23178
TinyMCE.Configuration.add_options
train
def add_options(options = {}, raw_options = nil) @options.merge!(options.stringify_keys) unless options.blank? @raw_options << raw_options unless raw_options.blank? end
ruby
{ "resource": "" }
q23179
TinyMCE.Configuration.reverse_add_options
train
def reverse_add_options(options = {}, raw_options = nil) @options.reverse_merge!(options.stringify_keys) unless options.blank? @raw_options << raw_options unless raw_options.blank? end
ruby
{ "resource": "" }
q23180
Paperclip.Upfile.content_type
train
def content_type type = (self.path.match(/\.(\w+)$/)[1] rescue "octet-stream").downcase case type when %r"jp(e|g|eg)" then "image/jpeg" when %r"tiff?" then "image/tiff" when %r"png", "gif", "bmp" then "image/#{type}" when "txt" then "text/plain" when %r"html?" then "text/html" when "js" then "application/js" when "csv", "xml", "css" then "text/#{type}" else # On BSDs, `file` doesn't give a result code of 1 if the file doesn't exist. content_type = (Paperclip.run("file", "-b --mime-type :file", :file => self.path).split(':').last.strip rescue "application/x-#{type}") content_type = "application/x-#{type}" if content_type.match(/\(.*?\)/) content_type end end
ruby
{ "resource": "" }
q23181
Shikashi.Sandbox.packet
train
def packet(*args) code = args.pick(String,:code) base_namespace = args.pick(:base_namespace) do nil end no_base_namespace = args.pick(:no_base_namespace) do @no_base_namespace end privileges_ = args.pick(Privileges,:privileges) do Privileges.new end encoding = get_source_encoding(code) || args.pick(:encoding) do nil end hook_handler = nil if base_namespace hook_handler = instantiate_evalhook_handler hook_handler.base_namespace = base_namespace hook_handler.sandbox = self else hook_handler = @hook_handler base_namespace = hook_handler.base_namespace end source = args.pick(:source) do generate_id end self.privileges[source] = privileges_ code = "nil;\n " + code unless no_base_namespace if (eval(base_namespace.to_s).instance_of? Module) code = "module #{base_namespace}\n #{code}\n end\n" else code = "class #{base_namespace}\n #{code}\n end\n" end end if encoding code = "# encoding: #{encoding}\n" + code end evalhook_packet = @hook_handler.packet(code) Shikashi::Sandbox::Packet.new(evalhook_packet, privileges_, source) end
ruby
{ "resource": "" }
q23182
TaxCloud.Address.verify
train
def verify params = to_hash.downcase_keys if TaxCloud.configuration.usps_username params = params.merge( 'uspsUserID' => TaxCloud.configuration.usps_username ) end response = TaxCloud.client.request(:verify_address, params) TaxCloud::Responses::VerifyAddress.parse(response) end
ruby
{ "resource": "" }
q23183
TaxCloud.Address.zip
train
def zip return nil unless zip5 && !zip5.empty? [zip5, zip4].select { |z| z && !z.empty? }.join('-') end
ruby
{ "resource": "" }
q23184
Paperclip.Style.processor_options
train
def processor_options args = {} @other_args.each do |k,v| args[k] = v.respond_to?(:call) ? v.call(attachment) : v end [:processors, :geometry, :format, :whiny, :convert_options].each do |k| (arg = send(k)) && args[k] = arg end args end
ruby
{ "resource": "" }
q23185
Paperclip.Attachment.styles
train
def styles unless @normalized_styles @normalized_styles = {} (@styles.respond_to?(:call) ? @styles.call(self) : @styles).each do |name, args| @normalized_styles[name] = Paperclip::Style.new(name, args.dup, self) end end @normalized_styles end
ruby
{ "resource": "" }
q23186
Paperclip.Attachment.url
train
def url(style_name = default_style, use_timestamp = @use_timestamp) url = original_filename.nil? ? interpolate(@default_url, style_name) : interpolate(@url, style_name) use_timestamp && updated_at ? [url, updated_at].compact.join(url.include?("?") ? "&" : "?") : url end
ruby
{ "resource": "" }
q23187
Elasticity.EMR.add_tags
train
def add_tags(jobflow_id, tags) params = { :operation => 'AddTags', :resource_id => jobflow_id, :tags => tags } aws_result = @aws_request.submit(params) yield aws_result if block_given? end
ruby
{ "resource": "" }
q23188
Elasticity.EMR.describe_cluster
train
def describe_cluster(jobflow_id) params = { :operation => 'DescribeCluster', :cluster_id => jobflow_id, } aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
ruby
{ "resource": "" }
q23189
Elasticity.EMR.describe_step
train
def describe_step(jobflow_id, step_id) params = { :operation => 'DescribeStep', :cluster_id => jobflow_id, :step_id => step_id } aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
ruby
{ "resource": "" }
q23190
Elasticity.EMR.list_clusters
train
def list_clusters(options={}) params = { :operation => 'ListClusters' } params.merge!(:cluster_states => options[:states]) if options[:states] params.merge!(:created_before => options[:created_before].to_i) if options[:created_before] params.merge!(:created_after => options[:created_after].to_i) if options[:created_after] params.merge!(:marker => options[:marker]) if options[:marker] aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
ruby
{ "resource": "" }
q23191
Elasticity.EMR.list_instance_groups
train
def list_instance_groups(jobflow_id) params = { :operation => 'ListInstanceGroups', :cluster_id => jobflow_id, } aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
ruby
{ "resource": "" }
q23192
Elasticity.EMR.list_bootstrap_actions
train
def list_bootstrap_actions(jobflow_id) params = { :operation => 'ListBootstrapActions', :cluster_id => jobflow_id, } aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
ruby
{ "resource": "" }
q23193
Elasticity.EMR.list_steps
train
def list_steps(jobflow_id, options={}) params = { :operation => 'ListSteps', :cluster_id => jobflow_id, } params.merge!(:step_ids => options[:step_ids]) if options[:step_ids] params.merge!(:step_states => options[:step_states]) if options[:step_states] params.merge!(:marker => options[:marker]) if options[:marker] aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
ruby
{ "resource": "" }
q23194
Elasticity.EMR.remove_tags
train
def remove_tags(jobflow_id, keys) params = { :operation => 'RemoveTags', :resource_id => jobflow_id, :tag_keys => keys } aws_result = @aws_request.submit(params) yield aws_result if block_given? end
ruby
{ "resource": "" }
q23195
Elasticity.EMR.set_termination_protection
train
def set_termination_protection(jobflow_ids, protection_enabled=true) params = { :operation => 'SetTerminationProtection', :termination_protected => protection_enabled, :job_flow_ids => jobflow_ids } aws_result = @aws_request.submit(params) yield aws_result if block_given? end
ruby
{ "resource": "" }
q23196
Elasticity.EMR.set_visible_to_all_users
train
def set_visible_to_all_users(jobflow_ids, visible=true) params = { :operation => 'SetVisibleToAllUsers', :visible_to_all_users => visible, :job_flow_ids => jobflow_ids } aws_result = @aws_request.submit(params) yield aws_result if block_given? end
ruby
{ "resource": "" }
q23197
Bonsai.Page.assets
train
def assets Dir["#{directory}/**/*"].sort.select{|path| !File.directory?(path) && !File.basename(path).include?("yml") }.map do |file| file_to_hash(file) end end
ruby
{ "resource": "" }
q23198
Bonsai.Page.to_hash
train
def to_hash hash = { :slug => slug, :permalink => permalink, :name => name, :children => children, :siblings => siblings, :parent => parent, :ancestors => ancestors, :navigation => Bonsai::Navigation.tree, :updated_at => mtime, :created_at => ctime }.merge(formatted_content).merge(disk_assets).merge(Bonsai.site) hash.stringify_keys end
ruby
{ "resource": "" }
q23199
Bonsai.Page.formatted_content
train
def formatted_content formatted_content = content formatted_content.each do |k,v| if v.is_a?(String) and v =~ /\n/ formatted_content[k] = to_markdown(v) end end formatted_content end
ruby
{ "resource": "" }