_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q13000
Haml.Helpers.with_haml_buffer
train
def with_haml_buffer(buffer) @haml_buffer, old_buffer = buffer, @haml_buffer old_buffer.active, old_was_active = false, old_buffer.active? if old_buffer @haml_buffer.active, was_active = true, @haml_buffer.active? yield ensure @haml_buffer.active = was_active old_buffer.active = old_was_active if old_buffer @haml_buffer = old_buffer end
ruby
{ "resource": "" }
q13001
Haml.Helpers.haml_bind_proc
train
def haml_bind_proc(&proc) _hamlout = haml_buffer #double assignment is to avoid warnings _erbout = _erbout = _hamlout.buffer proc { |*args| proc.call(*args) } end
ruby
{ "resource": "" }
q13002
Haml.Parser.process_indent
train
def process_indent(line) return unless line.tabs <= @template_tabs && @template_tabs > 0 to_close = @template_tabs - line.tabs to_close.times {|i| close unless to_close - 1 - i == 0 && continuation_script?(line.text)} end
ruby
{ "resource": "" }
q13003
Haml.Parser.process_line
train
def process_line(line) case line.text[0] when DIV_CLASS; push div(line) when DIV_ID return push plain(line) if %w[{ @ $].include?(line.text[1]) push div(line) when ELEMENT; push tag(line) when COMMENT; push comment(line.text[1..-1].lstrip) when SANITIZE return push plain(line.strip!(3), :escape_html) if line.text[1, 2] == '==' return push script(line.strip!(2), :escape_html) if line.text[1] == SCRIPT return push flat_script(line.strip!(2), :escape_html) if line.text[1] == FLAT_SCRIPT return push plain(line.strip!(1), :escape_html) if line.text[1] == ?\s || line.text[1..2] == '#{' push plain(line) when SCRIPT return push plain(line.strip!(2)) if line.text[1] == SCRIPT line.text = line.text[1..-1] push script(line) when FLAT_SCRIPT; push flat_script(line.strip!(1)) when SILENT_SCRIPT return push haml_comment(line.text[2..-1]) if line.text[1] == SILENT_COMMENT push silent_script(line) when FILTER; push filter(line.text[1..-1].downcase) when DOCTYPE return push doctype(line.text) if line.text[0, 3] == '!!!' return push plain(line.strip!(3), false) if line.text[1, 2] == '==' return push script(line.strip!(2), false) if line.text[1] == SCRIPT return push flat_script(line.strip!(2), false) if line.text[1] == FLAT_SCRIPT return push plain(line.strip!(1), false) if line.text[1] == ?\s || line.text[1..2] == '#{' push plain(line) when ESCAPE line.text = line.text[1..-1] push plain(line) else; push plain(line) end end
ruby
{ "resource": "" }
q13004
Haml.Parser.comment
train
def comment(text) if text[0..1] == '![' revealed = true text = text[1..-1] else revealed = false end conditional, text = balance(text, ?[, ?]) if text[0] == ?[ text.strip! if contains_interpolation?(text) parse = true text = unescape_interpolation(text) else parse = false end if block_opened? && !text.empty? raise SyntaxError.new(Haml::Error.message(:illegal_nesting_content), @next_line.index) end ParseNode.new(:comment, @line.index + 1, :conditional => conditional, :text => text, :revealed => revealed, :parse => parse) end
ruby
{ "resource": "" }
q13005
Haml.Parser.doctype
train
def doctype(text) raise SyntaxError.new(Error.message(:illegal_nesting_header), @next_line.index) if block_opened? version, type, encoding = text[3..-1].strip.downcase.scan(DOCTYPE_REGEX)[0] ParseNode.new(:doctype, @line.index + 1, :version => version, :type => type, :encoding => encoding) end
ruby
{ "resource": "" }
q13006
Haml.Parser.parse_tag
train
def parse_tag(text) match = text.scan(/%([-:\w]+)([-:\w.#\@]*)(.+)?/)[0] raise SyntaxError.new(Error.message(:invalid_tag, text)) unless match tag_name, attributes, rest = match if !attributes.empty? && (attributes =~ /[.#](\.|#|\z)/) raise SyntaxError.new(Error.message(:illegal_element)) end new_attributes_hash = old_attributes_hash = last_line = nil object_ref = :nil attributes_hashes = {} while rest && !rest.empty? case rest[0] when ?{ break if old_attributes_hash old_attributes_hash, rest, last_line = parse_old_attributes(rest) attributes_hashes[:old] = old_attributes_hash when ?( break if new_attributes_hash new_attributes_hash, rest, last_line = parse_new_attributes(rest) attributes_hashes[:new] = new_attributes_hash when ?[ break unless object_ref == :nil object_ref, rest = balance(rest, ?[, ?]) else; break end end if rest && !rest.empty? nuke_whitespace, action, value = rest.scan(/(<>|><|[><])?([=\/\~&!])?(.*)?/)[0] if nuke_whitespace nuke_outer_whitespace = nuke_whitespace.include? '>' nuke_inner_whitespace = nuke_whitespace.include? '<' end end if @options.remove_whitespace nuke_outer_whitespace = true nuke_inner_whitespace = true end if value.nil? value = '' else value.strip! end [tag_name, attributes, attributes_hashes, object_ref, nuke_outer_whitespace, nuke_inner_whitespace, action, value, last_line || @line.index + 1] end
ruby
{ "resource": "" }
q13007
Haml.Parser.is_multiline?
train
def is_multiline?(text) text && text.length > 1 && text[-1] == MULTILINE_CHAR_VALUE && text[-2] == ?\s && text !~ BLOCK_WITH_SPACES end
ruby
{ "resource": "" }
q13008
Haml.Compiler.push_silent
train
def push_silent(text, can_suppress = false) flush_merged_text return if can_suppress && @options.suppress_eval? newline = (text == "end") ? ";" : "\n" @temple << [:code, "#{resolve_newlines}#{text}#{newline}"] @output_line = @output_line + text.count("\n") + newline.count("\n") end
ruby
{ "resource": "" }
q13009
Haml.Compiler.rstrip_buffer!
train
def rstrip_buffer!(index = -1) last = @to_merge[index] if last.nil? push_silent("_hamlout.rstrip!", false) return end case last.first when :text last[1] = last[1].rstrip if last[1].empty? @to_merge.slice! index rstrip_buffer! index end when :script last[1].gsub!(/\(haml_temp, (.*?)\);$/, '(haml_temp.rstrip, \1);') rstrip_buffer! index - 1 else raise SyntaxError.new("[HAML BUG] Undefined entry in Haml::Compiler@to_merge.") end end
ruby
{ "resource": "" }
q13010
Haml.Filters.remove_filter
train
def remove_filter(name) defined.delete name.to_s.downcase if constants.map(&:to_s).include?(name.to_s) remove_const name.to_sym end end
ruby
{ "resource": "" }
q13011
Watir.Waitable.wait_until
train
def wait_until(depr_timeout = nil, depr_message = nil, timeout: nil, message: nil, interval: nil, **opt, &blk) if depr_message || depr_timeout Watir.logger.deprecate 'Using arguments for #wait_until', 'keywords', ids: [:timeout_arguments] timeout = depr_timeout message = depr_message end message ||= proc { |obj| "waiting for true condition on #{obj.inspect}" } # TODO: Consider throwing argument error for mixing block & options proc = create_proc(opt, &blk) Wait.until(timeout: timeout, message: message, interval: interval, object: self, &proc) self end
ruby
{ "resource": "" }
q13012
Watir.Waitable.wait_until_present
train
def wait_until_present(depr_timeout = nil, timeout: nil, interval: nil, message: nil) timeout = depr_timeout if depr_timeout Watir.logger.deprecate "#{self.class}#wait_until_present", "#{self.class}#wait_until(&:present?)", ids: [:wait_until_present] message ||= proc { |obj| "waiting for #{obj.inspect} to become present" } wait_until(timeout: timeout, interval: interval, message: message, element_reset: true, &:present?) end
ruby
{ "resource": "" }
q13013
Watir.Waitable.wait_while_present
train
def wait_while_present(depr_timeout = nil, timeout: nil, interval: nil, message: nil) timeout = depr_timeout if depr_timeout Watir.logger.deprecate "#{self.class}#wait_while_present", "#{self.class}#wait_while(&:present?)", ids: [:wait_while_present] message ||= proc { |obj| "waiting for #{obj.inspect} not to be present" } wait_while(timeout: timeout, interval: interval, message: message, element_reset: true, &:present?) end
ruby
{ "resource": "" }
q13014
Watir.UserEditable.set!
train
def set!(*args) msg = '#set! does not support special keys, use #set instead' raise ArgumentError, msg if args.any? { |v| v.is_a?(::Symbol) } input_value = args.join set input_value[0] return content_editable_set!(*args) if @content_editable element_call { execute_js(:setValue, @element, input_value[0..-2]) } append(input_value[-1]) return if value == input_value raise Exception::Error, "#set! value: '#{value}' does not match expected input: '#{input_value}'" end
ruby
{ "resource": "" }
q13015
Watir.IFrame.execute_script
train
def execute_script(script, *args) args.map! do |e| e.is_a?(Element) ? e.wait_until(&:exists?).wd : e end returned = driver.execute_script(script, *args) browser.wrap_elements_in(self, returned) end
ruby
{ "resource": "" }
q13016
Watir.JSExecution.fire_event
train
def fire_event(event_name) event_name = event_name.to_s.sub(/^on/, '').downcase element_call { execute_js :fireEvent, @element, event_name } end
ruby
{ "resource": "" }
q13017
Watir.Select.include?
train
def include?(str_or_rx) option(text: str_or_rx).exist? || option(label: str_or_rx).exist? end
ruby
{ "resource": "" }
q13018
Watir.Select.select
train
def select(*str_or_rx) results = str_or_rx.flatten.map { |v| select_by v } results.first end
ruby
{ "resource": "" }
q13019
Watir.Select.select_all
train
def select_all(*str_or_rx) results = str_or_rx.flatten.map { |v| select_all_by v } results.first end
ruby
{ "resource": "" }
q13020
Watir.Select.select!
train
def select!(*str_or_rx) results = str_or_rx.flatten.map { |v| select_by!(v, :single) } results.first end
ruby
{ "resource": "" }
q13021
Watir.Select.select_all!
train
def select_all!(*str_or_rx) results = str_or_rx.flatten.map { |v| select_by!(v, :multiple) } results.first end
ruby
{ "resource": "" }
q13022
Watir.FileField.value=
train
def value=(path) path = path.gsub(File::SEPARATOR, File::ALT_SEPARATOR) if File::ALT_SEPARATOR element_call { @element.send_keys path } end
ruby
{ "resource": "" }
q13023
Watir.Navigation.goto
train
def goto(uri) uri = "http://#{uri}" unless uri =~ URI::DEFAULT_PARSER.make_regexp @driver.navigate.to uri @after_hooks.run uri end
ruby
{ "resource": "" }
q13024
Watir.Logger.warn
train
def warn(message, ids: [], &block) msg = ids.empty? ? '' : "[#{ids.map!(&:to_s).map(&:inspect).join(', ')}] " msg += message @logger.warn(msg, &block) unless (@ignored & ids).any? end
ruby
{ "resource": "" }
q13025
Watir.Logger.deprecate
train
def deprecate(old, new, reference: '', ids: []) return if @ignored.include?('deprecations') || (@ignored & ids.map!(&:to_s)).any? msg = ids.empty? ? '' : "[#{ids.map(&:inspect).join(', ')}] " ref_msg = reference.empty? ? '.' : "; see explanation for this deprecation: #{reference}." warn "[DEPRECATION] #{msg}#{old} is deprecated. Use #{new} instead#{ref_msg}" end
ruby
{ "resource": "" }
q13026
Watir.AttributeHelper.attribute
train
def attribute(type, method, attr) typed_attributes[type] << [method, attr] define_attribute(type, method, attr) end
ruby
{ "resource": "" }
q13027
Watir.Browser.execute_script
train
def execute_script(script, *args) args.map! do |e| e.is_a?(Element) ? e.wait_until(&:exists?).wd : e end wrap_elements_in(self, @driver.execute_script(script, *args)) end
ruby
{ "resource": "" }
q13028
Watir.Window.resize_to
train
def resize_to(width, height) Selenium::WebDriver::Dimension.new(Integer(width), Integer(height)).tap do |dimension| use { @driver.manage.window.size = dimension } end end
ruby
{ "resource": "" }
q13029
Watir.Window.move_to
train
def move_to(x_coord, y_coord) Selenium::WebDriver::Point.new(Integer(x_coord), Integer(y_coord)).tap do |point| use { @driver.manage.window.position = point } end end
ruby
{ "resource": "" }
q13030
Watir.Cookies.to_a
train
def to_a @control.all_cookies.map do |e| e.merge(expires: e[:expires] ? e[:expires].to_time : nil) end end
ruby
{ "resource": "" }
q13031
Watir.Cookies.add
train
def add(name, value, opts = {}) cookie = { name: name, value: value } cookie[:secure] = opts[:secure] if opts.key?(:secure) cookie[:path] = opts[:path] if opts.key?(:path) expires = opts[:expires] if expires cookie[:expires] = expires.is_a?(String) ? ::Time.parse(expires) : expires end cookie[:domain] = opts[:domain] if opts.key?(:domain) @control.add_cookie cookie end
ruby
{ "resource": "" }
q13032
Watir.Cookies.load
train
def load(file = '.cookies') YAML.safe_load(IO.read(file), [::Symbol, ::Time]).each do |c| add(c.delete(:name), c.delete(:value), c) end end
ruby
{ "resource": "" }
q13033
Watir.Table.headers
train
def headers(row = nil) row ||= rows.first header_type = row.th.exist? ? 'th' : 'td' row.send("#{header_type}s") end
ruby
{ "resource": "" }
q13034
Watir.RadioSet.select
train
def select(str_or_rx) %i[value label].each do |key| radio = radio(key => str_or_rx) next unless radio.exist? radio.click unless radio.selected? return key == :value ? radio.value : radio.text end raise UnknownObjectException, "Unable to locate radio matching #{str_or_rx.inspect}" end
ruby
{ "resource": "" }
q13035
Watir.RadioSet.selected?
train
def selected?(str_or_rx) found = frame.radio(label: str_or_rx) return found.selected? if found.exist? raise UnknownObjectException, "Unable to locate radio matching #{str_or_rx.inspect}" end
ruby
{ "resource": "" }
q13036
Watir.HasWindow.windows
train
def windows(*args) all = @driver.window_handles.map { |handle| Window.new(self, handle: handle) } if args.empty? all else filter_windows extract_selector(args), all end end
ruby
{ "resource": "" }
q13037
Watir.HasWindow.window
train
def window(*args, &blk) win = Window.new self, extract_selector(args) win.use(&blk) if block_given? win end
ruby
{ "resource": "" }
q13038
Watir.Scroll.to
train
def to(param = :top) args = @object.is_a?(Watir::Element) ? element_scroll(param) : browser_scroll(param) raise ArgumentError, "Don't know how to scroll #{@object} to: #{param}!" if args.nil? @object.browser.execute_script(*args) self end
ruby
{ "resource": "" }
q13039
Watir.Adjacent.children
train
def children(opt = {}) raise ArgumentError, '#children can not take an index value' if opt[:index] xpath_adjacent(opt.merge(adjacent: :child, plural: true)) end
ruby
{ "resource": "" }
q13040
Watir.EventuallyPresent.when_present
train
def when_present(timeout = nil) msg = '#when_present' repl_msg = '#wait_until_present if a wait is still needed' Watir.logger.deprecate msg, repl_msg, ids: [:when_present] timeout ||= Watir.default_timeout message = "waiting for #{selector_string} to become present" if block_given? Wait.until(timeout, message) { present? } yield self else WhenPresentDecorator.new(self, timeout, message) end end
ruby
{ "resource": "" }
q13041
Watir.EventuallyPresent.when_enabled
train
def when_enabled(timeout = nil) msg = '#when_enabled' repl_msg = 'wait_until(&:enabled?)' Watir.logger.deprecate msg, repl_msg, ids: [:when_enabled] timeout ||= Watir.default_timeout message = "waiting for #{selector_string} to become enabled" if block_given? Wait.until(timeout, message) { enabled? } yield self else WhenEnabledDecorator.new(self, timeout, message) end end
ruby
{ "resource": "" }
q13042
Watir.AfterHooks.add
train
def add(after_hook = nil, &block) if block_given? @after_hooks << block elsif after_hook.respond_to? :call @after_hooks << after_hook else raise ArgumentError, 'expected block or object responding to #call' end end
ruby
{ "resource": "" }
q13043
Watir.AfterHooks.run
train
def run # We can't just rescue exception because Firefox automatically closes alert when exception raised return unless @after_hooks.any? && !@browser.alert.exists? each { |after_hook| after_hook.call(@browser) } rescue Selenium::WebDriver::Error::NoSuchWindowError => ex Watir.logger.info "Could not execute After Hooks because browser window was closed #{ex}" end
ruby
{ "resource": "" }
q13044
Watir.Element.exists?
train
def exists? if located? && stale? Watir.logger.deprecate 'Checking `#exists? == false` to determine a stale element', '`#stale? == true`', reference: 'http://watir.com/staleness-changes', ids: [:stale_exists] # TODO: Change this to `reset!` after removing deprecation return false end assert_exists true rescue UnknownObjectException, UnknownFrameException false end
ruby
{ "resource": "" }
q13045
Watir.Element.click
train
def click(*modifiers) # TODO: Should wait_for_enabled be default, or `Button` specific behavior? element_call(:wait_for_enabled) do if modifiers.any? action = driver.action modifiers.each { |mod| action.key_down mod } action.click @element modifiers.each { |mod| action.key_up mod } action.perform else @element.click end end browser.after_hooks.run end
ruby
{ "resource": "" }
q13046
Watir.Element.drag_and_drop_on
train
def drag_and_drop_on(other) assert_is_element other value = element_call(:wait_for_present) do driver.action .drag_and_drop(@element, other.wd) .perform end browser.after_hooks.run value end
ruby
{ "resource": "" }
q13047
Watir.Element.drag_and_drop_by
train
def drag_and_drop_by(right_by, down_by) element_call(:wait_for_present) do driver.action .drag_and_drop_by(@element, right_by, down_by) .perform end end
ruby
{ "resource": "" }
q13048
Watir.Element.attribute_value
train
def attribute_value(attribute_name) attribute_name = attribute_name.to_s.tr('_', '-') if attribute_name.is_a?(::Symbol) element_call { @element.attribute attribute_name } end
ruby
{ "resource": "" }
q13049
Watir.Element.attribute_values
train
def attribute_values result = element_call { execute_js(:attributeValues, @element) } result.keys.each do |key| next unless key == key[/[a-zA-Z\-]*/] result[key.tr('-', '_').to_sym] = result.delete(key) end result end
ruby
{ "resource": "" }
q13050
Watir.Element.center
train
def center point = location dimensions = size Selenium::WebDriver::Point.new(point.x + (dimensions['width'] / 2), point.y + (dimensions['height'] / 2)) end
ruby
{ "resource": "" }
q13051
Watir.Element.visible?
train
def visible? msg = '#visible? behavior will be changing slightly, consider switching to #present? ' \ '(more details: http://watir.com/element-existentialism/)' Watir.logger.warn msg, ids: [:visible_element] displayed = display_check if displayed.nil? && display_check Watir.logger.deprecate 'Checking `#visible? == false` to determine a stale element', '`#stale? == true`', reference: 'http://watir.com/staleness-changes', ids: [:stale_visible] end raise unknown_exception if displayed.nil? displayed end
ruby
{ "resource": "" }
q13052
Watir.Element.present?
train
def present? displayed = display_check if displayed.nil? && display_check Watir.logger.deprecate 'Checking `#present? == false` to determine a stale element', '`#stale? == true`', reference: 'http://watir.com/staleness-changes', ids: [:stale_present] end displayed rescue UnknownObjectException, UnknownFrameException false end
ruby
{ "resource": "" }
q13053
Watir.ElementCollection.[]
train
def [](value) if value.is_a?(Range) to_a[value] elsif @selector.key? :adjacent to_a[value] || element_class.new(@query_scope, invalid_locator: true) elsif @to_a && @to_a[value] @to_a[value] else element_class.new(@query_scope, @selector.merge(index: value)) end end
ruby
{ "resource": "" }
q13054
Watir.ElementCollection.to_a
train
def to_a hash = {} @to_a ||= elements_with_tags.map.with_index do |(el, tag_name), idx| selector = @selector.dup selector[:index] = idx unless idx.zero? element = element_class.new(@query_scope, selector) if [HTMLElement, Input].include? element.class construct_subtype(element, hash, tag_name).tap { |e| e.cache = el } else element.tap { |e| e.cache = el } end end end
ruby
{ "resource": "" }
q13055
Rugged.Commit.diff
train
def diff(*args) args.unshift(parents.first) if args.size == 1 && args.first.is_a?(Hash) self.tree.diff(*args) end
ruby
{ "resource": "" }
q13056
Rugged.Repository.checkout
train
def checkout(target, options = {}) options[:strategy] ||= :safe options.delete(:paths) return checkout_head(options) if target == "HEAD" if target.kind_of?(Rugged::Branch) branch = target else branch = branches[target] end if branch self.checkout_tree(branch.target, options) if branch.remote? references.create("HEAD", branch.target_id, force: true) else references.create("HEAD", branch.canonical_name, force: true) end else commit = Commit.lookup(self, self.rev_parse_oid(target)) references.create("HEAD", commit.oid, force: true) self.checkout_tree(commit, options) end end
ruby
{ "resource": "" }
q13057
Rugged.Repository.create_branch
train
def create_branch(name, sha_or_ref = "HEAD") case sha_or_ref when Rugged::Object target = sha_or_ref.oid else target = rev_parse_oid(sha_or_ref) end branches.create(name, target) end
ruby
{ "resource": "" }
q13058
Rugged.Repository.blob_at
train
def blob_at(revision, path) tree = Rugged::Commit.lookup(self, revision).tree begin blob_data = tree.path(path) rescue Rugged::TreeError return nil end blob = Rugged::Blob.lookup(self, blob_data[:oid]) (blob.type == :blob) ? blob : nil end
ruby
{ "resource": "" }
q13059
Rugged.Repository.push
train
def push(remote_or_url, *args) unless remote_or_url.kind_of? Remote remote_or_url = remotes[remote_or_url] || remotes.create_anonymous(remote_or_url) end remote_or_url.push(*args) end
ruby
{ "resource": "" }
q13060
Rugged.SubmoduleCollection.clone_submodule
train
def clone_submodule(repo, fetch_options) # the remote was just added by setup_add, no need to check presence repo.remotes['origin'].fetch(fetch_options) repo.branches.create('master','origin/master') repo.branches['master'].upstream = repo.branches['origin/master'] repo.checkout_head(strategy: :force) end
ruby
{ "resource": "" }
q13061
OAuth2.Client.build_access_token
train
def build_access_token(response, access_token_opts, access_token_class) access_token_class.from_hash(self, response.parsed.merge(access_token_opts)).tap do |access_token| access_token.response = response if access_token.respond_to?(:response=) end end
ruby
{ "resource": "" }
q13062
OAuth2.Authenticator.apply
train
def apply(params) case mode.to_sym when :basic_auth apply_basic_auth(params) when :request_body apply_params_auth(params) else raise NotImplementedError end end
ruby
{ "resource": "" }
q13063
OAuth2.Authenticator.apply_basic_auth
train
def apply_basic_auth(params) headers = params.fetch(:headers, {}) headers = basic_auth_header.merge(headers) params.merge(:headers => headers) end
ruby
{ "resource": "" }
q13064
OAuth2.Response.content_type
train
def content_type return nil unless response.headers ((response.headers.values_at('content-type', 'Content-Type').compact.first || '').split(';').first || '').strip end
ruby
{ "resource": "" }
q13065
OAuth2.MACToken.request
train
def request(verb, path, opts = {}, &block) url = client.connection.build_url(path, opts[:params]).to_s opts[:headers] ||= {} opts[:headers]['Authorization'] = header(verb, url) @client.request(verb, path, opts, &block) end
ruby
{ "resource": "" }
q13066
OAuth2.MACToken.header
train
def header(verb, url) timestamp = Time.now.utc.to_i nonce = Digest::MD5.hexdigest([timestamp, SecureRandom.hex].join(':')) uri = URI.parse(url) raise(ArgumentError, "could not parse \"#{url}\" into URI") unless uri.is_a?(URI::HTTP) mac = signature(timestamp, nonce, verb, uri) "MAC id=\"#{token}\", ts=\"#{timestamp}\", nonce=\"#{nonce}\", mac=\"#{mac}\"" end
ruby
{ "resource": "" }
q13067
OAuth2.MACToken.signature
train
def signature(timestamp, nonce, verb, uri) signature = [ timestamp, nonce, verb.to_s.upcase, uri.request_uri, uri.host, uri.port, '', nil ].join("\n") Base64.strict_encode64(OpenSSL::HMAC.digest(@algorithm, secret, signature)) end
ruby
{ "resource": "" }
q13068
OAuth2.MACToken.algorithm=
train
def algorithm=(alg) @algorithm = begin case alg.to_s when 'hmac-sha-1' OpenSSL::Digest::SHA1.new when 'hmac-sha-256' OpenSSL::Digest::SHA256.new else raise(ArgumentError, 'Unsupported algorithm') end end end
ruby
{ "resource": "" }
q13069
OAuth2.AccessToken.refresh
train
def refresh(params = {}, access_token_opts = {}, access_token_class = self.class) raise('A refresh_token is not available') unless refresh_token params[:grant_type] = 'refresh_token' params[:refresh_token] = refresh_token new_token = @client.get_token(params, access_token_opts, access_token_class) new_token.options = options new_token.refresh_token = refresh_token unless new_token.refresh_token new_token end
ruby
{ "resource": "" }
q13070
OAuth2.AccessToken.request
train
def request(verb, path, opts = {}, &block) configure_authentication!(opts) @client.request(verb, path, opts, &block) end
ruby
{ "resource": "" }
q13071
Git.Log.run_log
train
def run_log log = @base.lib.full_log_commits(:count => @count, :object => @object, :path_limiter => @path, :since => @since, :author => @author, :grep => @grep, :skip => @skip, :until => @until, :between => @between) @commits = log.map { |c| Git::Object::Commit.new(@base, c['sha'], c) } end
ruby
{ "resource": "" }
q13072
Git.Branches.[]
train
def [](branch_name) @branches.values.inject(@branches) do |branches, branch| branches[branch.full] ||= branch # This is how Git (version 1.7.9.5) works. # Lets you ignore the 'remotes' if its at the beginning of the branch full name (even if is not a real remote branch). branches[branch.full.sub('remotes/', '')] ||= branch if branch.full =~ /^remotes\/.+/ branches end[branch_name.to_s] end
ruby
{ "resource": "" }
q13073
Git.Lib.describe
train
def describe(committish=nil, opts={}) arr_opts = [] arr_opts << '--all' if opts[:all] arr_opts << '--tags' if opts[:tags] arr_opts << '--contains' if opts[:contains] arr_opts << '--debug' if opts[:debug] arr_opts << '--long' if opts[:long] arr_opts << '--always' if opts[:always] arr_opts << '--exact-match' if opts[:exact_match] || opts[:"exact-match"] arr_opts << '--dirty' if opts['dirty'] == true arr_opts << "--dirty=#{opts['dirty']}" if opts['dirty'].is_a?(String) arr_opts << "--abbrev=#{opts['abbrev']}" if opts[:abbrev] arr_opts << "--candidates=#{opts['candidates']}" if opts[:candidates] arr_opts << "--match=#{opts['match']}" if opts[:match] arr_opts << committish if committish return command('describe', arr_opts) end
ruby
{ "resource": "" }
q13074
Git.Lib.commit_data
train
def commit_data(sha) sha = sha.to_s cdata = command_lines('cat-file', ['commit', sha]) process_commit_data(cdata, sha, 0) end
ruby
{ "resource": "" }
q13075
Git.Lib.read_tree
train
def read_tree(treeish, opts = {}) arr_opts = [] arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix] arr_opts += [treeish] command('read-tree', arr_opts) end
ruby
{ "resource": "" }
q13076
Git.Lib.archive
train
def archive(sha, file = nil, opts = {}) opts[:format] ||= 'zip' if opts[:format] == 'tgz' opts[:format] = 'tar' opts[:add_gzip] = true end if !file tempfile = Tempfile.new('archive') file = tempfile.path # delete it now, before we write to it, so that Ruby doesn't delete it # when it finalizes the Tempfile. tempfile.close! end arr_opts = [] arr_opts << "--format=#{opts[:format]}" if opts[:format] arr_opts << "--prefix=#{opts[:prefix]}" if opts[:prefix] arr_opts << "--remote=#{opts[:remote]}" if opts[:remote] arr_opts << sha arr_opts << '--' << opts[:path] if opts[:path] command('archive', arr_opts, true, (opts[:add_gzip] ? '| gzip' : '') + " > #{escape file}") return file end
ruby
{ "resource": "" }
q13077
Git.Lib.current_command_version
train
def current_command_version output = command('version', [], false) version = output[/\d+\.\d+(\.\d+)+/] version.split('.').collect {|i| i.to_i} end
ruby
{ "resource": "" }
q13078
Git.Lib.log_common_options
train
def log_common_options(opts) arr_opts = [] arr_opts << "-#{opts[:count]}" if opts[:count] arr_opts << "--no-color" arr_opts << "--since=#{opts[:since]}" if opts[:since].is_a? String arr_opts << "--until=#{opts[:until]}" if opts[:until].is_a? String arr_opts << "--grep=#{opts[:grep]}" if opts[:grep].is_a? String arr_opts << "--author=#{opts[:author]}" if opts[:author].is_a? String arr_opts << "#{opts[:between][0].to_s}..#{opts[:between][1].to_s}" if (opts[:between] && opts[:between].size == 2) arr_opts end
ruby
{ "resource": "" }
q13079
Git.Lib.log_path_options
train
def log_path_options(opts) arr_opts = [] arr_opts << opts[:object] if opts[:object].is_a? String arr_opts << '--' << opts[:path_limiter] if opts[:path_limiter] arr_opts end
ruby
{ "resource": "" }
q13080
Git.Base.is_local_branch?
train
def is_local_branch?(branch) branch_names = self.branches.local.map {|b| b.name} branch_names.include?(branch) end
ruby
{ "resource": "" }
q13081
Git.Base.is_remote_branch?
train
def is_remote_branch?(branch) branch_names = self.branches.remote.map {|b| b.name} branch_names.include?(branch) end
ruby
{ "resource": "" }
q13082
Git.Base.is_branch?
train
def is_branch?(branch) branch_names = self.branches.map {|b| b.name} branch_names.include?(branch) end
ruby
{ "resource": "" }
q13083
Git.Base.commit_all
train
def commit_all(message, opts = {}) opts = {:add_all => true}.merge(opts) self.lib.commit(message, opts) end
ruby
{ "resource": "" }
q13084
Git.Base.with_index
train
def with_index(new_index) # :yields: new_index old_index = @index set_index(new_index, false) return_value = yield @index set_index(old_index) return_value end
ruby
{ "resource": "" }
q13085
Creek.Creek::Sheet.rows_generator
train
def rows_generator include_meta_data=false, use_simple_rows_format=false path = if @sheetfile.start_with? "/xl/" or @sheetfile.start_with? "xl/" then @sheetfile else "xl/#{@sheetfile}" end if @book.files.file.exist?(path) # SAX parsing, Each element in the stream comes through as two events: # one to open the element and one to close it. opener = Nokogiri::XML::Reader::TYPE_ELEMENT closer = Nokogiri::XML::Reader::TYPE_END_ELEMENT Enumerator.new do |y| row, cells, cell = nil, {}, nil cell_type = nil cell_style_idx = nil @book.files.file.open(path) do |xml| Nokogiri::XML::Reader.from_io(xml).each do |node| if (node.name.eql? 'row') and (node.node_type.eql? opener) row = node.attributes row['cells'] = Hash.new cells = Hash.new y << (include_meta_data ? row : cells) if node.self_closing? elsif (node.name.eql? 'row') and (node.node_type.eql? closer) processed_cells = fill_in_empty_cells(cells, row['r'], cell, use_simple_rows_format) if @images_present processed_cells.each do |cell_name, cell_value| next unless cell_value.nil? processed_cells[cell_name] = images_at(cell_name) end end row['cells'] = processed_cells y << (include_meta_data ? row : processed_cells) elsif (node.name.eql? 'c') and (node.node_type.eql? opener) cell_type = node.attributes['t'] cell_style_idx = node.attributes['s'] cell = node.attributes['r'] elsif (['v', 't'].include? node.name) and (node.node_type.eql? opener) unless cell.nil? node.read cells[(use_simple_rows_format ? cell.tr("0-9", "") : cell)] = convert(node.value, cell_type, cell_style_idx) end end end end end end end
ruby
{ "resource": "" }
q13086
Creek.Creek::Sheet.fill_in_empty_cells
train
def fill_in_empty_cells(cells, row_number, last_col, use_simple_rows_format) new_cells = Hash.new unless cells.empty? last_col = last_col.gsub(row_number, '') ("A"..last_col).to_a.each do |column| id = use_simple_rows_format ? "#{column}" : "#{column}#{row_number}" new_cells[id] = cells[id] end end new_cells end
ruby
{ "resource": "" }
q13087
Creek.Creek::Sheet.extract_drawing_filepath
train
def extract_drawing_filepath # Read drawing relationship ID from the sheet. sheet_filepath = "xl/#{@sheetfile}" drawing = parse_xml(sheet_filepath).css('drawing').first return if drawing.nil? drawing_rid = drawing.attributes['id'].value # Read sheet rels to find drawing file's location. sheet_rels_filepath = expand_to_rels_path(sheet_filepath) parse_xml(sheet_rels_filepath).css("Relationship[@Id='#{drawing_rid}']").first.attributes['Target'].value end
ruby
{ "resource": "" }
q13088
Rollbar.Notifier.log
train
def log(level, *args) return 'disabled' unless enabled? message, exception, extra, context = extract_arguments(args) use_exception_level_filters = use_exception_level_filters?(extra) return 'ignored' if ignored?(exception, use_exception_level_filters) begin status = call_before_process(:level => level, :exception => exception, :message => message, :extra => extra) return 'ignored' if status == 'ignored' rescue Rollbar::Ignore return 'ignored' end level = lookup_exception_level(level, exception, use_exception_level_filters) begin report(level, message, exception, extra, context) rescue StandardError, SystemStackError => e report_internal_error(e) 'error' end end
ruby
{ "resource": "" }
q13089
Rollbar.Notifier.process_from_async_handler
train
def process_from_async_handler(payload) payload = Rollbar::JSON.load(payload) if payload.is_a?(String) item = Item.build_with(payload, :notifier => self, :configuration => configuration, :logger => logger) Rollbar.silenced do begin process_item(item) rescue StandardError => e report_internal_error(e) raise end end end
ruby
{ "resource": "" }
q13090
Rollbar.Notifier.report_internal_error
train
def report_internal_error(exception) log_error '[Rollbar] Reporting internal error encountered while sending data to Rollbar.' configuration.execute_hook(:on_report_internal_error, exception) begin item = build_item('error', nil, exception, { :internal => true }, nil) rescue StandardError => e send_failsafe('build_item in exception_data', e) log_error "[Rollbar] Exception: #{exception}" return end begin process_item(item) rescue StandardError => e send_failsafe('error in process_item', e) log_error "[Rollbar] Item: #{item}" return end begin log_instance_link(item['data']) rescue StandardError => e send_failsafe('error logging instance link', e) log_error "[Rollbar] Item: #{item}" return end end
ruby
{ "resource": "" }
q13091
Rollbar.Notifier.build_item
train
def build_item(level, message, exception, extra, context) options = { :level => level, :message => message, :exception => exception, :extra => extra, :configuration => configuration, :logger => logger, :scope => scope_object, :notifier => self, :context => context } item = Item.new(options) item.build item end
ruby
{ "resource": "" }
q13092
RDL::Typecheck.Env.bind
train
def bind(var, typ, force: false) raise RuntimeError, "Can't update variable with fixed type" if !force && @env[var] && @env[var][:fixed] result = Env.new result.env = @env.merge(var => {type: typ, fixed: false}) return result end
ruby
{ "resource": "" }
q13093
RDL::Typecheck.Env.merge
train
def merge(other) result = Env.new result.env = @env.merge(other.env) return result end
ruby
{ "resource": "" }
q13094
RDL::Type.MethodType.match
train
def match(other) other = other.type if other.instance_of? AnnotatedArgType return true if other.instance_of? WildQuery return false unless other.instance_of? MethodType return false unless @ret.match(other.ret) if @block == nil return false unless other.block == nil else return false if other.block == nil return false unless @block.match(other.block) end # Check arg matches; logic is similar to pre_cond states = [[0,0]] # [position in self, position in other] until states.empty? s_arg, o_arg = states.pop return true if s_arg == @args.size && o_arg == other.args.size # everything matches next if s_arg >= @args.size # match not possible, not enough args in self if @args[s_arg].instance_of? DotsQuery then if o_arg == other.args.size # no args left in other, skip ... states << [s_arg+1, o_arg] else states << [s_arg+1, o_arg+1] # match, no more matches to ... states << [s_arg, o_arg+1] # match, more matches to ... coming end else next if o_arg == other.args.size # match not possible, not enough args in other s_arg_t = @args[s_arg] s_arg_t = s_arg_t.type if s_arg_t.instance_of? AnnotatedArgType o_arg_t = other.args[o_arg] o_arg_t = o_arg_t.type if o_arg_t.instance_of? AnnotatedArgType next unless s_arg_t.match(o_arg_t) states << [s_arg+1, o_arg+1] end end return false end
ruby
{ "resource": "" }
q13095
TinyMCE::Rails.Helper.tinymce
train
def tinymce(config=:default, options={}) javascript_tag(nonce: true) do unless @_tinymce_configurations_added concat tinymce_configurations_javascript concat "\n" @_tinymce_configurations_added = true end concat tinymce_javascript(config, options) end end
ruby
{ "resource": "" }
q13096
TinyMCE::Rails.Helper.tinymce_javascript
train
def tinymce_javascript(config=:default, options={}) options, config = config, :default if config.is_a?(Hash) options = Configuration.new(options) "TinyMCERails.initialize('#{config}', #{options.to_javascript});".html_safe end
ruby
{ "resource": "" }
q13097
TinyMCE::Rails.Helper.tinymce_configurations_javascript
train
def tinymce_configurations_javascript(options={}) javascript = [] TinyMCE::Rails.each_configuration do |name, config| config = config.merge(options) if options.present? javascript << "TinyMCERails.configuration.#{name} = #{config.to_javascript};".html_safe end safe_join(javascript, "\n") end
ruby
{ "resource": "" }
q13098
ActionDispatch::Routing.Mapper.devise_verification_code
train
def devise_verification_code(mapping, controllers) resource :paranoid_verification_code, only: [:show, :update], path: mapping.path_names[:verification_code], controller: controllers[:paranoid_verification_code] end
ruby
{ "resource": "" }
q13099
Devise::Models.PasswordExpirable.password_too_old?
train
def password_too_old? return false if new_record? return false unless password_expiration_enabled? return false if expire_password_on_demand? password_changed_at < expire_password_after.seconds.ago end
ruby
{ "resource": "" }