_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q6900
URIx.URIx.claim_interface
train
def claim_interface devices = usb.devices(:idVendor => VENDOR_ID, :idProduct => PRODUCT_ID) unless devices.first then return end @device = devices.first @handle = @device.open @handle.detach_kernel_driver(HID_INTERFACE) @handle.claim_interface( HID_INTERFACE ) end
ruby
{ "resource": "" }
q6901
URIx.URIx.set_output
train
def set_output pin, state state = false if state == :low state = true if state == :high if ( @pin_states >> ( pin - 1 )).odd? && ( state == false ) or ( @pin_states >> ( pin - 1 )).even? && ( state == true ) then mask = 0 + ( 1 << ( pin - 1 )) @pin_states ^= mask end write_output end
ruby
{ "resource": "" }
q6902
URIx.URIx.set_pin_mode
train
def set_pin_mode pin, mode if ( @pin_modes >> ( pin - 1 )).odd? && ( mode == :input ) or ( @pin_modes >> ( pin - 1 )).even? && ( mode == :output ) then mask = 0 + ( 1 << ( pin - 1 )) @pin_modes ^= mask end end
ruby
{ "resource": "" }
q6903
Montage.Client.auth
train
def auth build_response("token") do connection.post do |req| req.headers.delete("Authorization") req.url "auth/" req.body = { username: username, password: password }.to_json end end end
ruby
{ "resource": "" }
q6904
Montage.Client.build_response
train
def build_response(resource_name) response = yield resource = response_successful?(response) ? resource_name : "error" response_object = Montage::Response.new(response.status, response.body, resource) set_token(response_object.token.value) if resource_name == "token" && response.success? response_object end
ruby
{ "resource": "" }
q6905
Montage.Client.connection
train
def connection @connect ||= Faraday.new do |f| f.adapter :net_http f.headers = connection_headers f.url_prefix = "#{default_url_prefix}/api/v#{api_version}/" f.response :json, content_type: /\bjson$/ end end
ruby
{ "resource": "" }
q6906
FamilytreeV2.Communicator.write_note
train
def write_note(options) url = "#{Base}note" note = Org::Familysearch::Ws::Familytree::V2::Schema::Note.new note.build(options) familytree = Org::Familysearch::Ws::Familytree::V2::Schema::FamilyTree.new familytree.notes = [note] res = @fs_communicator.post(url,familytree.to_json) familytree = Org::Familysearch::Ws::Familytree::V2::Schema::FamilyTree.from_json JSON.parse(res.body) return familytree.notes.first end
ruby
{ "resource": "" }
q6907
FamilytreeV2.Communicator.combine
train
def combine(person_array) url = Base + 'person' version_persons = self.person person_array, :genders => 'none', :events => 'none', :names => 'none' combine_person = Org::Familysearch::Ws::Familytree::V2::Schema::Person.new combine_person.create_combine(version_persons) familytree = Org::Familysearch::Ws::Familytree::V2::Schema::FamilyTree.new familytree.persons = [combine_person] res = @fs_communicator.post(url,familytree.to_json) familytree = Org::Familysearch::Ws::Familytree::V2::Schema::FamilyTree.from_json JSON.parse(res.body) return familytree.persons[0] end
ruby
{ "resource": "" }
q6908
Roroacms.Admin::CommentsController.edit
train
def edit # add breadcrumb and set title add_breadcrumb I18n.t("controllers.admin.comments.edit.breadcrumb") set_title(I18n.t("controllers.admin.comments.edit.title")) @comment = Comment.find(params[:id]) end
ruby
{ "resource": "" }
q6909
Roroacms.Admin::CommentsController.update
train
def update @comment = Comment.find(params[:id]) atts = comments_params respond_to do |format| if @comment.update_attributes(atts) format.html { redirect_to edit_admin_comment_path(@comment), notice: I18n.t("controllers.admin.comments.update.flash.success") } else format.html { # add breadcrumb and set title add_breadcrumb I18n.t("controllers.admin.comments.edit.breadcrumb") render action: "edit" } end end end
ruby
{ "resource": "" }
q6910
Roroacms.Admin::CommentsController.destroy
train
def destroy @comment = Comment.find(params[:id]) @comment.destroy respond_to do |format| format.html { redirect_to admin_comments_path, notice: I18n.t("controllers.admin.comments.destroy.flash.success") } end end
ruby
{ "resource": "" }
q6911
Roroacms.Admin::CommentsController.bulk_update
train
def bulk_update # This is what makes the update func = Comment.bulk_update params respond_to do |format| format.html { redirect_to admin_comments_path, notice: func == 'ntd' ? I18n.t("controllers.admin.comments.bulk_update.flash.nothing_to_do") : I18n.t("controllers.admin.comments.bulk_update.flash.success", func: func) } end end
ruby
{ "resource": "" }
q6912
Roroacms.Admin::CommentsController.mark_as_spam
train
def mark_as_spam comment = Comment.find(params[:id]) comment.comment_approved = "S" comment.is_spam = "S" respond_to do |format| if comment.save format.html { redirect_to admin_comments_path, notice: I18n.t("controllers.admin.comments.mark_as_spam.flash.success") } else format.html { render action: "index" } end end end
ruby
{ "resource": "" }
q6913
SwaggerDocsGenerator.Sort.sort_by_tag
train
def sort_by_tag by_tag = Hash[@routes[:paths].sort_by do |_key, value| value.first[1]['tags'] end] place_readme_first(by_tag) end
ruby
{ "resource": "" }
q6914
ActiveTracker.Tracker.method_missing
train
def method_missing(m, *args, &block) if @tracker_names.include? m @tracker_blocks[m] = block else super(name, *args, &block) end end
ruby
{ "resource": "" }
q6915
Numerals.Rounding.truncate
train
def truncate(numeral, round_up=nil) check_base numeral unless simplifying? # TODO: could simplify this just skiping on free? n = precision(numeral) if n == 0 return numeral if numeral.repeating? # or rails inexact... n = numeral.digits.size end unless n >= numeral.digits.size && numeral.approximate? if n < numeral.digits.size - 1 rest_digits = numeral.digits[n+1..-1] else rest_digits = [] end if numeral.repeating? && numeral.repeat < numeral.digits.size && n >= numeral.repeat rest_digits += numeral.digits[numeral.repeat..-1] end digits = numeral.digits[0, n] if digits.size < n digits += (digits.size...n).map{|i| numeral.digit_value_at(i)} end if numeral.base % 2 == 0 tie_digit = numeral.base / 2 max_lo = tie_digit - 1 else max_lo = numeral.base / 2 end next_digit = numeral.digit_value_at(n) if next_digit == 0 unless round_up.nil? && rest_digits.all?{|d| d == 0} round_up = :lo end elsif next_digit <= max_lo # next_digit < tie_digit round_up = :lo elsif next_digit == tie_digit if round_up || rest_digits.any?{|d| d != 0} round_up = :hi else round_up = :tie end else # next_digit > tie_digit round_up = :hi end numeral = Numeral[ digits, point: numeral.point, sign: numeral.sign, base: numeral.base, normalize: :approximate ] end end [numeral, round_up] end
ruby
{ "resource": "" }
q6916
Numerals.Rounding.adjust
train
def adjust(numeral, round_up) check_base numeral point, digits = Flt::Support.adjust_digits( numeral.point, numeral.digits.digits_array, round_mode: @mode, negative: numeral.sign == -1, round_up: round_up, base: numeral.base ) if numeral.zero? && simplifying? digits = [] point = 0 end normalization = simplifying? ? :exact : :approximate Numeral[digits, point: point, base: numeral.base, sign: numeral.sign, normalize: normalization] end
ruby
{ "resource": "" }
q6917
ActiveRecord::Base::TablelessModel.ClassMethods.column
train
def column(name, sql_type = :text, default = nil, null = true) columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null) end
ruby
{ "resource": "" }
q6918
Gitolite.Manager.create_user
train
def create_user(username, rsa_pub_key, rsa_pub_key_name) key_name = "#{username}@#{rsa_pub_key_name}" key_path = @configuration.user_key_path(key_name) if users_public_keys().include?(key_path) raise ::Gitolite::Duplicate, "Public key (#{rsa_pub_key_name}) already exists for user (#{username}) on gitolite server" end add_commit_file(key_path,rsa_pub_key, "Added public key (#{rsa_pub_key_name}) for user (#{username}) ") key_path end
ruby
{ "resource": "" }
q6919
TriglavClient.MessagesApi.send_messages
train
def send_messages(messages, opts = {}) data, _status_code, _headers = send_messages_with_http_info(messages, opts) return data end
ruby
{ "resource": "" }
q6920
Buzztools.File.real_path
train
def real_path(aPath) (path = Pathname.new(::File.expand_path(aPath))) && path.realpath.to_s end
ruby
{ "resource": "" }
q6921
Buzztools.File.expand_magic_path
train
def expand_magic_path(aPath,aBasePath=nil) aBasePath ||= Dir.pwd path = aPath if path.begins_with?('...') rel_part = path.split3(/\.\.\.[\/\\]/)[2] return find_upwards(aBasePath,rel_part) end path_combine(aBasePath,aPath) end
ruby
{ "resource": "" }
q6922
Grapple.HtmlTableBuilder.container
train
def container(inner_html) html = '' html << before_container html << template.tag('div', container_attributes, true) + "\n" html << inner_html html << "</div>\n" html << after_container return html.html_safe end
ruby
{ "resource": "" }
q6923
Yargi.Markable.add_marks
train
def add_marks(marks=nil) marks.each_pair {|k,v| self[k]=v} if marks if block_given? result = yield self add_marks(result) if Hash===result end end
ruby
{ "resource": "" }
q6924
Yargi.Markable.to_h
train
def to_h(nonil=true) return {} unless @marks marks = @marks.dup if nonil marks.delete_if {|k,v| v.nil?} end marks end
ruby
{ "resource": "" }
q6925
DQReadability.Document.author
train
def author # Let's grab this author: # <meta name="dc.creator" content="Finch - http://www.getfinch.com" /> author_elements = @html.xpath('//meta[@name = "dc.creator"]') unless author_elements.empty? author_elements.each do |element| if element['content'] return element['content'].strip end end end # Now let's try to grab this # <span class="byline author vcard"><span>By</span><cite class="fn">Austin Fonacier</cite></span> # <div class="author">By</div><div class="author vcard"><a class="url fn" href="http://austinlivesinyoapp.com/">Austin Fonacier</a></div> author_elements = @html.xpath('//*[contains(@class, "vcard")]//*[contains(@class, "fn")]') unless author_elements.empty? author_elements.each do |element| if element.text return element.text.strip end end end # Now let's try to grab this # <a rel="author" href="http://dbanksdesign.com">Danny Banks (rel)</a> # TODO: strip out the (rel)? author_elements = @html.xpath('//a[@rel = "author"]') unless author_elements.empty? author_elements.each do |element| if element.text return element.text.strip end end end author_elements = @html.xpath('//*[@id = "author"]') unless author_elements.empty? author_elements.each do |element| if element.text return element.text.strip end end end end
ruby
{ "resource": "" }
q6926
BarkestCore.UsersHelper.gravatar_for
train
def gravatar_for(user, options = {}) options = { size: 80, default: :identicon }.merge(options || {}) options[:default] = options[:default].to_s.to_sym unless options[:default].nil? || options[:default].is_a?(Symbol) gravatar_id = Digest::MD5::hexdigest(user.email.downcase) size = options[:size] default = [:mm, :identicon, :monsterid, :wavatar, :retro].include?(options[:default]) ? "&d=#{options[:default]}" : '' gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}?s=#{size}#{default}" image_tag(gravatar_url, alt: user.name, class: 'gravatar', style: "width: #{size}px, height: #{size}px") end
ruby
{ "resource": "" }
q6927
Neon.ArgumentHelpers.extract_session
train
def extract_session(args) if args.last.is_a?(Session::Rest) || args.last.is_a?(Session::Embedded) args.pop else Session.current end end
ruby
{ "resource": "" }
q6928
ComfyPress::IsMirrored.InstanceMethods.mirrors
train
def mirrors return [] unless self.site.is_mirrored? (Cms::Site.mirrored - [self.site]).collect do |site| case self when Cms::Layout then site.layouts.find_by_identifier(self.identifier) when Cms::Page then site.pages.find_by_full_path(self.full_path) when Cms::Snippet then site.snippets.find_by_identifier(self.identifier) end end.compact end
ruby
{ "resource": "" }
q6929
ComfyPress::IsMirrored.InstanceMethods.sync_mirror
train
def sync_mirror return if self.is_mirrored || !self.site.is_mirrored? (Cms::Site.mirrored - [self.site]).each do |site| mirror = case self when Cms::Layout m = site.layouts.find_by_identifier(self.identifier_was || self.identifier) || site.layouts.new m.attributes = { :identifier => self.identifier, :parent_id => site.layouts.find_by_identifier(self.parent.try(:identifier)).try(:id) } m when Cms::Page m = site.pages.find_by_full_path(self.full_path_was || self.full_path) || site.pages.new m.attributes = { :slug => self.slug, :label => self.slug.blank?? self.label : m.label, :parent_id => site.pages.find_by_full_path(self.parent.try(:full_path)).try(:id), :layout => site.layouts.find_by_identifier(self.layout.try(:identifier)) } m when Cms::Snippet m = site.snippets.find_by_identifier(self.identifier_was || self.identifier) || site.snippets.new m.attributes = { :identifier => self.identifier } m end mirror.is_mirrored = true begin mirror.save! rescue ActiveRecord::RecordInvalid logger.detailed_error($!) end end end
ruby
{ "resource": "" }
q6930
ComfyPress::IsMirrored.InstanceMethods.destroy_mirror
train
def destroy_mirror return if self.is_mirrored || !self.site.is_mirrored? mirrors.each do |mirror| mirror.is_mirrored = true mirror.destroy end end
ruby
{ "resource": "" }
q6931
Shells.BashCommon.read_file
train
def read_file(path, use_method = nil) if use_method use_method = use_method.to_sym raise ArgumentError, "use_method (#{use_method.inspect}) is not a valid method." unless file_methods.include?(use_method) raise Shells::ShellError, "The #{use_method} binary is not available with this shell." unless which(use_method) send "read_file_#{use_method}", path elsif default_file_method return send "read_file_#{default_file_method}", path else raise Shells::ShellError, 'No supported binary to encode/decode files.' end end
ruby
{ "resource": "" }
q6932
Shells.BashCommon.sudo_exec
train
def sudo_exec(command, options = {}, &block) sudo_prompt = '[sp:' sudo_match = /\n\[sp:$/m sudo_strip = /\[sp:[^\n]*\n/m ret = exec("sudo -p \"#{sudo_prompt}\" bash -c \"#{command.gsub('"', '\\"')}\"", options) do |data,type| test_data = data.to_s desired_length = sudo_prompt.length + 1 # prefix a NL before the prompt. # pull from the current stdout to get the full test data, but only if we received some new data. if test_data.length > 0 && test_data.length < desired_length test_data = stdout[-desired_length..-1].to_s end if test_data =~ sudo_match self.options[:password] else if block block.call(data, type) else nil end end end # remove the sudo prompts. ret.gsub(sudo_strip, '') end
ruby
{ "resource": "" }
q6933
Shells.BashCommon.setup_prompt
train
def setup_prompt #:nodoc: command = "PS1=#{options[:prompt]}" sleep 1.0 # let shell initialize fully. exec_ignore_code command, silence_timeout: 10, command_timeout: 10, timeout_error: true, get_output: false end
ruby
{ "resource": "" }
q6934
KeytechKit.DataDictionaryHandler.getData
train
def getData(datadictionary_id) # /DataDictionaries/{ID}|{Name}/data parameter = { basic_auth: @auth } response = self.class.get("/datadictionaries/#{datadictionary_id}/data", parameter) if response.success? response['Data'] else raise response.response end end
ruby
{ "resource": "" }
q6935
Immutability.Object.at
train
def at(point) ipoint = point.to_i target = (ipoint < 0) ? (version + ipoint) : ipoint return unless (0..version).include? target detect { |state| target.equal? state.version } end
ruby
{ "resource": "" }
q6936
KeyTree.Forest.fetch
train
def fetch(key, *default) trees.lazy.each do |tree| catch do |ball| return tree.fetch(key) { throw ball } end end return yield(key) if block_given? return default.first unless default.empty? raise KeyError, %(key not found: "#{key}") end
ruby
{ "resource": "" }
q6937
KeyTree.Forest.flatten
train
def flatten(&merger) trees.reverse_each.reduce(Tree[]) do |result, tree| result.merge!(tree, &merger) end end
ruby
{ "resource": "" }
q6938
KeyTree.Forest.trees
train
def trees Enumerator.new do |yielder| remaining = [self] remaining.each do |woods| next yielder << woods if woods.is_a?(Tree) woods.each { |wood| remaining << wood } end end end
ruby
{ "resource": "" }
q6939
KeyTree.Forest.key_paths
train
def key_paths trees.reduce(Set.new) { |result, tree| result.merge(tree.key_paths) } end
ruby
{ "resource": "" }
q6940
Incline::Extensions.String.to_byte_string
train
def to_byte_string ret = self.gsub(/\s+/,'') raise 'Hex string must have even number of characters.' unless ret.size % 2 == 0 raise 'Hex string must only contain 0-9 and A-F characters.' if ret =~ /[^0-9a-fA-F]/ [ret].pack('H*').force_encoding('ascii-8bit') end
ruby
{ "resource": "" }
q6941
Signup.UsersHelper.remember
train
def remember(user) user.remember cookies.permanent.signed[:user_id] = user.id cookies.permanent[:remember_token] = user.remember_token end
ruby
{ "resource": "" }
q6942
Signup.UsersHelper.current_user
train
def current_user if (user_id = session[:user_id]) @current_user ||= User.find_by(id: user_id) elsif (user_id = cookies.signed[:user_id]) user = User.find_by(id: user_id) if user && user.authenticated?(cookies[:remember_token]) log_in user @current_user = user end end end
ruby
{ "resource": "" }
q6943
RJMetrics.Client.makeAuthAPICall
train
def makeAuthAPICall(url = API_BASE) request_url = "#{url}/client/#{@client_id}/authenticate?apikey=#{@api_key}" begin response = RestClient.get(request_url) return response rescue RestClient::Exception => error begin response = JSON.parse(error.response) unless response raise InvalidRequestException, "The Import API returned: #{error.http_code} #{error.message}" end raise InvalidRequestException, "The Import API returned: #{response['code']} #{response['message']}. Reasons: #{response['reasons']}" rescue JSON::ParserError, TypeError => json_parse_error raise InvalidResponseException, "RestClientError: #{error.class}\n Message: #{error.message}\n Response Code: #{error.http_code}\n Full Response: #{error.response}" end end end
ruby
{ "resource": "" }
q6944
Yummi.Table.column
train
def column(index) index = parse_index(index) columns = [] @data.each do |row| columns << row_to_array(row)[index].value end columns end
ruby
{ "resource": "" }
q6945
Yummi.Table.header=
train
def header=(header) header = [header] unless header.respond_to? :each @header = normalize(header) @aliases = header.map do |n| n.downcase.gsub(' ', '_').gsub("\n", '_').to_sym end if @aliases.empty? end
ruby
{ "resource": "" }
q6946
Yummi.Table.colorize
train
def colorize(indexes, params = {}, &block) [*indexes].each do |index| index = parse_index(index) if index obj = extract_component(params, &block) component[:colorizers][index] = obj else colorize_null params, &block end end end
ruby
{ "resource": "" }
q6947
Yummi.Table.colorize_null
train
def colorize_null(params = {}, &block) component[:null_colorizer] = (params[:using] or block) component[:null_colorizer] ||= proc do |value| params[:with] end end
ruby
{ "resource": "" }
q6948
Yummi.Table.format
train
def format(indexes, params = {}, &block) [*indexes].each do |index| index = parse_index(index) if index component[:formatters][index] = (params[:using] or block) component[:formatters][index] ||= proc do |ctx| params[:with] % ctx.value end else format_null params, &block end end end
ruby
{ "resource": "" }
q6949
Yummi.Table.format_null
train
def format_null(params = {}, &block) component[:null_formatter] = (params[:using] or block) component[:null_formatter] ||= proc do |value| params[:with] % value end end
ruby
{ "resource": "" }
q6950
Yummi.Table.to_s
train
def to_s header_output = build_header_output data_output = build_data_output string = '' string << Yummi.colorize(@title, @style[:title]) << $/ if @title string << Yummi.colorize(@description, @style[:description]) << $/ if @description table_data = header_output + data_output if @layout == :vertical # don't use array transpose because the data may differ in each line size table_data = rotate table_data end string << content(table_data) end
ruby
{ "resource": "" }
q6951
Yummi.Table.width
train
def width string = to_s max_width = 0 string.each_line do |line| max_width = [max_width, line.uncolored.chomp.size].max end max_width end
ruby
{ "resource": "" }
q6952
Yummi.Table.content
train
def content (data) string = '' data.each_index do |i| row = data[i] row.each_index do |j| column = row[j] column ||= {:value => nil, :color => nil} width = max_width data, j alignment = (@align[j] or @default_align) value = Aligner.align alignment, column[:value].to_s, width value = Yummi.colorize value, column[:color] unless @no_colors string << value string << (' ' * @colspan) end string.strip! << $/ end string end
ruby
{ "resource": "" }
q6953
Yummi.Table.build_header_output
train
def build_header_output output = [] @header.each do |line| _data = [] line.each do |h| _data << {:value => h, :color => @style[:header]} end output << _data end output end
ruby
{ "resource": "" }
q6954
Yummi.Table.build_row_contexts
train
def build_row_contexts rows = @data.size row_contexts = [:default] * rows offset = 0 @contexts.each do |ctx| if ctx == :default break end size = ctx[:rows] row_contexts[offset...(size + offset)] = [ctx[:id]] * size offset += size end @contexts.reverse_each do |ctx| if ctx == :default break end size = ctx[:rows] row_contexts[(rows - size)...rows] = [ctx[:id]] * size rows -= size end row_contexts end
ruby
{ "resource": "" }
q6955
Yummi.Table.build_data_output
train
def build_data_output output = [] row_contexts = build_row_contexts @data.each_index do |row_index| # sets the current context @current_context = row_contexts[row_index] row = row_to_array(@data[row_index], row_index) _row_data = [] row.each_index do |col_index| next if not @header.empty? and @header[0].size < col_index + 1 column = row[col_index] colorizer = component[:colorizers][col_index] color = if component[:null_colorizer] and column.value.nil? component[:null_colorizer].call(column) elsif colorizer colorizer.call(column) else @style[:value] end formatter = if column.value.nil? @null_formatter else component[:formatters][col_index] end value = if formatter formatter.call(column) else column.value end _row_data << {:value => value, :color => color} end row_colorizer = component[:row_colorizer] if row_colorizer row_color = row_colorizer.call row.first _row_data.collect! { |data| data[:color] = row_color; data } if row_color end _row_data = normalize( _row_data, :extract => proc do |data| data[:value].to_s end, :new => proc do |value, data| {:value => value, :color => data[:color]} end ) _row_data.each do |_row| output << _row end end output end
ruby
{ "resource": "" }
q6956
Tokyo.Assert.raise
train
def raise type = nil, message = nil, &block failure = Tokyo.__send__( @assert ? :assert_raised_as_expected : :refute_raised_as_expected, @object, type, message, block ) Tokyo.fail(failure, caller[0]) if failure end
ruby
{ "resource": "" }
q6957
Tokyo.Assert.throw
train
def throw expected_symbol = nil, &block failure = Tokyo.__send__( @assert ? :assert_thrown_as_expected : :refute_thrown_as_expected, @object, expected_symbol ? expected_symbol.to_sym : nil, block ) Tokyo.fail(failure, caller[0]) if failure end
ruby
{ "resource": "" }
q6958
Lipa.Node.eval_attrs
train
def eval_attrs result = {} @attrs.each_pair do |k,v| result[k.to_sym] = instance_eval(k.to_s) end result end
ruby
{ "resource": "" }
q6959
CruAuthLib.AccessTokenProtectedConcern.oauth_access_token_from_header
train
def oauth_access_token_from_header auth_header = request.env['HTTP_AUTHORIZATION'] || '' match = auth_header.match(/^Bearer\s(.*)/) return match[1] if match.present? false end
ruby
{ "resource": "" }
q6960
XmlDsl.BlockMethod.call
train
def call(a, b = nil, c = nil) if block self.send method, *[a, b, c].compact + args, &block else self.send method, *[a, b, c].compact + args end end
ruby
{ "resource": "" }
q6961
Hornetseye.GCCValue.load
train
def load( typecode ) offset = 0 typecode.typecodes.collect do |t| value = GCCValue.new @function, "*(#{GCCType.new( t ).identifier} *)( #{self} + #{offset} )" offset += t.storage_size value end end
ruby
{ "resource": "" }
q6962
Hornetseye.GCCValue.save
train
def save( value ) offset = 0 value.class.typecodes.zip( value.values ).each do |t,v| @function << "#{@function.indent}*(#{GCCType.new( t ).identifier} *)( #{self} + #{offset} ) = #{v};\n" offset += t.storage_size end end
ruby
{ "resource": "" }
q6963
Hornetseye.GCCValue.conditional
train
def conditional( a, b ) if a.is_a?( Proc ) and b.is_a?( Proc ) conditional a.call, b.call else GCCValue.new @function, "( #{self} ) ? ( #{a} ) : ( #{b} )" end end
ruby
{ "resource": "" }
q6964
Hornetseye.GCCValue.if_else
train
def if_else( action1, action2 ) @function << "#{@function.indent}if ( #{self} ) {\n" @function.indent_offset +1 action1.call @function.indent_offset -1 @function << "#{@function.indent}} else {\n" @function.indent_offset +1 action2.call @function.indent_offset -1 @function << "#{@function.indent}};\n" self end
ruby
{ "resource": "" }
q6965
Hornetseye.GCCValue.**
train
def **( other ) if GCCValue.generic? other GCCValue.new @function, "pow( #{self}, #{other} )" else x, y = other.coerce self x ** y end end
ruby
{ "resource": "" }
q6966
Hornetseye.GCCValue.conditional_with_rgb
train
def conditional_with_rgb( a, b ) if a.is_a?(RGB) or b.is_a?(RGB) Hornetseye::RGB conditional(a.r, b.r), conditional(a.g, b.g), conditional(a.b, b.b) else conditional_without_rgb a, b end end
ruby
{ "resource": "" }
q6967
Hornetseye.GCCValue.conditional_with_complex
train
def conditional_with_complex( a, b ) if a.is_a?( InternalComplex ) or b.is_a?( InternalComplex ) InternalComplex.new conditional( a.real, b.real ), conditional( a.imag, b.imag ) else conditional_without_complex a, b end end
ruby
{ "resource": "" }
q6968
Jaws.Server.build_env
train
def build_env(client, req) rack_env = DefaultRackEnv.dup req.fill_rack_env(rack_env) rack_env["SERVER_PORT"] ||= @port.to_s if (rack_env["rack.input"].respond_to? :set_encoding) rack_env["rack.input"].set_encoding "ASCII-8BIT" end rack_env["REMOTE_PORT"], rack_env["REMOTE_ADDR"] = Socket::unpack_sockaddr_in(client.getpeername) rack_env["REMOTE_PORT"] &&= rack_env["REMOTE_PORT"].to_s rack_env["SERVER_PROTOCOL"] = "HTTP/" << req.version.join('.') return rack_env end
ruby
{ "resource": "" }
q6969
Jaws.Server.chunked_read
train
def chunked_read(io, timeout) begin loop do list = IO.select([io], [], [], @read_timeout) if (list.nil? || list.empty?) # IO.select tells us we timed out by giving us nil, # disconnect the non-talkative client. return end data = io.recv(4096) if (data == "") # If recv returns an empty string, that means the other # end closed the connection (either in response to our # end closing the write pipe or because they just felt # like it) so we close the connection from our end too. return end yield data end ensure io.close if (!io.closed?) end end
ruby
{ "resource": "" }
q6970
Jaws.Server.process_client
train
def process_client(app) loop do client = nil begin make_interruptable do client = @listener.synchronize do begin @listener && @listener.accept() rescue => e return # this means we've been turned off, so exit the loop. end end if (!client) return # nil return means we're quitting, exit loop. end end req = Http::Parser.new() buf = "" chunked_read(client, @timeout) do |data| begin buf << data req.parse!(buf) if (req.done?) process_request(client, req, app) req = Http::Parser.new() if (@listener.closed?) return # ignore any more requests from this client if we're shutting down. end end rescue Http::ParserError => e err_str = "<h2>#{e.code} #{e.message}</h2>" client.write("HTTP/1.1 #{e.code} #{e.message}\r\n") client.write("Connection: close\r\n") client.write("Content-Length: #{err_str.length}\r\n") client.write("Content-Type: text/html\r\n") client.write("\r\n") client.write(err_str) client.close_write end end rescue Errno::EPIPE # do nothing, just let the connection close. rescue SystemExit, GracefulExit raise # pass it on. rescue Object => e $stderr.puts("Unhandled error #{e}:") e.backtrace.each do |line| $stderr.puts(line) end ensure client.close if (client && !client.closed?) end end end
ruby
{ "resource": "" }
q6971
Jaws.Server.run
train
def run(app) synchronize do @interruptable = [] int_orig = trap "INT" do stop() end term_orig = trap "TERM" do stop() end begin @listener = create_listener(@options) @interruptable.extend Mutex_m if (@max_clients > 1) @master = Thread.current @workers = (0...@max_clients).collect do Thread.new do begin process_client(app) rescue GracefulExit, SystemExit => e # let it exit. rescue => e $stderr.puts("Handler thread unexpectedly died with #{e}:", e.backtrace) end end end @workers.each do |worker| worker.join end else begin @master = Thread.current @workers = [Thread.current] process_client(app) rescue GracefulExit, SystemExit => e # let it exit rescue => e $stderr.puts("Handler thread unexpectedly died with #{e}:", e.backtrace) end end ensure trap "INT", int_orig trap "TERM", term_orig @listener.close if (@listener && !@listener.closed?) @interruptable = @listener = @master = @workers = nil end end end
ruby
{ "resource": "" }
q6972
UsBankHolidays.Month.to_s
train
def to_s @to_s ||= begin wks = @weeks.map { |w| w.map { |d| if d.nil? ' ' elsif d.day < 10 " #{d.day}" else "#{d.day}" end }.join(' ') }.join("\n") "Su Mo Tu We Th Fr Sa\n#{wks}\n" end end
ruby
{ "resource": "" }
q6973
ExactTargetSDK.Client.Create
train
def Create(*args) # TODO: implement and accept CreateOptions api_objects = args response = execute_request 'Create' do |xml| xml.CreateRequest do xml.Options # TODO: support CreateOptions api_objects.each do |api_object| xml.Objects "xsi:type" => api_object.type_name do api_object.render!(xml) end end end end CreateResponse.new(response) end
ruby
{ "resource": "" }
q6974
ExactTargetSDK.Client.Retrieve
train
def Retrieve(object_type_name, filter, *properties) object_type_name = object_type_name.type_name if object_type_name.respond_to?(:type_name) response = execute_request 'Retrieve' do |xml| xml.RetrieveRequestMsg do xml.RetrieveRequest do xml.Options xml.ObjectType object_type_name properties.each do |property| xml.Properties(property) end xml.Filter "xsi:type" => filter.type_name do filter.render!(xml) end end end end RetrieveResponse.new(response) end
ruby
{ "resource": "" }
q6975
ExactTargetSDK.Client.Update
train
def Update(*args) # TODO: implement and accept UpdateOptions api_objects = args response = execute_request 'Update' do |xml| xml.UpdateRequest do xml.Options # TODO: support UpdateOptions api_objects.each do |api_object| xml.Objects "xsi:type" => api_object.type_name do api_object.render!(xml) end end end end UpdateResponse.new(response) end
ruby
{ "resource": "" }
q6976
ExactTargetSDK.Client.Delete
train
def Delete(*args) # TODO: implement and accept DeleteOptions api_objects = args response = execute_request 'Delete' do |xml| xml.DeleteRequest do xml.Options # TODO: support DeleteOptions api_objects.each do |api_object| xml.Objects "xsi:type" => api_object.type_name do api_object.render!(xml) end end end end DeleteResponse.new(response) end
ruby
{ "resource": "" }
q6977
ExactTargetSDK.Client.Perform
train
def Perform(action, *args) # TODO: implement and accept PerformOptions definitions = args response = execute_request 'Perform' do |xml| xml.PerformRequestMsg do xml.Action action xml.Definitions do definitions.each do |definition| xml.Definition "xsi:type" => definition.type_name do definition.render!(xml) end end end xml.Options # TODO: support PerformOptions end end PerformResponse.new(response) end
ruby
{ "resource": "" }
q6978
ExactTargetSDK.Client.initialize_client!
train
def initialize_client! self.client = ::Savon.client( :endpoint => config[:endpoint], :namespace => config[:namespace], :open_timeout => config[:open_timeout], :read_timeout => config[:read_timeout], :raise_errors => false, :logger => config[:logger], :log => config[:logger] && config[:logger].level == Logger::DEBUG ) end
ruby
{ "resource": "" }
q6979
ExactTargetSDK.Client.execute_request
train
def execute_request(method) begin response = client.call(method) do |locals| xml = Builder::XmlMarkup.new xml.instruct!(:xml, :encoding => 'UTF-8') result = begin xml.s :Envelope, "xmlns" => config[:namespace], "xmlns:xsd" => "http://www.w3.org/2001/XMLSchema", "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", "xmlns:s" => "http://www.w3.org/2003/05/soap-envelope", "xmlns:a" => "http://schemas.xmlsoap.org/ws/2004/08/addressing", "xmlns:o" => "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" do xml.s :Header do xml.a :Action, method, "s:mustUnderstand" => "1" xml.a :MessageID, "uuid:#{Guid.new.to_s}" xml.a :ReplyTo do xml.a :Address, "http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous" end xml.a :To, config[:endpoint], "s:mustUnderstand" => "1" xml.o :Security, "s:mustUnderstand" => "1" do xml.o :UsernameToken, "o:Id" => "test" do xml.o :Username, config[:username] xml.o :Password, config[:password] end end end xml.s :Body do yield(xml) end end end locals.xml result end if response.http_error? raise HTTPError, response.http_error.to_s end if response.soap_fault? raise SOAPFault, response.soap_fault.to_s end response rescue ::Timeout::Error => e timeout = ::ExactTargetSDK::TimeoutError.new("#{e.message}; open_timeout: #{config[:open_timeout]}; read_timeout: #{config[:read_timeout]}") timeout.set_backtrace(e.backtrace) raise timeout rescue Exception => e raise ::ExactTargetSDK::UnknownError, e end end
ruby
{ "resource": "" }
q6980
I18n::Processes.GoogleTranslation.dump_value
train
def dump_value(value) case value when Array # dump recursively value.map { |v| dump_value v } when String replace_interpolations value end end
ruby
{ "resource": "" }
q6981
I18n::Processes.GoogleTranslation.parse_value
train
def parse_value(untranslated, each_translated) case untranslated when Array # implode array untranslated.map { |from| parse_value(from, each_translated) } when String restore_interpolations untranslated, each_translated.next else untranslated end end
ruby
{ "resource": "" }
q6982
BarkestCore.ConnectionAdapterExtensions.object_exists?
train
def object_exists?(object_name) safe_name = "'#{object_name.gsub('\'','\'\'')}'" klass = self.class.name sql = if klass == 'ActiveRecord::ConnectionAdapters::SQLServerAdapter' # use sysobjects table. "SELECT COUNT(*) AS \"one\" FROM \"sysobjects\" WHERE \"name\"=#{safe_name}" elsif klass == 'ActiveRecord::ConnectionAdapters::SQLite3Adapter' # use sqlite_master table. "SELECT COUNT(*) AS \"one\" FROM \"sqlite_master\" WHERE (\"type\"='table' OR \"type\"='view') AND (\"name\"=#{safe_name})" else # query the information_schema TABLES and ROUTINES views. "SELECT SUM(Z.\"one\") AS \"one\" FROM (SELECT COUNT(*) AS \"one\" FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME=#{safe_name} UNION SELECT COUNT(*) AS \"one\" FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_NAME=#{safe_name}) AS Z" end result = exec_query(sql).first result && result['one'] >= 1 end
ruby
{ "resource": "" }
q6983
BarkestCore.ConnectionAdapterExtensions.exec_sp
train
def exec_sp(stmt) klass = self.class.name if klass == 'ActiveRecord::ConnectionAdapters::SQLServerAdapter' rex = /^exec(?:ute)?\s+[\["]?(?<PROC>[a-z][a-z0-9_]*)[\]"]?(?<ARGS>\s.*)?$/i match = rex.match(stmt) if match exec_query("DECLARE @RET INTEGER; EXECUTE @RET=[#{match['PROC']}]#{match['ARGS']}; SELECT @RET AS [RET]").first['RET'] else execute stmt end else execute stmt end end
ruby
{ "resource": "" }
q6984
LiveFront.ApplicationHelper.current_controller?
train
def current_controller?(*args) args.any? { |v| v.to_s.downcase == controller.controller_name } end
ruby
{ "resource": "" }
q6985
YoClient.Client.yo
train
def yo(username, options = {}) options.merge!(username: username.upcase) response = connection_wrapper { @faraday.post '/yo/', token_hash.merge(options) } response.success? end
ruby
{ "resource": "" }
q6986
YoClient.Client.connection_wrapper
train
def connection_wrapper(&block) begin response = block.call raise ClientError.new(response.body['error']) if response.body.has_key?('error') rescue Faraday::ParsingError => e # Has gotten a response, but it is not formatted with JSON raise ClientError.new(e.message) rescue Faraday::ClientError => e # Failed to build a connection raise ConnectionError.new(e.message) end response end
ruby
{ "resource": "" }
q6987
Pith.Project.published_inputs
train
def published_inputs inputs.select { |i| i.published? }.sort_by { |i| i.published_at } end
ruby
{ "resource": "" }
q6988
FishTransactions.Callbacks.after_transaction
train
def after_transaction(opts = {}, &block) # default options default_options = { only: nil, if_no_transaction: :run} opts = default_options.merge(opts) # normalize opts to string keys normalized = opts.dup opts.each{ |k,v| normalized[k.to_s] = v } opts = normalized if ActiveRecord::Base.connection.open_transactions > 0 callbacks = ActiveRecord::Base.callbacks case opts['only'] when :commit callbacks.store(:commit,&block) when :rollback callbacks.store(:rollback,&block) else # both cases callbacks.store(:commit,&block) callbacks.store(:rollback,&block) end else if opts['if_no_transaction'] == :run block.call end end end
ruby
{ "resource": "" }
q6989
Garcon.Coercer.register
train
def register(origin, target, &block) raise(ArgumentError, 'block is required') unless block_given? @mutex.synchronize do @coercions[origin][target] = Coercion.new(origin, target, &block) end end
ruby
{ "resource": "" }
q6990
RDSBackup.Job.write_to_s3
train
def write_to_s3 status_path = "#{@s3_path}/status.json" s3.put_object(@bucket, status_path, "#{to_json}\n") unless @status_url expire_date = Time.now + (3600 * 24) # one day from now @status_url = s3.get_object_http_url(@bucket, status_path, expire_date) s3.put_object(@bucket, status_path, "#{to_json}\n") end end
ruby
{ "resource": "" }
q6991
RDSBackup.Job.perform_backup
train
def perform_backup begin prepare_backup update_status "Backing up #{rds_id} from account #{account_name}" create_disconnected_rds download_data_from_tmp_rds # populates @sql_file delete_disconnected_rds upload_output_to_s3 update_status "Backup of #{rds_id} complete" send_mail rescue Exception => e update_status "ERROR: #{e.message.split("\n").first}", 500 raise e end end
ruby
{ "resource": "" }
q6992
RDSBackup.Job.create_disconnected_rds
train
def create_disconnected_rds(new_rds_name = nil) @new_rds_id = new_rds_name if new_rds_name prepare_backup unless @original_server # in case run as a convenience method snapshot_original_rds create_tmp_rds_from_snapshot configure_tmp_rds wait_for_new_security_group wait_for_new_parameter_group # (reboots as needed) destroy_snapshot end
ruby
{ "resource": "" }
q6993
RDSBackup.Job.prepare_backup
train
def prepare_backup unless @original_server = RDSBackup.get_rds(rds_id) names = RDSBackup.rds_accounts.map {|name, account| name } raise "Unable to find RDS #{rds_id} in accounts #{names.join ", "}" end @account_name = @original_server.tracker_account[:name] @rds = ::Fog::AWS::RDS.new( RDSBackup.rds_accounts[@account_name][:credentials]) @snapshot = @rds.snapshots.get @snapshot_id @new_instance = @rds.servers.get @new_rds_id end
ruby
{ "resource": "" }
q6994
RDSBackup.Job.snapshot_original_rds
train
def snapshot_original_rds unless @new_instance || @snapshot update_status "Waiting for RDS instance #{@original_server.id}" @original_server.wait_for { ready? } update_status "Creating snapshot #{@snapshot_id} from RDS #{rds_id}" @snapshot = @rds.snapshots.create(id: @snapshot_id, instance_id: rds_id) end end
ruby
{ "resource": "" }
q6995
RDSBackup.Job.create_tmp_rds_from_snapshot
train
def create_tmp_rds_from_snapshot unless @new_instance update_status "Waiting for snapshot #{@snapshot_id}" @snapshot.wait_for { ready? } update_status "Booting new RDS #{@new_rds_id} from snapshot #{@snapshot.id}" @rds.restore_db_instance_from_db_snapshot(@snapshot.id, @new_rds_id, 'DBInstanceClass' => @original_server.flavor_id) @new_instance = @rds.servers.get @new_rds_id end end
ruby
{ "resource": "" }
q6996
RDSBackup.Job.configure_tmp_rds
train
def configure_tmp_rds update_status "Waiting for instance #{@new_instance.id}..." @new_instance.wait_for { ready? } update_status "Modifying RDS attributes for new RDS #{@new_instance.id}" @rds.modify_db_instance(@new_instance.id, true, { 'DBParameterGroupName' => @original_server.db_parameter_groups. first['DBParameterGroupName'], 'DBSecurityGroups' => [ @config['rds_security_group'] ], 'MasterUserPassword' => @new_password, }) end
ruby
{ "resource": "" }
q6997
RDSBackup.Job.wait_for_new_security_group
train
def wait_for_new_security_group old_group_name = @config['rds_security_group'] update_status "Applying security group #{old_group_name}"+ " to #{@new_instance.id}" @new_instance.wait_for { new_group = (db_security_groups.select do |group| group['DBSecurityGroupName'] == old_group_name end).first (new_group ? new_group['Status'] : 'Unknown') == 'active' } end
ruby
{ "resource": "" }
q6998
RDSBackup.Job.wait_for_new_parameter_group
train
def wait_for_new_parameter_group old_name = @original_server.db_parameter_groups.first['DBParameterGroupName'] update_status "Applying parameter group #{old_name} to #{@new_instance.id}" job = self # save local var for closure in wait_for, below @new_instance.wait_for { new_group = (db_parameter_groups.select do |group| group['DBParameterGroupName'] == old_name end).first status = (new_group ? new_group['ParameterApplyStatus'] : 'Unknown') if (status == "pending-reboot") job.update_status "Rebooting RDS #{id} to apply ParameterGroup #{old_name}" reboot and wait_for { ready? } end status == 'in-sync' && ready? } end
ruby
{ "resource": "" }
q6999
RDSBackup.Job.update_status
train
def update_status(message, new_status = nil) @log = @options[:logger] || RDSBackup.default_logger(STDOUT) @message = message @status = new_status if new_status @status == 200 ? (@log.info message) : (@log.error message) write_to_s3 end
ruby
{ "resource": "" }