id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
6,900
qwertos/URIx-Util
lib/urix/urix.rb
URIx.URIx.claim_interface
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
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
[ "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" ]
Creates a new URIx interface. Claim the USB interface for this program. Must be called to begin using the interface.
[ "Creates", "a", "new", "URIx", "interface", ".", "Claim", "the", "USB", "interface", "for", "this", "program", ".", "Must", "be", "called", "to", "begin", "using", "the", "interface", "." ]
a7b565543aad947ccdb3ffb869e98401b8efb798
https://github.com/qwertos/URIx-Util/blob/a7b565543aad947ccdb3ffb869e98401b8efb798/lib/urix/urix.rb#L26-L38
6,901
qwertos/URIx-Util
lib/urix/urix.rb
URIx.URIx.set_output
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
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
[ "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" ]
Sets the state of a GPIO pin. @param pin [Integer] ID of GPIO pin. @param state [Boolean] State to set pin to. True == :high
[ "Sets", "the", "state", "of", "a", "GPIO", "pin", "." ]
a7b565543aad947ccdb3ffb869e98401b8efb798
https://github.com/qwertos/URIx-Util/blob/a7b565543aad947ccdb3ffb869e98401b8efb798/lib/urix/urix.rb#L54-L66
6,902
qwertos/URIx-Util
lib/urix/urix.rb
URIx.URIx.set_pin_mode
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
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
[ "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" ]
Sets the mode of a GPIO pin to input or output. @param pin [Integer] ID of GPIO pin. @param mode [Symbol] :input or :output
[ "Sets", "the", "mode", "of", "a", "GPIO", "pin", "to", "input", "or", "output", "." ]
a7b565543aad947ccdb3ffb869e98401b8efb798
https://github.com/qwertos/URIx-Util/blob/a7b565543aad947ccdb3ffb869e98401b8efb798/lib/urix/urix.rb#L73-L80
6,903
Montage-Inc/ruby-montage
lib/montage/client.rb
Montage.Client.auth
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
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
[ "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" ]
Attempts to authenticate with the Montage API * *Returns* : - A hash containing a valid token or an error string, oh no!
[ "Attempts", "to", "authenticate", "with", "the", "Montage", "API" ]
2e6f7e591f2f87158994c17ad9619fa29b716bad
https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/client.rb#L88-L96
6,904
Montage-Inc/ruby-montage
lib/montage/client.rb
Montage.Client.build_response
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
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
[ "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" ]
Instantiates a response object based on the yielded block * *Args* : - +resource_name+ -> The name of the Montage resource * *Returns* : * A Montage::Response Object containing: - A http status code - The response body - The resource name
[ "Instantiates", "a", "response", "object", "based", "on", "the", "yielded", "block" ]
2e6f7e591f2f87158994c17ad9619fa29b716bad
https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/client.rb#L214-L223
6,905
Montage-Inc/ruby-montage
lib/montage/client.rb
Montage.Client.connection
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
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
[ "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", ":", "/", "\\b", "/", "end", "end" ]
Creates an Faraday connection instance for requests * *Returns* : - A Faraday connection object with an instance specific configuration
[ "Creates", "an", "Faraday", "connection", "instance", "for", "requests" ]
2e6f7e591f2f87158994c17ad9619fa29b716bad
https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/client.rb#L245-L252
6,906
jimmyz/ruby-fs-stack
lib/ruby-fs-stack/familytree/communicator.rb
FamilytreeV2.Communicator.write_note
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
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
[ "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" ]
Writes a note attached to the value ID of the specific person or relationship. ====Params * <tt>options</tt> - Options for the note including the following: * <tt>:personId</tt> - the person ID if attaching to a person assertion. * <tt>:spouseIds</tt> - an Array of spouse IDs if creating a note attached to a spouse relationship assertion. * <tt>:parentIds</tt> - an Array of parent IDs if creating a note attached to a parent relationship assertion. If creating a note for a child-parent or parent-child relationship, you will need only one parent ID in the array along with a :childId option. * <tt>:childId</tt> - a child ID. * <tt>:text</tt> - the text of the note (required). * <tt>:assertionId</tt> - the valueId of the assertion you are attaching this note to.
[ "Writes", "a", "note", "attached", "to", "the", "value", "ID", "of", "the", "specific", "person", "or", "relationship", "." ]
11281818635984971026e750d32a5c4599557dd1
https://github.com/jimmyz/ruby-fs-stack/blob/11281818635984971026e750d32a5c4599557dd1/lib/ruby-fs-stack/familytree/communicator.rb#L233-L242
6,907
jimmyz/ruby-fs-stack
lib/ruby-fs-stack/familytree/communicator.rb
FamilytreeV2.Communicator.combine
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
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
[ "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" ]
Combines person into a new person ====Params * <tt>person_array</tt> - an array of person IDs.
[ "Combines", "person", "into", "a", "new", "person" ]
11281818635984971026e750d32a5c4599557dd1
https://github.com/jimmyz/ruby-fs-stack/blob/11281818635984971026e750d32a5c4599557dd1/lib/ruby-fs-stack/familytree/communicator.rb#L248-L258
6,908
mrsimonfletcher/roroacms
app/controllers/roroacms/admin/comments_controller.rb
Roroacms.Admin::CommentsController.edit
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
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
[ "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" ]
get and disply certain comment
[ "get", "and", "disply", "certain", "comment" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/comments_controller.rb#L15-L21
6,909
mrsimonfletcher/roroacms
app/controllers/roroacms/admin/comments_controller.rb
Roroacms.Admin::CommentsController.update
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
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
[ "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" ]
update the comment. You are able to update everything about the comment as an admin
[ "update", "the", "comment", ".", "You", "are", "able", "to", "update", "everything", "about", "the", "comment", "as", "an", "admin" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/comments_controller.rb#L26-L43
6,910
mrsimonfletcher/roroacms
app/controllers/roroacms/admin/comments_controller.rb
Roroacms.Admin::CommentsController.destroy
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
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
[ "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" ]
delete the comment
[ "delete", "the", "comment" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/comments_controller.rb#L48-L57
6,911
mrsimonfletcher/roroacms
app/controllers/roroacms/admin/comments_controller.rb
Roroacms.Admin::CommentsController.bulk_update
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
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
[ "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" ]
bulk_update function takes all of the checked options and updates them with the given option selected. The options for the bulk update in comments area are - Unapprove - Approve - Mark as Spam - Destroy
[ "bulk_update", "function", "takes", "all", "of", "the", "checked", "options", "and", "updates", "them", "with", "the", "given", "option", "selected", ".", "The", "options", "for", "the", "bulk", "update", "in", "comments", "area", "are", "-", "Unapprove", "-", "Approve", "-", "Mark", "as", "Spam", "-", "Destroy" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/comments_controller.rb#L66-L74
6,912
mrsimonfletcher/roroacms
app/controllers/roroacms/admin/comments_controller.rb
Roroacms.Admin::CommentsController.mark_as_spam
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
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
[ "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" ]
mark_as_spam function is a button on the ui and so need its own function. The function simply marks the comment as spam against the record in the database. the record is then not visable unless you explicity tell the system that you want to see spam records.
[ "mark_as_spam", "function", "is", "a", "button", "on", "the", "ui", "and", "so", "need", "its", "own", "function", ".", "The", "function", "simply", "marks", "the", "comment", "as", "spam", "against", "the", "record", "in", "the", "database", ".", "the", "record", "is", "then", "not", "visable", "unless", "you", "explicity", "tell", "the", "system", "that", "you", "want", "to", "see", "spam", "records", "." ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/comments_controller.rb#L80-L91
6,913
Dev-Crea/swagger-docs-generator
lib/swagger_docs_generator/metadata/sort.rb
SwaggerDocsGenerator.Sort.sort_by_tag
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
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
[ "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" ]
Sort routes by tags
[ "Sort", "routes", "by", "tags" ]
5d3de176aa1119cb38100b451bee028d66c0809d
https://github.com/Dev-Crea/swagger-docs-generator/blob/5d3de176aa1119cb38100b451bee028d66c0809d/lib/swagger_docs_generator/metadata/sort.rb#L20-L25
6,914
whistler/active-tracker
lib/active_tracker/tracker.rb
ActiveTracker.Tracker.method_missing
def method_missing(m, *args, &block) if @tracker_names.include? m @tracker_blocks[m] = block else super(name, *args, &block) end end
ruby
def method_missing(m, *args, &block) if @tracker_names.include? m @tracker_blocks[m] = block else super(name, *args, &block) end end
[ "def", "method_missing", "(", "m", ",", "*", "args", ",", "&", "block", ")", "if", "@tracker_names", ".", "include?", "m", "@tracker_blocks", "[", "m", "]", "=", "block", "else", "super", "(", "name", ",", "args", ",", "block", ")", "end", "end" ]
store tracker code blocks
[ "store", "tracker", "code", "blocks" ]
5a618042f3f7f9425e31dc083b7b9b970cbcf0b9
https://github.com/whistler/active-tracker/blob/5a618042f3f7f9425e31dc083b7b9b970cbcf0b9/lib/active_tracker/tracker.rb#L34-L40
6,915
jgoizueta/numerals
lib/numerals/rounding.rb
Numerals.Rounding.truncate
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
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
[ "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" ]
Truncate a numeral and return also a round_up value with information about the digits beyond the truncation point that can be used to round the truncated numeral. If the numeral has already been truncated, the round_up result of that prior truncation should be passed as the second argument.
[ "Truncate", "a", "numeral", "and", "return", "also", "a", "round_up", "value", "with", "information", "about", "the", "digits", "beyond", "the", "truncation", "point", "that", "can", "be", "used", "to", "round", "the", "truncated", "numeral", ".", "If", "the", "numeral", "has", "already", "been", "truncated", "the", "round_up", "result", "of", "that", "prior", "truncation", "should", "be", "passed", "as", "the", "second", "argument", "." ]
a195e75f689af926537f791441bf8d11590c99c0
https://github.com/jgoizueta/numerals/blob/a195e75f689af926537f791441bf8d11590c99c0/lib/numerals/rounding.rb#L239-L290
6,916
jgoizueta/numerals
lib/numerals/rounding.rb
Numerals.Rounding.adjust
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
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
[ "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" ]
Adjust a truncated numeral using the round-up information
[ "Adjust", "a", "truncated", "numeral", "using", "the", "round", "-", "up", "information" ]
a195e75f689af926537f791441bf8d11590c99c0
https://github.com/jgoizueta/numerals/blob/a195e75f689af926537f791441bf8d11590c99c0/lib/numerals/rounding.rb#L293-L308
6,917
kmcd/active_record-tableless_model
lib/active_record-tableless_model.rb
ActiveRecord::Base::TablelessModel.ClassMethods.column
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
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
[ "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" ]
Creates an attribute corresponding to a database column. N.B No table is created in the database == Arguments <tt>name</tt> :: column name, such as supplier_id in supplier_id int(11). <tt>default</tt> :: type-casted default value, such as new in sales_stage varchar(20) default 'new'. <tt>sql_type</tt> :: used to extract the column length, if necessary. For example 60 in company_name varchar(60). null determines if this column allows NULL values. == Usage class Task < ActiveRecord::Base no_table column :description, :text column :description, :string, 'foo', false end
[ "Creates", "an", "attribute", "corresponding", "to", "a", "database", "column", ".", "N", ".", "B", "No", "table", "is", "created", "in", "the", "database" ]
42b84a0b2001bd3f000685bab7920c6fbf60e21b
https://github.com/kmcd/active_record-tableless_model/blob/42b84a0b2001bd3f000685bab7920c6fbf60e21b/lib/active_record-tableless_model.rb#L31-L33
6,918
rich-dtk/dtk-common
lib/gitolite/manager.rb
Gitolite.Manager.create_user
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
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
[ "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" ]
this should be depracated
[ "this", "should", "be", "depracated" ]
18d312092e9060f01d271a603ad4b0c9bef318b1
https://github.com/rich-dtk/dtk-common/blob/18d312092e9060f01d271a603ad4b0c9bef318b1/lib/gitolite/manager.rb#L41-L52
6,919
triglav-dataflow/triglav-client-ruby
lib/triglav_client/api/messages_api.rb
TriglavClient.MessagesApi.send_messages
def send_messages(messages, opts = {}) data, _status_code, _headers = send_messages_with_http_info(messages, opts) return data end
ruby
def send_messages(messages, opts = {}) data, _status_code, _headers = send_messages_with_http_info(messages, opts) return data end
[ "def", "send_messages", "(", "messages", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "send_messages_with_http_info", "(", "messages", ",", "opts", ")", "return", "data", "end" ]
Enqueues new messages @param messages Messages to enqueue @param [Hash] opts the optional parameters @return [BulkinsertResponse]
[ "Enqueues", "new", "messages" ]
b2f3781d65ee032ba96eb703fbd789c713a5e0bd
https://github.com/triglav-dataflow/triglav-client-ruby/blob/b2f3781d65ee032ba96eb703fbd789c713a5e0bd/lib/triglav_client/api/messages_api.rb#L156-L159
6,920
buzzware/buzztools
lib/buzztools/file.rb
Buzztools.File.real_path
def real_path(aPath) (path = Pathname.new(::File.expand_path(aPath))) && path.realpath.to_s end
ruby
def real_path(aPath) (path = Pathname.new(::File.expand_path(aPath))) && path.realpath.to_s end
[ "def", "real_path", "(", "aPath", ")", "(", "path", "=", "Pathname", ".", "new", "(", "::", "File", ".", "expand_path", "(", "aPath", ")", ")", ")", "&&", "path", ".", "realpath", ".", "to_s", "end" ]
make path real according to file system
[ "make", "path", "real", "according", "to", "file", "system" ]
0823721974d521330ceffe099368ed8cac6209c3
https://github.com/buzzware/buzztools/blob/0823721974d521330ceffe099368ed8cac6209c3/lib/buzztools/file.rb#L64-L66
6,921
buzzware/buzztools
lib/buzztools/file.rb
Buzztools.File.expand_magic_path
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
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
[ "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" ]
allows special symbols in path currently only ... supported, which looks upward in the filesystem for the following relative path from the basepath
[ "allows", "special", "symbols", "in", "path", "currently", "only", "...", "supported", "which", "looks", "upward", "in", "the", "filesystem", "for", "the", "following", "relative", "path", "from", "the", "basepath" ]
0823721974d521330ceffe099368ed8cac6209c3
https://github.com/buzzware/buzztools/blob/0823721974d521330ceffe099368ed8cac6209c3/lib/buzztools/file.rb#L86-L94
6,922
equallevel/grapple
lib/grapple/html_table_builder.rb
Grapple.HtmlTableBuilder.container
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
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
[ "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" ]
Wrap the table in a div
[ "Wrap", "the", "table", "in", "a", "div" ]
65dc1c141adaa3342f0985f4b09d34f6de49e31f
https://github.com/equallevel/grapple/blob/65dc1c141adaa3342f0985f4b09d34f6de49e31f/lib/grapple/html_table_builder.rb#L18-L26
6,923
blambeau/yargi
lib/yargi/markable.rb
Yargi.Markable.add_marks
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
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
[ "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" ]
Add all marks provided by a Hash instance _marks_.
[ "Add", "all", "marks", "provided", "by", "a", "Hash", "instance", "_marks_", "." ]
100141e96d245a0a8211cd4f7590909be149bc3c
https://github.com/blambeau/yargi/blob/100141e96d245a0a8211cd4f7590909be149bc3c/lib/yargi/markable.rb#L46-L52
6,924
blambeau/yargi
lib/yargi/markable.rb
Yargi.Markable.to_h
def to_h(nonil=true) return {} unless @marks marks = @marks.dup if nonil marks.delete_if {|k,v| v.nil?} end marks end
ruby
def to_h(nonil=true) return {} unless @marks marks = @marks.dup if nonil marks.delete_if {|k,v| v.nil?} end marks end
[ "def", "to_h", "(", "nonil", "=", "true", ")", "return", "{", "}", "unless", "@marks", "marks", "=", "@marks", ".", "dup", "if", "nonil", "marks", ".", "delete_if", "{", "|", "k", ",", "v", "|", "v", ".", "nil?", "}", "end", "marks", "end" ]
Converts this Markable to a Hash. When _nonil_ is true, nil mark values do not lead to hash entries.
[ "Converts", "this", "Markable", "to", "a", "Hash", ".", "When", "_nonil_", "is", "true", "nil", "mark", "values", "do", "not", "lead", "to", "hash", "entries", "." ]
100141e96d245a0a8211cd4f7590909be149bc3c
https://github.com/blambeau/yargi/blob/100141e96d245a0a8211cd4f7590909be149bc3c/lib/yargi/markable.rb#L57-L64
6,925
DaQwest/dq-readability
lib/dq-readability.rb
DQReadability.Document.author
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
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
[ "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" ]
Look through the @html document looking for the author Precedence Information here on the wiki: (TODO attach wiki URL if it is accepted) Returns nil if no author is detected
[ "Look", "through", "the" ]
6fe7830e1aba4867b4a263ee664d0987e8df039a
https://github.com/DaQwest/dq-readability/blob/6fe7830e1aba4867b4a263ee664d0987e8df039a/lib/dq-readability.rb#L262-L306
6,926
barkerest/barkest_core
app/helpers/barkest_core/users_helper.rb
BarkestCore.UsersHelper.gravatar_for
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
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
[ "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" ]
Returns the Gravatar for the given user. Based on the tutorial from [www.railstutorial.org](www.railstutorial.org). The +user+ is the user you want to get the gravatar for. Valid options: * +size+ The size (in pixels) for the returned gravatar. The gravatar will be a square image using this value as both the width and height. The default is 80 pixels. * +default+ The default image to return when no image is set. This can be nil, :mm, :identicon, :monsterid, :wavatar, or :retro. The default is :identicon.
[ "Returns", "the", "Gravatar", "for", "the", "given", "user", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/helpers/barkest_core/users_helper.rb#L21-L29
6,927
ujjwalt/neon
lib/helpers/argument_helpers.rb
Neon.ArgumentHelpers.extract_session
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
def extract_session(args) if args.last.is_a?(Session::Rest) || args.last.is_a?(Session::Embedded) args.pop else Session.current end end
[ "def", "extract_session", "(", "args", ")", "if", "args", ".", "last", ".", "is_a?", "(", "Session", "::", "Rest", ")", "||", "args", ".", "last", ".", "is_a?", "(", "Session", "::", "Embedded", ")", "args", ".", "pop", "else", "Session", ".", "current", "end", "end" ]
Extracts a session from the array of arguments if one exists at the end. @param args [Array] an array of arguments of any type. @return [Session] a session if the last argument is a valid session and pops it out of args. Otherwise it returns the current session.
[ "Extracts", "a", "session", "from", "the", "array", "of", "arguments", "if", "one", "exists", "at", "the", "end", "." ]
609769b16f051a100809131df105df29f98037fc
https://github.com/ujjwalt/neon/blob/609769b16f051a100809131df105df29f98037fc/lib/helpers/argument_helpers.rb#L11-L17
6,928
omegainteractive/comfypress
lib/comfypress/extensions/is_mirrored.rb
ComfyPress::IsMirrored.InstanceMethods.mirrors
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
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
[ "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" ]
Mirrors of the object found on other sites
[ "Mirrors", "of", "the", "object", "found", "on", "other", "sites" ]
3b64699bf16774b636cb13ecd89281f6e2acb264
https://github.com/omegainteractive/comfypress/blob/3b64699bf16774b636cb13ecd89281f6e2acb264/lib/comfypress/extensions/is_mirrored.rb#L21-L30
6,929
omegainteractive/comfypress
lib/comfypress/extensions/is_mirrored.rb
ComfyPress::IsMirrored.InstanceMethods.sync_mirror
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
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
[ "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" ]
Creating or updating a mirror object. Relationships are mirrored but content is unique. When updating need to grab mirrors based on self.slug_was, new objects will use self.slug.
[ "Creating", "or", "updating", "a", "mirror", "object", ".", "Relationships", "are", "mirrored", "but", "content", "is", "unique", ".", "When", "updating", "need", "to", "grab", "mirrors", "based", "on", "self", ".", "slug_was", "new", "objects", "will", "use", "self", ".", "slug", "." ]
3b64699bf16774b636cb13ecd89281f6e2acb264
https://github.com/omegainteractive/comfypress/blob/3b64699bf16774b636cb13ecd89281f6e2acb264/lib/comfypress/extensions/is_mirrored.rb#L35-L71
6,930
omegainteractive/comfypress
lib/comfypress/extensions/is_mirrored.rb
ComfyPress::IsMirrored.InstanceMethods.destroy_mirror
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
def destroy_mirror return if self.is_mirrored || !self.site.is_mirrored? mirrors.each do |mirror| mirror.is_mirrored = true mirror.destroy end end
[ "def", "destroy_mirror", "return", "if", "self", ".", "is_mirrored", "||", "!", "self", ".", "site", ".", "is_mirrored?", "mirrors", ".", "each", "do", "|", "mirror", "|", "mirror", ".", "is_mirrored", "=", "true", "mirror", ".", "destroy", "end", "end" ]
Mirrors should be destroyed
[ "Mirrors", "should", "be", "destroyed" ]
3b64699bf16774b636cb13ecd89281f6e2acb264
https://github.com/omegainteractive/comfypress/blob/3b64699bf16774b636cb13ecd89281f6e2acb264/lib/comfypress/extensions/is_mirrored.rb#L74-L80
6,931
barkerest/shells
lib/shells/bash_common.rb
Shells.BashCommon.read_file
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
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
[ "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" ]
Reads from a file on the device.
[ "Reads", "from", "a", "file", "on", "the", "device", "." ]
674a0254f48cea01b0ae8979933f13892e398506
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/bash_common.rb#L10-L21
6,932
barkerest/shells
lib/shells/bash_common.rb
Shells.BashCommon.sudo_exec
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
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
[ "def", "sudo_exec", "(", "command", ",", "options", "=", "{", "}", ",", "&", "block", ")", "sudo_prompt", "=", "'[sp:'", "sudo_match", "=", "/", "\\n", "\\[", "/m", "sudo_strip", "=", "/", "\\[", "\\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" ]
Executes an elevated command using the 'sudo' command.
[ "Executes", "an", "elevated", "command", "using", "the", "sudo", "command", "." ]
674a0254f48cea01b0ae8979933f13892e398506
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/bash_common.rb#L40-L65
6,933
barkerest/shells
lib/shells/bash_common.rb
Shells.BashCommon.setup_prompt
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
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
[ "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" ]
Uses the PS1= command to set the prompt for the shell.
[ "Uses", "the", "PS1", "=", "command", "to", "set", "the", "prompt", "for", "the", "shell", "." ]
674a0254f48cea01b0ae8979933f13892e398506
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/bash_common.rb#L91-L95
6,934
tclaus/keytechkit.gem
lib/keytechKit/elements/data_dictionary/data_dictionary_handler.rb
KeytechKit.DataDictionaryHandler.getData
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
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
[ "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" ]
Returns a hashed value with data
[ "Returns", "a", "hashed", "value", "with", "data" ]
caa7a6bee32b75ec18a4004179ae10cb69d148c2
https://github.com/tclaus/keytechkit.gem/blob/caa7a6bee32b75ec18a4004179ae10cb69d148c2/lib/keytechKit/elements/data_dictionary/data_dictionary_handler.rb#L28-L38
6,935
nepalez/immutability
lib/immutability/object.rb
Immutability.Object.at
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
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
[ "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" ]
Returns the state of the object at some point in the past @param [#to_i] point Either a positive number of target version, or a negative number of version (snapshots) before the current one +0+ stands for the first version. @return [Object, nil]
[ "Returns", "the", "state", "of", "the", "object", "at", "some", "point", "in", "the", "past" ]
6f44a7e3dad9cbc51f40e5ec9b3810d1cc730a10
https://github.com/nepalez/immutability/blob/6f44a7e3dad9cbc51f40e5ec9b3810d1cc730a10/lib/immutability/object.rb#L55-L61
6,936
notCalle/ruby-keytree
lib/key_tree/forest.rb
KeyTree.Forest.fetch
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
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
[ "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" ]
Fetch a value from a forest :call-seq: fetch(key) => value fetch(key, default) => value fetch(key) { |key| } => value The first form raises a +KeyError+ unless +key+ has a value.
[ "Fetch", "a", "value", "from", "a", "forest" ]
1a88c902c8b5d14f21fd350338776fc094eae8e3
https://github.com/notCalle/ruby-keytree/blob/1a88c902c8b5d14f21fd350338776fc094eae8e3/lib/key_tree/forest.rb#L52-L62
6,937
notCalle/ruby-keytree
lib/key_tree/forest.rb
KeyTree.Forest.flatten
def flatten(&merger) trees.reverse_each.reduce(Tree[]) do |result, tree| result.merge!(tree, &merger) end end
ruby
def flatten(&merger) trees.reverse_each.reduce(Tree[]) do |result, tree| result.merge!(tree, &merger) end end
[ "def", "flatten", "(", "&", "merger", ")", "trees", ".", "reverse_each", ".", "reduce", "(", "Tree", "[", "]", ")", "do", "|", "result", ",", "tree", "|", "result", ".", "merge!", "(", "tree", ",", "merger", ")", "end", "end" ]
Flattening a forest produces a tree with the equivalent view of key paths
[ "Flattening", "a", "forest", "produces", "a", "tree", "with", "the", "equivalent", "view", "of", "key", "paths" ]
1a88c902c8b5d14f21fd350338776fc094eae8e3
https://github.com/notCalle/ruby-keytree/blob/1a88c902c8b5d14f21fd350338776fc094eae8e3/lib/key_tree/forest.rb#L90-L94
6,938
notCalle/ruby-keytree
lib/key_tree/forest.rb
KeyTree.Forest.trees
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
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
[ "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" ]
Return a breadth-first Enumerator for all the trees in the forest, and any nested forests
[ "Return", "a", "breadth", "-", "first", "Enumerator", "for", "all", "the", "trees", "in", "the", "forest", "and", "any", "nested", "forests" ]
1a88c902c8b5d14f21fd350338776fc094eae8e3
https://github.com/notCalle/ruby-keytree/blob/1a88c902c8b5d14f21fd350338776fc094eae8e3/lib/key_tree/forest.rb#L98-L107
6,939
notCalle/ruby-keytree
lib/key_tree/forest.rb
KeyTree.Forest.key_paths
def key_paths trees.reduce(Set.new) { |result, tree| result.merge(tree.key_paths) } end
ruby
def key_paths trees.reduce(Set.new) { |result, tree| result.merge(tree.key_paths) } end
[ "def", "key_paths", "trees", ".", "reduce", "(", "Set", ".", "new", ")", "{", "|", "result", ",", "tree", "|", "result", ".", "merge", "(", "tree", ".", "key_paths", ")", "}", "end" ]
Return all visible key paths in the forest
[ "Return", "all", "visible", "key", "paths", "in", "the", "forest" ]
1a88c902c8b5d14f21fd350338776fc094eae8e3
https://github.com/notCalle/ruby-keytree/blob/1a88c902c8b5d14f21fd350338776fc094eae8e3/lib/key_tree/forest.rb#L110-L112
6,940
barkerest/incline
lib/incline/extensions/string.rb
Incline::Extensions.String.to_byte_string
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
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
[ "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", "=~", "/", "/", "[", "ret", "]", ".", "pack", "(", "'H*'", ")", ".", "force_encoding", "(", "'ascii-8bit'", ")", "end" ]
Converts a hex string into a byte string. Whitespace in the string is ignored. The string must only contain characters valid for hex (ie - 0-9, A-F, a-f). The string must contain an even number of characters since each character only represents half a byte.
[ "Converts", "a", "hex", "string", "into", "a", "byte", "string", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/string.rb#L13-L18
6,941
BDMADE/signup
app/helpers/signup/users_helper.rb
Signup.UsersHelper.remember
def remember(user) user.remember cookies.permanent.signed[:user_id] = user.id cookies.permanent[:remember_token] = user.remember_token end
ruby
def remember(user) user.remember cookies.permanent.signed[:user_id] = user.id cookies.permanent[:remember_token] = user.remember_token end
[ "def", "remember", "(", "user", ")", "user", ".", "remember", "cookies", ".", "permanent", ".", "signed", "[", ":user_id", "]", "=", "user", ".", "id", "cookies", ".", "permanent", "[", ":remember_token", "]", "=", "user", ".", "remember_token", "end" ]
Remembers a user in a persistent session.
[ "Remembers", "a", "user", "in", "a", "persistent", "session", "." ]
59a4b9a2d0ab54eac853193d9f4ac4a2dbf3f8e0
https://github.com/BDMADE/signup/blob/59a4b9a2d0ab54eac853193d9f4ac4a2dbf3f8e0/app/helpers/signup/users_helper.rb#L9-L13
6,942
BDMADE/signup
app/helpers/signup/users_helper.rb
Signup.UsersHelper.current_user
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
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
[ "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" ]
Returns the user corresponding to the remember token cookie.
[ "Returns", "the", "user", "corresponding", "to", "the", "remember", "token", "cookie", "." ]
59a4b9a2d0ab54eac853193d9f4ac4a2dbf3f8e0
https://github.com/BDMADE/signup/blob/59a4b9a2d0ab54eac853193d9f4ac4a2dbf3f8e0/app/helpers/signup/users_helper.rb#L16-L26
6,943
RJMetrics/RJMetrics-ruby
lib/rjmetrics-client/client.rb
RJMetrics.Client.makeAuthAPICall
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
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
[ "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" ]
Authenticates with the RJMetrics Data Import API
[ "Authenticates", "with", "the", "RJMetrics", "Data", "Import", "API" ]
f09d014af873656e2deb049a4975428afabdf088
https://github.com/RJMetrics/RJMetrics-ruby/blob/f09d014af873656e2deb049a4975428afabdf088/lib/rjmetrics-client/client.rb#L94-L114
6,944
devnull-tools/yummi
lib/yummi/table.rb
Yummi.Table.column
def column(index) index = parse_index(index) columns = [] @data.each do |row| columns << row_to_array(row)[index].value end columns end
ruby
def column(index) index = parse_index(index) columns = [] @data.each do |row| columns << row_to_array(row)[index].value end columns end
[ "def", "column", "(", "index", ")", "index", "=", "parse_index", "(", "index", ")", "columns", "=", "[", "]", "@data", ".", "each", "do", "|", "row", "|", "columns", "<<", "row_to_array", "(", "row", ")", "[", "index", "]", ".", "value", "end", "columns", "end" ]
Retrieves the column at the given index. Aliases can be used
[ "Retrieves", "the", "column", "at", "the", "given", "index", ".", "Aliases", "can", "be", "used" ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L174-L181
6,945
devnull-tools/yummi
lib/yummi/table.rb
Yummi.Table.header=
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
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
[ "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" ]
Sets the table header. If no aliases are defined, they will be defined as the texts in lowercase with line breaks and spaces replaced by underscores. Defining headers also limits the printed column to only columns that has a header (even if it is empty). === Args +header+:: Array containing the texts for displaying the header. Line breaks are supported === Examples table.header = ['Name', 'Email', 'Work Phone', "Home\nPhone"] This will create the following aliases: :key, :email, :work_phone and :home_phone
[ "Sets", "the", "table", "header", ".", "If", "no", "aliases", "are", "defined", "they", "will", "be", "defined", "as", "the", "texts", "in", "lowercase", "with", "line", "breaks", "and", "spaces", "replaced", "by", "underscores", "." ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L201-L207
6,946
devnull-tools/yummi
lib/yummi/table.rb
Yummi.Table.colorize
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
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
[ "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" ]
Sets a component to colorize a column. The component must respond to +call+ with the column value (or row if used with #using_row) as the arguments and return a color or +nil+ if default color should be used. A block can also be used. === Args +indexes+:: The column indexes or its aliases +params+:: A hash with params in case a block is not given: - :using defines the component to use - :with defines the color to use (to use the same color for all columns) === Example table.colorize :description, :with => :magenta table.colorize([:value, :total]) { |value| :red if value < 0 }
[ "Sets", "a", "component", "to", "colorize", "a", "column", "." ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L283-L293
6,947
devnull-tools/yummi
lib/yummi/table.rb
Yummi.Table.colorize_null
def colorize_null(params = {}, &block) component[:null_colorizer] = (params[:using] or block) component[:null_colorizer] ||= proc do |value| params[:with] end end
ruby
def colorize_null(params = {}, &block) component[:null_colorizer] = (params[:using] or block) component[:null_colorizer] ||= proc do |value| params[:with] end end
[ "def", "colorize_null", "(", "params", "=", "{", "}", ",", "&", "block", ")", "component", "[", ":null_colorizer", "]", "=", "(", "params", "[", ":using", "]", "or", "block", ")", "component", "[", ":null_colorizer", "]", "||=", "proc", "do", "|", "value", "|", "params", "[", ":with", "]", "end", "end" ]
Defines a colorizer to null values. === Args +params+:: A hash with params in case a block is not given: - :using defines the component to use - :with defines the format to use
[ "Defines", "a", "colorizer", "to", "null", "values", "." ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L305-L310
6,948
devnull-tools/yummi
lib/yummi/table.rb
Yummi.Table.format
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
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
[ "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" ]
Sets a component to format a column. The component must respond to +call+ with the column value as the arguments and return a color or +nil+ if default color should be used. A block can also be used. === Args +indexes+:: The column indexes or its aliases +params+:: A hash with params in case a block is not given: - :using defines the component to use - :with defines the format to use (to use the same format for all columns) === Example table.format :value, :with => '%.2f' table.format [:value, :total], :with => '%.2f'
[ "Sets", "a", "component", "to", "format", "a", "column", "." ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L333-L345
6,949
devnull-tools/yummi
lib/yummi/table.rb
Yummi.Table.format_null
def format_null(params = {}, &block) component[:null_formatter] = (params[:using] or block) component[:null_formatter] ||= proc do |value| params[:with] % value end end
ruby
def format_null(params = {}, &block) component[:null_formatter] = (params[:using] or block) component[:null_formatter] ||= proc do |value| params[:with] % value end end
[ "def", "format_null", "(", "params", "=", "{", "}", ",", "&", "block", ")", "component", "[", ":null_formatter", "]", "=", "(", "params", "[", ":using", "]", "or", "block", ")", "component", "[", ":null_formatter", "]", "||=", "proc", "do", "|", "value", "|", "params", "[", ":with", "]", "%", "value", "end", "end" ]
Defines a formatter to null values. === Args +params+:: A hash with params in case a block is not given: - :using defines the component to use - :with defines the format to use
[ "Defines", "a", "formatter", "to", "null", "values", "." ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L357-L362
6,950
devnull-tools/yummi
lib/yummi/table.rb
Yummi.Table.to_s
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
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
[ "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" ]
Return a colorized and formatted table.
[ "Return", "a", "colorized", "and", "formatted", "table", "." ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L374-L387
6,951
devnull-tools/yummi
lib/yummi/table.rb
Yummi.Table.width
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
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
[ "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" ]
Calculates the table width using the rendered lines
[ "Calculates", "the", "table", "width", "using", "the", "rendered", "lines" ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L392-L399
6,952
devnull-tools/yummi
lib/yummi/table.rb
Yummi.Table.content
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
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
[ "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" ]
Gets the content string for the given color map and content
[ "Gets", "the", "content", "string", "for", "the", "given", "color", "map", "and", "content" ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L436-L453
6,953
devnull-tools/yummi
lib/yummi/table.rb
Yummi.Table.build_header_output
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
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
[ "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" ]
Builds the header output for this table. Returns the color map and the header.
[ "Builds", "the", "header", "output", "for", "this", "table", "." ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L460-L471
6,954
devnull-tools/yummi
lib/yummi/table.rb
Yummi.Table.build_row_contexts
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
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
[ "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" ]
maps the context for each row
[ "maps", "the", "context", "for", "each", "row" ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L474-L495
6,955
devnull-tools/yummi
lib/yummi/table.rb
Yummi.Table.build_data_output
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
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
[ "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" ]
Builds the data output for this table. Returns the color map and the formatted data.
[ "Builds", "the", "data", "output", "for", "this", "table", "." ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/table.rb#L502-L553
6,956
sleewoo/tokyo
lib/tokyo/assert.rb
Tokyo.Assert.raise
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
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
[ "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" ]
ensure the given block raises as expected @note if block given it will have precedence over arguments @example assertion pass if block raises whatever assert {some code}.raise @example assertion pass if block raises NameError assert {some code}.raise NameError @example assertion pass if block raises NameError and error message matches /blah/ assert {some code}.raise NameError, /blah/ @example assertion pass if block raises whatever error that matches /blah/ assert {some code}.raise nil, /blah/ @example assertion pass if validation block returns a positive value assert {some code}.raise {|e| e.is_a?(NameError) && e.message =~ /blah/} @example assertion pass if nothing raised refute {some code}.raise # same fail_if {some code}.raise @example assertion fails only if block raises a NameError. it may raise whatever but NameError. if nothing raised assertion will fail. fail_if {some code}.raise NameError @example assertion pass if raised error does not match /blah/ if nothing raised assertion will fail. fail_if {some code}.raise nil, /blah/ @example assertion will pass if raised error is not a NameError and error message does not match /blah/ if nothing raised assertion will fail as well. fail_if {some code}.raise NameError, /blah/
[ "ensure", "the", "given", "block", "raises", "as", "expected" ]
bcd0a031b535dadce13039acde81aef3d16454e0
https://github.com/sleewoo/tokyo/blob/bcd0a031b535dadce13039acde81aef3d16454e0/lib/tokyo/assert.rb#L76-L82
6,957
sleewoo/tokyo
lib/tokyo/assert.rb
Tokyo.Assert.throw
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
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
[ "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" ]
ensure given block thrown as expected @note if block given it will have precedence over arguments @example assertion pass if any symbol thrown assert {some code}.throw @example assertion pass only if :x symbol thrown assert {some code}.throw(:x) @example assertion pass only if given block validates thrown symbol assert {some code}.throw {|sym| sym == :x}
[ "ensure", "given", "block", "thrown", "as", "expected" ]
bcd0a031b535dadce13039acde81aef3d16454e0
https://github.com/sleewoo/tokyo/blob/bcd0a031b535dadce13039acde81aef3d16454e0/lib/tokyo/assert.rb#L98-L104
6,958
flipback/lipa
lib/lipa/node.rb
Lipa.Node.eval_attrs
def eval_attrs result = {} @attrs.each_pair do |k,v| result[k.to_sym] = instance_eval(k.to_s) end result end
ruby
def eval_attrs result = {} @attrs.each_pair do |k,v| result[k.to_sym] = instance_eval(k.to_s) end result end
[ "def", "eval_attrs", "result", "=", "{", "}", "@attrs", ".", "each_pair", "do", "|", "k", ",", "v", "|", "result", "[", "k", ".", "to_sym", "]", "=", "instance_eval", "(", "k", ".", "to_s", ")", "end", "result", "end" ]
Copy attributes with eval @retun [Hash] hash @example node :some_node d: param_1 1 param_2 run{ param_1 + 2} end node.attrs #=> {:param_1 => 1, :param_2 => Proc} node.eval_attrs #=> {:param_1 => 1, :param_2 => 3}
[ "Copy", "attributes", "with", "eval" ]
d735846c09473525df812fa829141a83aa2b385d
https://github.com/flipback/lipa/blob/d735846c09473525df812fa829141a83aa2b385d/lib/lipa/node.rb#L96-L102
6,959
CruGlobal/cru-auth-lib
lib/cru_auth_lib/access_token_protected_concern.rb
CruAuthLib.AccessTokenProtectedConcern.oauth_access_token_from_header
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
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
[ "def", "oauth_access_token_from_header", "auth_header", "=", "request", ".", "env", "[", "'HTTP_AUTHORIZATION'", "]", "||", "''", "match", "=", "auth_header", ".", "match", "(", "/", "\\s", "/", ")", "return", "match", "[", "1", "]", "if", "match", ".", "present?", "false", "end" ]
grabs access_token from header if one is present
[ "grabs", "access_token", "from", "header", "if", "one", "is", "present" ]
e25d4100236ee6fa062d9a8350ec4c207827c584
https://github.com/CruGlobal/cru-auth-lib/blob/e25d4100236ee6fa062d9a8350ec4c207827c584/lib/cru_auth_lib/access_token_protected_concern.rb#L20-L25
6,960
vladson/xml_dsl
lib/xml_dsl/block_method.rb
XmlDsl.BlockMethod.call
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
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
[ "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" ]
order of params to be called can differ, so naming is ambiguous
[ "order", "of", "params", "to", "be", "called", "can", "differ", "so", "naming", "is", "ambiguous" ]
dc96eb41df35617bf8740f225e7218df4c674bb0
https://github.com/vladson/xml_dsl/blob/dc96eb41df35617bf8740f225e7218df4c674bb0/lib/xml_dsl/block_method.rb#L11-L17
6,961
wedesoft/multiarray
lib/multiarray/gccvalue.rb
Hornetseye.GCCValue.load
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
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
[ "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" ]
Add code to read all components of a typed value from memory @return [Array<GCCValue>] An array of objects referencing values in C. @private
[ "Add", "code", "to", "read", "all", "components", "of", "a", "typed", "value", "from", "memory" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/gccvalue.rb#L185-L193
6,962
wedesoft/multiarray
lib/multiarray/gccvalue.rb
Hornetseye.GCCValue.save
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
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
[ "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" ]
Add code to write all components of a typed value to memory @param [Node] value Value to write to memory. @return [Object] The return value should be ignored. @private
[ "Add", "code", "to", "write", "all", "components", "of", "a", "typed", "value", "to", "memory" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/gccvalue.rb#L202-L208
6,963
wedesoft/multiarray
lib/multiarray/gccvalue.rb
Hornetseye.GCCValue.conditional
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
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
[ "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" ]
Create code for conditional selection of value @param [GCCValue,Object] a First value. @param [GCCValue,Object] b Second value. @return [GCCValue] C value referring to result. @private
[ "Create", "code", "for", "conditional", "selection", "of", "value" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/gccvalue.rb#L299-L305
6,964
wedesoft/multiarray
lib/multiarray/gccvalue.rb
Hornetseye.GCCValue.if_else
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
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
[ "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" ]
Generate code for conditional statement @param [Proc] action1 Block to run when condition is fullfilled. @param [Proc] action2 Block to run otherwise. @return [Object] Returns +self+. @private
[ "Generate", "code", "for", "conditional", "statement" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/gccvalue.rb#L331-L342
6,965
wedesoft/multiarray
lib/multiarray/gccvalue.rb
Hornetseye.GCCValue.**
def **( other ) if GCCValue.generic? other GCCValue.new @function, "pow( #{self}, #{other} )" else x, y = other.coerce self x ** y end end
ruby
def **( other ) if GCCValue.generic? other GCCValue.new @function, "pow( #{self}, #{other} )" else x, y = other.coerce self x ** y end end
[ "def", "**", "(", "other", ")", "if", "GCCValue", ".", "generic?", "other", "GCCValue", ".", "new", "@function", ",", "\"pow( #{self}, #{other} )\"", "else", "x", ",", "y", "=", "other", ".", "coerce", "self", "x", "**", "y", "end", "end" ]
Generate code for computing exponentiation @param [Object,GCCValue] other Second operand for binary operation. @return [GCCValue] C value refering to the result. @private
[ "Generate", "code", "for", "computing", "exponentiation" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/gccvalue.rb#L437-L444
6,966
wedesoft/multiarray
lib/multiarray/gccvalue.rb
Hornetseye.GCCValue.conditional_with_rgb
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
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
[ "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" ]
Create code for conditional selection of RGB value @param [GCCValue,Object] a First value. @param [GCCValue,Object] b Second value. @return [GCCValue] C value referring to result. @private
[ "Create", "code", "for", "conditional", "selection", "of", "RGB", "value" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/gccvalue.rb#L496-L502
6,967
wedesoft/multiarray
lib/multiarray/gccvalue.rb
Hornetseye.GCCValue.conditional_with_complex
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
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
[ "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" ]
Create code for conditional selection of complex value @param [GCCValue,Object] a First value. @param [GCCValue,Object] b Second value. @return [GCCValue] C value referring to result. @private
[ "Create", "code", "for", "conditional", "selection", "of", "complex", "value" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/gccvalue.rb#L514-L521
6,968
stormbrew/jaws
lib/jaws/server.rb
Jaws.Server.build_env
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
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
[ "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" ]
Builds an env object from the information provided. Derived handlers can override this to provide additional information.
[ "Builds", "an", "env", "object", "from", "the", "information", "provided", ".", "Derived", "handlers", "can", "override", "this", "to", "provide", "additional", "information", "." ]
b5035b475f28cbccac360581514774da4c49f605
https://github.com/stormbrew/jaws/blob/b5035b475f28cbccac360581514774da4c49f605/lib/jaws/server.rb#L97-L111
6,969
stormbrew/jaws
lib/jaws/server.rb
Jaws.Server.chunked_read
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
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
[ "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" ]
Reads from a connection, yielding chunks of data as it goes, until the connection closes. Once the connection closes, it returns.
[ "Reads", "from", "a", "connection", "yielding", "chunks", "of", "data", "as", "it", "goes", "until", "the", "connection", "closes", ".", "Once", "the", "connection", "closes", "it", "returns", "." ]
b5035b475f28cbccac360581514774da4c49f605
https://github.com/stormbrew/jaws/blob/b5035b475f28cbccac360581514774da4c49f605/lib/jaws/server.rb#L116-L138
6,970
stormbrew/jaws
lib/jaws/server.rb
Jaws.Server.process_client
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
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
[ "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" ]
Accepts a connection from a client and handles requests on it until the connection closes.
[ "Accepts", "a", "connection", "from", "a", "client", "and", "handles", "requests", "on", "it", "until", "the", "connection", "closes", "." ]
b5035b475f28cbccac360581514774da4c49f605
https://github.com/stormbrew/jaws/blob/b5035b475f28cbccac360581514774da4c49f605/lib/jaws/server.rb#L252-L306
6,971
stormbrew/jaws
lib/jaws/server.rb
Jaws.Server.run
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 && [email protected]?) @interruptable = @listener = @master = @workers = nil end end end
ruby
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 && [email protected]?) @interruptable = @listener = @master = @workers = nil end end end
[ "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" ]
Runs the application through the configured handler. Can only be run once at a time. If you try to run it more than once, the second run will block until the first finishes.
[ "Runs", "the", "application", "through", "the", "configured", "handler", ".", "Can", "only", "be", "run", "once", "at", "a", "time", ".", "If", "you", "try", "to", "run", "it", "more", "than", "once", "the", "second", "run", "will", "block", "until", "the", "first", "finishes", "." ]
b5035b475f28cbccac360581514774da4c49f605
https://github.com/stormbrew/jaws/blob/b5035b475f28cbccac360581514774da4c49f605/lib/jaws/server.rb#L328-L374
6,972
albertosaurus/us_bank_holidays
lib/us_bank_holidays/month.rb
UsBankHolidays.Month.to_s
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
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
[ "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" ]
Initializes an instance from a year and a month. Raises an error if the month is not in the allowed range, i.e. it must be between 1 and 12 inclusive.
[ "Initializes", "an", "instance", "from", "a", "year", "and", "a", "month", ".", "Raises", "an", "error", "if", "the", "month", "is", "not", "in", "the", "allowed", "range", "i", ".", "e", ".", "it", "must", "be", "between", "1", "and", "12", "inclusive", "." ]
506269159bfaf0737955b2cca2d43c627ac9704e
https://github.com/albertosaurus/us_bank_holidays/blob/506269159bfaf0737955b2cca2d43c627ac9704e/lib/us_bank_holidays/month.rb#L21-L36
6,973
daws/exact_target_sdk
lib/exact_target_sdk/client.rb
ExactTargetSDK.Client.Create
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
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
[ "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" ]
Constructs a client. Any of the options documented in ExactTargetSDK#config may be overridden using the options parameter. Since ExactTarget's API is stateless, constructing a client object will not make any remote calls. Invokes the Create method. The provided arguments should each be sub-classes of APIObject, and each provided object will be created in order. Possible exceptions are: HTTPError if an HTTP error (such as a timeout) occurs SOAPFault if a SOAP fault occurs Timeout if there is a timeout waiting for the response InvalidAPIObject if any of the provided objects don't pass validation Returns a CreateResponse object.
[ "Constructs", "a", "client", "." ]
64fde8f61356a5f0c75586a10b07d175adfeac12
https://github.com/daws/exact_target_sdk/blob/64fde8f61356a5f0c75586a10b07d175adfeac12/lib/exact_target_sdk/client.rb#L42-L60
6,974
daws/exact_target_sdk
lib/exact_target_sdk/client.rb
ExactTargetSDK.Client.Retrieve
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
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
[ "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" ]
Invokes the Retrieve method. Note that this implementation abstracts away the useless RetrieveRequest sub-wrapper, and introduces a RequestResponse wrapper to contain the output parameters. Does not currently support requests that have too many results for one batch. Possible exceptions are: HTTPError if an HTTP error (such as a timeout) occurs SOAPFault if a SOAP fault occurs Timeout if there is a timeout waiting for the response InvalidAPIObject if any of the provided objects don't pass validation Returns a RetrieveResponse object.
[ "Invokes", "the", "Retrieve", "method", "." ]
64fde8f61356a5f0c75586a10b07d175adfeac12
https://github.com/daws/exact_target_sdk/blob/64fde8f61356a5f0c75586a10b07d175adfeac12/lib/exact_target_sdk/client.rb#L78-L99
6,975
daws/exact_target_sdk
lib/exact_target_sdk/client.rb
ExactTargetSDK.Client.Update
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
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
[ "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" ]
Invokes the Update method. The provided arguments should each be sub-classes of APIObject, and each provided object will be updated in order. Possible exceptions are: HTTPError if an HTTP error (such as a timeout) occurs SOAPFault if a SOAP fault occurs Timeout if there is a timeout waiting for the response InvalidAPIObject if any of the provided objects don't pass validation Returns an UpdateResponse object.
[ "Invokes", "the", "Update", "method", "." ]
64fde8f61356a5f0c75586a10b07d175adfeac12
https://github.com/daws/exact_target_sdk/blob/64fde8f61356a5f0c75586a10b07d175adfeac12/lib/exact_target_sdk/client.rb#L113-L131
6,976
daws/exact_target_sdk
lib/exact_target_sdk/client.rb
ExactTargetSDK.Client.Delete
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
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
[ "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" ]
Invokes the Delete method. The provided arguments should each be sub-classes of APIObject, and each provided object will be updated in order. Possible exceptions are: HTTPError if an HTTP error (such as a timeout) occurs SOAPFault if a SOAP fault occurs Timeout if there is a timeout waiting for the response InvalidAPIObject if any of the provided objects don't pass validation Returns a DeleteResponse object.
[ "Invokes", "the", "Delete", "method", "." ]
64fde8f61356a5f0c75586a10b07d175adfeac12
https://github.com/daws/exact_target_sdk/blob/64fde8f61356a5f0c75586a10b07d175adfeac12/lib/exact_target_sdk/client.rb#L145-L163
6,977
daws/exact_target_sdk
lib/exact_target_sdk/client.rb
ExactTargetSDK.Client.Perform
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
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
[ "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" ]
Invokes the Perform method. The provided arguments should each be definitions that are sub-classes of APIObject. Possible exceptions are: HTTPError if an HTTP error (such as a timeout) occurs SOAPFault if a SOAP fault occurs Timeout if there is a timeout waiting for the response InvalidAPIObject if any of the provided objects don't pass validation Returns a PerformResponse object.
[ "Invokes", "the", "Perform", "method", "." ]
64fde8f61356a5f0c75586a10b07d175adfeac12
https://github.com/daws/exact_target_sdk/blob/64fde8f61356a5f0c75586a10b07d175adfeac12/lib/exact_target_sdk/client.rb#L177-L199
6,978
daws/exact_target_sdk
lib/exact_target_sdk/client.rb
ExactTargetSDK.Client.initialize_client!
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
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
[ "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" ]
Constructs and saves the savon client using provided config.
[ "Constructs", "and", "saves", "the", "savon", "client", "using", "provided", "config", "." ]
64fde8f61356a5f0c75586a10b07d175adfeac12
https://github.com/daws/exact_target_sdk/blob/64fde8f61356a5f0c75586a10b07d175adfeac12/lib/exact_target_sdk/client.rb#L210-L220
6,979
daws/exact_target_sdk
lib/exact_target_sdk/client.rb
ExactTargetSDK.Client.execute_request
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
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
[ "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" ]
Builds the SOAP request for the given method, delegating body rendering to the provided block. Handles errors and re-raises with appropriate sub-class of ExactTargetSDK::Error. Returns the raw savon response.
[ "Builds", "the", "SOAP", "request", "for", "the", "given", "method", "delegating", "body", "rendering", "to", "the", "provided", "block", "." ]
64fde8f61356a5f0c75586a10b07d175adfeac12
https://github.com/daws/exact_target_sdk/blob/64fde8f61356a5f0c75586a10b07d175adfeac12/lib/exact_target_sdk/client.rb#L229-L284
6,980
Lupeipei/i18n-processes
lib/i18n/processes/google_translation.rb
I18n::Processes.GoogleTranslation.dump_value
def dump_value(value) case value when Array # dump recursively value.map { |v| dump_value v } when String replace_interpolations value end end
ruby
def dump_value(value) case value when Array # dump recursively value.map { |v| dump_value v } when String replace_interpolations value end end
[ "def", "dump_value", "(", "value", ")", "case", "value", "when", "Array", "# dump recursively", "value", ".", "map", "{", "|", "v", "|", "dump_value", "v", "}", "when", "String", "replace_interpolations", "value", "end", "end" ]
Prepare value for translation. @return [String, Array<String, nil>, nil] value for Google Translate or nil for non-string values
[ "Prepare", "value", "for", "translation", "." ]
83c91517f80b82371ab19e197665e6e131024df3
https://github.com/Lupeipei/i18n-processes/blob/83c91517f80b82371ab19e197665e6e131024df3/lib/i18n/processes/google_translation.rb#L68-L76
6,981
Lupeipei/i18n-processes
lib/i18n/processes/google_translation.rb
I18n::Processes.GoogleTranslation.parse_value
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
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
[ "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" ]
Parse translated value from the each_translated enumerator @param [Object] untranslated @param [Enumerator] each_translated @return [Object] final translated value
[ "Parse", "translated", "value", "from", "the", "each_translated", "enumerator" ]
83c91517f80b82371ab19e197665e6e131024df3
https://github.com/Lupeipei/i18n-processes/blob/83c91517f80b82371ab19e197665e6e131024df3/lib/i18n/processes/google_translation.rb#L82-L92
6,982
barkerest/barkest_core
lib/barkest_core/extensions/active_record_extensions.rb
BarkestCore.ConnectionAdapterExtensions.object_exists?
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
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
[ "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" ]
Searches the database to determine if an object with the specified name exists.
[ "Searches", "the", "database", "to", "determine", "if", "an", "object", "with", "the", "specified", "name", "exists", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/lib/barkest_core/extensions/active_record_extensions.rb#L11-L30
6,983
barkerest/barkest_core
lib/barkest_core/extensions/active_record_extensions.rb
BarkestCore.ConnectionAdapterExtensions.exec_sp
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
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
[ "def", "exec_sp", "(", "stmt", ")", "klass", "=", "self", ".", "class", ".", "name", "if", "klass", "==", "'ActiveRecord::ConnectionAdapters::SQLServerAdapter'", "rex", "=", "/", "\\s", "\\[", "\\]", "\\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" ]
Executes a stored procedure. For MS SQL Server, this will return the return value from the procedure. For other providers, this is the same as +execute+.
[ "Executes", "a", "stored", "procedure", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/lib/barkest_core/extensions/active_record_extensions.rb#L37-L50
6,984
LiveTyping/live-front-rails
lib/live-front/application_helper.rb
LiveFront.ApplicationHelper.current_controller?
def current_controller?(*args) args.any? { |v| v.to_s.downcase == controller.controller_name } end
ruby
def current_controller?(*args) args.any? { |v| v.to_s.downcase == controller.controller_name } end
[ "def", "current_controller?", "(", "*", "args", ")", "args", ".", "any?", "{", "|", "v", "|", "v", ".", "to_s", ".", "downcase", "==", "controller", ".", "controller_name", "}", "end" ]
Check if a particular controller is the current one args - One or more controller names to check Examples # On TreeController current_controller?(:tree) # => true current_controller?(:commits) # => false current_controller?(:commits, :tree) # => true
[ "Check", "if", "a", "particular", "controller", "is", "the", "current", "one" ]
605946ec748bab2a2a751fd7eebcbf9a0e99832c
https://github.com/LiveTyping/live-front-rails/blob/605946ec748bab2a2a751fd7eebcbf9a0e99832c/lib/live-front/application_helper.rb#L13-L15
6,985
youcune/yo_client
lib/yo_client.rb
YoClient.Client.yo
def yo(username, options = {}) options.merge!(username: username.upcase) response = connection_wrapper { @faraday.post '/yo/', token_hash.merge(options) } response.success? end
ruby
def yo(username, options = {}) options.merge!(username: username.upcase) response = connection_wrapper { @faraday.post '/yo/', token_hash.merge(options) } response.success? end
[ "def", "yo", "(", "username", ",", "options", "=", "{", "}", ")", "options", ".", "merge!", "(", "username", ":", "username", ".", "upcase", ")", "response", "=", "connection_wrapper", "{", "@faraday", ".", "post", "'/yo/'", ",", "token_hash", ".", "merge", "(", "options", ")", "}", "response", ".", "success?", "end" ]
Yo to specific user @param [String] username usename to send yo @param [Hash] options allowed only link for now @return [Boolean] if request has succeed
[ "Yo", "to", "specific", "user" ]
a966c9d2d454315cb77deda1b8487255e48d5673
https://github.com/youcune/yo_client/blob/a966c9d2d454315cb77deda1b8487255e48d5673/lib/yo_client.rb#L32-L38
6,986
youcune/yo_client
lib/yo_client.rb
YoClient.Client.connection_wrapper
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
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
[ "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" ]
Connect with error handling @param [Proc] block
[ "Connect", "with", "error", "handling" ]
a966c9d2d454315cb77deda1b8487255e48d5673
https://github.com/youcune/yo_client/blob/a966c9d2d454315cb77deda1b8487255e48d5673/lib/yo_client.rb#L52-L65
6,987
mdub/pith
lib/pith/plugins/publication/project.rb
Pith.Project.published_inputs
def published_inputs inputs.select { |i| i.published? }.sort_by { |i| i.published_at } end
ruby
def published_inputs inputs.select { |i| i.published? }.sort_by { |i| i.published_at } end
[ "def", "published_inputs", "inputs", ".", "select", "{", "|", "i", "|", "i", ".", "published?", "}", ".", "sort_by", "{", "|", "i", "|", "i", ".", "published_at", "}", "end" ]
Return all the published inputs, in order of publication.
[ "Return", "all", "the", "published", "inputs", "in", "order", "of", "publication", "." ]
a78047cf65653172817b0527672bf6df960d510f
https://github.com/mdub/pith/blob/a78047cf65653172817b0527672bf6df960d510f/lib/pith/plugins/publication/project.rb#L10-L12
6,988
Beetrack/fish_transactions
lib/fish_transactions/callbacks.rb
FishTransactions.Callbacks.after_transaction
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
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
[ "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" ]
Allows to execute any block of code after transaction completes. If no transaction is actually open, the code runs immediately. Accepts the following options that modifies this behavior: * <tt>:only</tt> - Execute this code only on commit or only on rollback. Accepts one of the following symbols: <tt>:commit</tt>, <tt>:rollback</tt>. * <tt>:if_no_transaction</tt> - Specifies what to do if there is no active transaction. Accepts one of the following symbols: <tt>:run</tt> (default), <tt>:skip</tt> (do not run). Example of use: ActiveRecord::Base.transaction do # executes some code puts "runs within transaction" after_transaction do # things to do after transaction puts "runs after transaction" end # executes more code puts "again runs within transaction" end will output runs within transaction again runs within transaction runs after transaction
[ "Allows", "to", "execute", "any", "block", "of", "code", "after", "transaction", "completes", ".", "If", "no", "transaction", "is", "actually", "open", "the", "code", "runs", "immediately", "." ]
ee2bd83d1bd8b81e6b3d437ad7cfb44c7f1b9fb2
https://github.com/Beetrack/fish_transactions/blob/ee2bd83d1bd8b81e6b3d437ad7cfb44c7f1b9fb2/lib/fish_transactions/callbacks.rb#L88-L118
6,989
riddopic/garcun
lib/garcon/chef/coerce/coercer.rb
Garcon.Coercer.register
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
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
[ "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" ]
Registers a coercion with the Garcon library. @param [Class] origin The class to convert. @param [Class] target What the origin will be converted to.
[ "Registers", "a", "coercion", "with", "the", "Garcon", "library", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/chef/coerce/coercer.rb#L50-L56
6,990
benton/rds_backup_service
lib/rds_backup_service/model/backup_job.rb
RDSBackup.Job.write_to_s3
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
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
[ "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" ]
Writes this job's JSON representation to S3
[ "Writes", "this", "job", "s", "JSON", "representation", "to", "S3" ]
4930dd47e78a510f0a8abe21a5f9e1a483dda96f
https://github.com/benton/rds_backup_service/blob/4930dd47e78a510f0a8abe21a5f9e1a483dda96f/lib/rds_backup_service/model/backup_job.rb#L50-L58
6,991
benton/rds_backup_service
lib/rds_backup_service/model/backup_job.rb
RDSBackup.Job.perform_backup
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
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
[ "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" ]
Top-level, long-running method for performing the backup.
[ "Top", "-", "level", "long", "-", "running", "method", "for", "performing", "the", "backup", "." ]
4930dd47e78a510f0a8abe21a5f9e1a483dda96f
https://github.com/benton/rds_backup_service/blob/4930dd47e78a510f0a8abe21a5f9e1a483dda96f/lib/rds_backup_service/model/backup_job.rb#L74-L88
6,992
benton/rds_backup_service
lib/rds_backup_service/model/backup_job.rb
RDSBackup.Job.create_disconnected_rds
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
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
[ "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" ]
Step 1 of the overall process - create a disconnected copy of the RDS
[ "Step", "1", "of", "the", "overall", "process", "-", "create", "a", "disconnected", "copy", "of", "the", "RDS" ]
4930dd47e78a510f0a8abe21a5f9e1a483dda96f
https://github.com/benton/rds_backup_service/blob/4930dd47e78a510f0a8abe21a5f9e1a483dda96f/lib/rds_backup_service/model/backup_job.rb#L91-L100
6,993
benton/rds_backup_service
lib/rds_backup_service/model/backup_job.rb
RDSBackup.Job.prepare_backup
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
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
[ "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" ]
Queries RDS for any pre-existing entities associated with this job. Also waits for the original RDS to become ready.
[ "Queries", "RDS", "for", "any", "pre", "-", "existing", "entities", "associated", "with", "this", "job", ".", "Also", "waits", "for", "the", "original", "RDS", "to", "become", "ready", "." ]
4930dd47e78a510f0a8abe21a5f9e1a483dda96f
https://github.com/benton/rds_backup_service/blob/4930dd47e78a510f0a8abe21a5f9e1a483dda96f/lib/rds_backup_service/model/backup_job.rb#L104-L114
6,994
benton/rds_backup_service
lib/rds_backup_service/model/backup_job.rb
RDSBackup.Job.snapshot_original_rds
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
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
[ "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" ]
Snapshots the original RDS
[ "Snapshots", "the", "original", "RDS" ]
4930dd47e78a510f0a8abe21a5f9e1a483dda96f
https://github.com/benton/rds_backup_service/blob/4930dd47e78a510f0a8abe21a5f9e1a483dda96f/lib/rds_backup_service/model/backup_job.rb#L117-L124
6,995
benton/rds_backup_service
lib/rds_backup_service/model/backup_job.rb
RDSBackup.Job.create_tmp_rds_from_snapshot
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
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
[ "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" ]
Creates a new RDS from the snapshot
[ "Creates", "a", "new", "RDS", "from", "the", "snapshot" ]
4930dd47e78a510f0a8abe21a5f9e1a483dda96f
https://github.com/benton/rds_backup_service/blob/4930dd47e78a510f0a8abe21a5f9e1a483dda96f/lib/rds_backup_service/model/backup_job.rb#L127-L136
6,996
benton/rds_backup_service
lib/rds_backup_service/model/backup_job.rb
RDSBackup.Job.configure_tmp_rds
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
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
[ "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" ]
Updates the Master Password and applies the configured RDS Security Group
[ "Updates", "the", "Master", "Password", "and", "applies", "the", "configured", "RDS", "Security", "Group" ]
4930dd47e78a510f0a8abe21a5f9e1a483dda96f
https://github.com/benton/rds_backup_service/blob/4930dd47e78a510f0a8abe21a5f9e1a483dda96f/lib/rds_backup_service/model/backup_job.rb#L147-L157
6,997
benton/rds_backup_service
lib/rds_backup_service/model/backup_job.rb
RDSBackup.Job.wait_for_new_security_group
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
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
[ "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" ]
Wait for the new RDS Security Group to become 'active'
[ "Wait", "for", "the", "new", "RDS", "Security", "Group", "to", "become", "active" ]
4930dd47e78a510f0a8abe21a5f9e1a483dda96f
https://github.com/benton/rds_backup_service/blob/4930dd47e78a510f0a8abe21a5f9e1a483dda96f/lib/rds_backup_service/model/backup_job.rb#L160-L170
6,998
benton/rds_backup_service
lib/rds_backup_service/model/backup_job.rb
RDSBackup.Job.wait_for_new_parameter_group
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
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
[ "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" ]
Wait for the new RDS Parameter Group to become 'in-sync'
[ "Wait", "for", "the", "new", "RDS", "Parameter", "Group", "to", "become", "in", "-", "sync" ]
4930dd47e78a510f0a8abe21a5f9e1a483dda96f
https://github.com/benton/rds_backup_service/blob/4930dd47e78a510f0a8abe21a5f9e1a483dda96f/lib/rds_backup_service/model/backup_job.rb#L173-L188
6,999
benton/rds_backup_service
lib/rds_backup_service/model/backup_job.rb
RDSBackup.Job.update_status
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
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
[ "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" ]
Writes a new status message to the log, and writes the job info to S3
[ "Writes", "a", "new", "status", "message", "to", "the", "log", "and", "writes", "the", "job", "info", "to", "S3" ]
4930dd47e78a510f0a8abe21a5f9e1a483dda96f
https://github.com/benton/rds_backup_service/blob/4930dd47e78a510f0a8abe21a5f9e1a483dda96f/lib/rds_backup_service/model/backup_job.rb#L229-L235