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
8,700
zdavatz/htmlgrid
lib/htmlgrid/component.rb
HtmlGrid.Component.escape_symbols
def escape_symbols(txt) esc = '' txt.to_s.each_byte { |byte| esc << if(entity = @@symbol_entities[byte]) '&' << entity << ';' else byte end } esc end
ruby
def escape_symbols(txt) esc = '' txt.to_s.each_byte { |byte| esc << if(entity = @@symbol_entities[byte]) '&' << entity << ';' else byte end } esc end
[ "def", "escape_symbols", "(", "txt", ")", "esc", "=", "''", "txt", ".", "to_s", ".", "each_byte", "{", "|", "byte", "|", "esc", "<<", "if", "(", "entity", "=", "@@symbol_entities", "[", "byte", "]", ")", "'&'", "<<", "entity", "<<", "';'", "else", "byte", "end", "}", "esc", "end" ]
escape symbol-font strings
[ "escape", "symbol", "-", "font", "strings" ]
88a0440466e422328b4553685d0efe7c9bbb4d72
https://github.com/zdavatz/htmlgrid/blob/88a0440466e422328b4553685d0efe7c9bbb4d72/lib/htmlgrid/component.rb#L173-L183
8,701
dwa012/nacho
lib/nacho/helper.rb
Nacho.Helper.nacho_select_tag
def nacho_select_tag(name, choices = nil, options = {}, html_options = {}) nacho_options = build_options(name, choices, options, html_options) select_element = select_tag(name, options_for_select(nacho_options[:choices]), nacho_options[:options], nacho_options[:html_options]) select_element += nacho_options[:button] if nacho_options[:html_options][:multiple] select_element end
ruby
def nacho_select_tag(name, choices = nil, options = {}, html_options = {}) nacho_options = build_options(name, choices, options, html_options) select_element = select_tag(name, options_for_select(nacho_options[:choices]), nacho_options[:options], nacho_options[:html_options]) select_element += nacho_options[:button] if nacho_options[:html_options][:multiple] select_element end
[ "def", "nacho_select_tag", "(", "name", ",", "choices", "=", "nil", ",", "options", "=", "{", "}", ",", "html_options", "=", "{", "}", ")", "nacho_options", "=", "build_options", "(", "name", ",", "choices", ",", "options", ",", "html_options", ")", "select_element", "=", "select_tag", "(", "name", ",", "options_for_select", "(", "nacho_options", "[", ":choices", "]", ")", ",", "nacho_options", "[", ":options", "]", ",", "nacho_options", "[", ":html_options", "]", ")", "select_element", "+=", "nacho_options", "[", ":button", "]", "if", "nacho_options", "[", ":html_options", "]", "[", ":multiple", "]", "select_element", "end" ]
A tag helper version for a FormBuilder class. Will create the select and the needed modal that contains the given form for the target model to create. A multiple select will generate a button to trigger the modal. @param [Symbol] method See http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select. @param [Array] choices The list of choices for the select, shoudl be in [[val, display],...] format @param [Hash] options the options to create a message with. @option options [Boolean] :include_blank Include a blank option (Forced to <tt>true</tt> when <tt>choices.count</tt> == 0) @option options [String] :new_option_text Text to display as the <tt>option</tt> that will trigger the new modal (Default "-- Add new --", will be ignored if <tt>html_options[:multiple]</tt> is set to <tt>true</tt>) @option options [Symbol] :value_key The attribute of the model that will be used as the <tt>option</tt> value from the JSON return when a new record is created @option options [Symbol] :text_key The attribute of the model that will be used as the <tt>option</tt> display content from the JSON return when a new record is created @option options [Symbol] :new_key The JSON key that will contain the value of the record that was created with the modal @option options [String] :modal_title The title of the modal (Default to "Add new <model.class.name>") @option options [String] :partial The form partial for the modal body @param [Hash] html_options See http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select.
[ "A", "tag", "helper", "version", "for", "a", "FormBuilder", "class", ".", "Will", "create", "the", "select", "and", "the", "needed", "modal", "that", "contains", "the", "given", "form", "for", "the", "target", "model", "to", "create", "." ]
80b9dce74cdc0f17a59ee130de6d7c2bcdf9e903
https://github.com/dwa012/nacho/blob/80b9dce74cdc0f17a59ee130de6d7c2bcdf9e903/lib/nacho/helper.rb#L23-L29
8,702
checkdin/checkdin-ruby
lib/checkdin/custom_activities.rb
Checkdin.CustomActivities.create_custom_activity
def create_custom_activity(options={}) response = connection.post do |req| req.url "custom_activities", options end return_error_or_body(response) end
ruby
def create_custom_activity(options={}) response = connection.post do |req| req.url "custom_activities", options end return_error_or_body(response) end
[ "def", "create_custom_activity", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "post", "do", "|", "req", "|", "req", ".", "url", "\"custom_activities\"", ",", "options", "end", "return_error_or_body", "(", "response", ")", "end" ]
Notify checkd.in of a custom activity ocurring @param [Hash] options @option options Integer :custom_activity_node_id - The ID of the custom activity node that has ocurred, available in checkd.in admin. Required. @option options Integer :user_id - The ID of the user that has performed the custom activity - either this or email is required. @option options String :email - The email address of the user that has performed the custom activity - either this or user_id is required.
[ "Notify", "checkd", ".", "in", "of", "a", "custom", "activity", "ocurring" ]
c3c4b38b0f8c710e1f805100dcf3a70649215b48
https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/custom_activities.rb#L11-L16
8,703
michaelirey/mailgun_api
lib/mailgun/domain.rb
Mailgun.Domain.list
def list(domain=nil) if domain @mailgun.response = Mailgun::Base.fire(:get, @mailgun.api_url + "/domains/#{domain}") else @mailgun.response = Mailgun::Base.fire(:get, @mailgun.api_url + "/domains")["items"] || [] end end
ruby
def list(domain=nil) if domain @mailgun.response = Mailgun::Base.fire(:get, @mailgun.api_url + "/domains/#{domain}") else @mailgun.response = Mailgun::Base.fire(:get, @mailgun.api_url + "/domains")["items"] || [] end end
[ "def", "list", "(", "domain", "=", "nil", ")", "if", "domain", "@mailgun", ".", "response", "=", "Mailgun", "::", "Base", ".", "fire", "(", ":get", ",", "@mailgun", ".", "api_url", "+", "\"/domains/#{domain}\"", ")", "else", "@mailgun", ".", "response", "=", "Mailgun", "::", "Base", ".", "fire", "(", ":get", ",", "@mailgun", ".", "api_url", "+", "\"/domains\"", ")", "[", "\"items\"", "]", "||", "[", "]", "end", "end" ]
Used internally List Domains. If domain name is passed return detailed information, otherwise return a list of all domains.
[ "Used", "internally", "List", "Domains", ".", "If", "domain", "name", "is", "passed", "return", "detailed", "information", "otherwise", "return", "a", "list", "of", "all", "domains", "." ]
1008cb653b7ba346e8e5404d772f0ebc8f99fa7e
https://github.com/michaelirey/mailgun_api/blob/1008cb653b7ba346e8e5404d772f0ebc8f99fa7e/lib/mailgun/domain.rb#L17-L23
8,704
kamui/kanpachi
lib/kanpachi/response_list.rb
Kanpachi.ResponseList.add
def add(response) if @list.key? response.name raise DuplicateResponse, "A response named #{response.name} already exists" end @list[response.name] = response end
ruby
def add(response) if @list.key? response.name raise DuplicateResponse, "A response named #{response.name} already exists" end @list[response.name] = response end
[ "def", "add", "(", "response", ")", "if", "@list", ".", "key?", "response", ".", "name", "raise", "DuplicateResponse", ",", "\"A response named #{response.name} already exists\"", "end", "@list", "[", "response", ".", "name", "]", "=", "response", "end" ]
Add a response to the list @param [Kanpachi::Response] response The response to add. @return [Hash<Kanpachi::Response>] All the added responses. @raise DuplicateResponse If a response is being duplicated. @api public
[ "Add", "a", "response", "to", "the", "list" ]
dbd09646bd8779ab874e1578b57a13f5747b0da7
https://github.com/kamui/kanpachi/blob/dbd09646bd8779ab874e1578b57a13f5747b0da7/lib/kanpachi/response_list.rb#L34-L39
8,705
futurechimp/drafter
lib/drafter/apply.rb
Drafter.Apply.restore_attrs
def restore_attrs draftable_columns.each do |key| self.send "#{key}=", self.draft.data[key] if self.respond_to?(key) end self end
ruby
def restore_attrs draftable_columns.each do |key| self.send "#{key}=", self.draft.data[key] if self.respond_to?(key) end self end
[ "def", "restore_attrs", "draftable_columns", ".", "each", "do", "|", "key", "|", "self", ".", "send", "\"#{key}=\"", ",", "self", ".", "draft", ".", "data", "[", "key", "]", "if", "self", ".", "respond_to?", "(", "key", ")", "end", "self", "end" ]
Whack the draft data onto the real object. @return [Draftable] the draftable object populated with the draft attrs.
[ "Whack", "the", "draft", "data", "onto", "the", "real", "object", "." ]
8308b922148a6a44280023b0ef33d48a41f2e83e
https://github.com/futurechimp/drafter/blob/8308b922148a6a44280023b0ef33d48a41f2e83e/lib/drafter/apply.rb#L22-L27
8,706
futurechimp/drafter
lib/drafter/apply.rb
Drafter.Apply.restore_files
def restore_files draft.draft_uploads.each do |draft_upload| uploader = draft_upload.draftable_mount_column self.send(uploader + "=", draft_upload.file_data) end end
ruby
def restore_files draft.draft_uploads.each do |draft_upload| uploader = draft_upload.draftable_mount_column self.send(uploader + "=", draft_upload.file_data) end end
[ "def", "restore_files", "draft", ".", "draft_uploads", ".", "each", "do", "|", "draft_upload", "|", "uploader", "=", "draft_upload", ".", "draftable_mount_column", "self", ".", "send", "(", "uploader", "+", "\"=\"", ",", "draft_upload", ".", "file_data", ")", "end", "end" ]
Attach draft files to the real object. @return [Draftable] the draftable object where CarrierWave uploads on the object have been replaced with their draft equivalents.
[ "Attach", "draft", "files", "to", "the", "real", "object", "." ]
8308b922148a6a44280023b0ef33d48a41f2e83e
https://github.com/futurechimp/drafter/blob/8308b922148a6a44280023b0ef33d48a41f2e83e/lib/drafter/apply.rb#L33-L38
8,707
stevedowney/rails_view_helpers
app/helpers/rails_view_helpers/html_helper.rb
RailsViewHelpers.HtmlHelper.body_tag
def body_tag(options={}, &block) options = canonicalize_options(options) options.delete(:class) if options[:class].blank? options[:data] ||= {} options[:data][:controller] = controller.controller_name options[:data][:action] = controller.action_name content_tag(:body, options) do yield end end
ruby
def body_tag(options={}, &block) options = canonicalize_options(options) options.delete(:class) if options[:class].blank? options[:data] ||= {} options[:data][:controller] = controller.controller_name options[:data][:action] = controller.action_name content_tag(:body, options) do yield end end
[ "def", "body_tag", "(", "options", "=", "{", "}", ",", "&", "block", ")", "options", "=", "canonicalize_options", "(", "options", ")", "options", ".", "delete", "(", ":class", ")", "if", "options", "[", ":class", "]", ".", "blank?", "options", "[", ":data", "]", "||=", "{", "}", "options", "[", ":data", "]", "[", ":controller", "]", "=", "controller", ".", "controller_name", "options", "[", ":data", "]", "[", ":action", "]", "=", "controller", ".", "action_name", "content_tag", "(", ":body", ",", "options", ")", "do", "yield", "end", "end" ]
Includes controller and action name as data attributes. @example body_tag() #=> <body data-action='index' data-controller='home'> body_tag(id: 'my-id', class: 'my-class') #=> <body class="my-class" data-action="index" data-controller="home" id="my-id"> @param options [Hash] become attributes of the BODY tag @return [String]
[ "Includes", "controller", "and", "action", "name", "as", "data", "attributes", "." ]
715c7daca9434c763b777be25b1069ecc50df287
https://github.com/stevedowney/rails_view_helpers/blob/715c7daca9434c763b777be25b1069ecc50df287/app/helpers/rails_view_helpers/html_helper.rb#L13-L23
8,708
appdrones/page_record
lib/page_record/validations.rb
PageRecord.Validations.errors
def errors found_errors = @record.all('[data-error-for]') error_list = ActiveModel::Errors.new(self) found_errors.each do | error | attribute = error['data-error-for'] message = error.text error_list.add(attribute, message) end error_list end
ruby
def errors found_errors = @record.all('[data-error-for]') error_list = ActiveModel::Errors.new(self) found_errors.each do | error | attribute = error['data-error-for'] message = error.text error_list.add(attribute, message) end error_list end
[ "def", "errors", "found_errors", "=", "@record", ".", "all", "(", "'[data-error-for]'", ")", "error_list", "=", "ActiveModel", "::", "Errors", ".", "new", "(", "self", ")", "found_errors", ".", "each", "do", "|", "error", "|", "attribute", "=", "error", "[", "'data-error-for'", "]", "message", "=", "error", ".", "text", "error_list", ".", "add", "(", "attribute", ",", "message", ")", "end", "error_list", "end" ]
Searches the record for any errors and returns them @return [ActiveModel::Errors] the error object for the current record @raise [AttributeNotFound] when the attribute is not found in the record
[ "Searches", "the", "record", "for", "any", "errors", "and", "returns", "them" ]
2a6d285cbfab906dad6f13f66fea1c09d354b762
https://github.com/appdrones/page_record/blob/2a6d285cbfab906dad6f13f66fea1c09d354b762/lib/page_record/validations.rb#L12-L21
8,709
Velir/kaltura_fu
lib/kaltura_fu/view_helpers.rb
KalturaFu.ViewHelpers.kaltura_player_embed
def kaltura_player_embed(entry_id,options={}) player_conf_parameter = "/ui_conf_id/" options[:div_id] ||= "kplayer" options[:size] ||= [] options[:use_url] ||= false width = PLAYER_WIDTH height = PLAYER_HEIGHT source_type = "entryId" unless options[:size].empty? width = options[:size].first height = options[:size].last end if options[:use_url] == true source_type = "url" end unless options[:player_conf_id].nil? player_conf_parameter += "#{options[:player_conf_id]}" else unless KalturaFu.config.player_conf_id.nil? player_conf_parameter += "#{KalturaFu.config.player_conf_id}" else player_conf_parameter += "#{DEFAULT_KPLAYER}" end end "<div id=\"#{options[:div_id]}\"></div> <script type=\"text/javascript\"> var params= { allowscriptaccess: \"always\", allownetworking: \"all\", allowfullscreen: \"true\", wmode: \"opaque\", bgcolor: \"#000000\" }; var flashVars = {}; flashVars.sourceType = \"#{source_type}\"; flashVars.entryId = \"#{entry_id}\"; flashVars.emptyF = \"onKdpEmpty\"; flashVars.readyF = \"onKdpReady\"; var attributes = { id: \"#{options[:div_id]}\", name: \"#{options[:div_id]}\" }; swfobject.embedSWF(\"#{KalturaFu.config.service_url}/kwidget/wid/_#{KalturaFu.config.partner_id}" + player_conf_parameter + "\",\"#{options[:div_id]}\",\"#{width}\",\"#{height}\",\"10.0.0\",\"http://ttv.mit.edu/swfs/expressinstall.swf\",flashVars,params,attributes); </script>" end
ruby
def kaltura_player_embed(entry_id,options={}) player_conf_parameter = "/ui_conf_id/" options[:div_id] ||= "kplayer" options[:size] ||= [] options[:use_url] ||= false width = PLAYER_WIDTH height = PLAYER_HEIGHT source_type = "entryId" unless options[:size].empty? width = options[:size].first height = options[:size].last end if options[:use_url] == true source_type = "url" end unless options[:player_conf_id].nil? player_conf_parameter += "#{options[:player_conf_id]}" else unless KalturaFu.config.player_conf_id.nil? player_conf_parameter += "#{KalturaFu.config.player_conf_id}" else player_conf_parameter += "#{DEFAULT_KPLAYER}" end end "<div id=\"#{options[:div_id]}\"></div> <script type=\"text/javascript\"> var params= { allowscriptaccess: \"always\", allownetworking: \"all\", allowfullscreen: \"true\", wmode: \"opaque\", bgcolor: \"#000000\" }; var flashVars = {}; flashVars.sourceType = \"#{source_type}\"; flashVars.entryId = \"#{entry_id}\"; flashVars.emptyF = \"onKdpEmpty\"; flashVars.readyF = \"onKdpReady\"; var attributes = { id: \"#{options[:div_id]}\", name: \"#{options[:div_id]}\" }; swfobject.embedSWF(\"#{KalturaFu.config.service_url}/kwidget/wid/_#{KalturaFu.config.partner_id}" + player_conf_parameter + "\",\"#{options[:div_id]}\",\"#{width}\",\"#{height}\",\"10.0.0\",\"http://ttv.mit.edu/swfs/expressinstall.swf\",flashVars,params,attributes); </script>" end
[ "def", "kaltura_player_embed", "(", "entry_id", ",", "options", "=", "{", "}", ")", "player_conf_parameter", "=", "\"/ui_conf_id/\"", "options", "[", ":div_id", "]", "||=", "\"kplayer\"", "options", "[", ":size", "]", "||=", "[", "]", "options", "[", ":use_url", "]", "||=", "false", "width", "=", "PLAYER_WIDTH", "height", "=", "PLAYER_HEIGHT", "source_type", "=", "\"entryId\"", "unless", "options", "[", ":size", "]", ".", "empty?", "width", "=", "options", "[", ":size", "]", ".", "first", "height", "=", "options", "[", ":size", "]", ".", "last", "end", "if", "options", "[", ":use_url", "]", "==", "true", "source_type", "=", "\"url\"", "end", "unless", "options", "[", ":player_conf_id", "]", ".", "nil?", "player_conf_parameter", "+=", "\"#{options[:player_conf_id]}\"", "else", "unless", "KalturaFu", ".", "config", ".", "player_conf_id", ".", "nil?", "player_conf_parameter", "+=", "\"#{KalturaFu.config.player_conf_id}\"", "else", "player_conf_parameter", "+=", "\"#{DEFAULT_KPLAYER}\"", "end", "end", "\"<div id=\\\"#{options[:div_id]}\\\"></div>\n <script type=\\\"text/javascript\\\">\n \tvar params= {\n \t\tallowscriptaccess: \\\"always\\\",\n \t\tallownetworking: \\\"all\\\",\n \t\tallowfullscreen: \\\"true\\\",\n \t\twmode: \\\"opaque\\\",\n \t\tbgcolor: \\\"#000000\\\"\n \t};\n \tvar flashVars = {};\n \tflashVars.sourceType = \\\"#{source_type}\\\"; \t \n \tflashVars.entryId = \\\"#{entry_id}\\\";\n \tflashVars.emptyF = \\\"onKdpEmpty\\\";\n \t\tflashVars.readyF = \\\"onKdpReady\\\";\n \t\t\n \tvar attributes = {\n id: \\\"#{options[:div_id]}\\\",\n name: \\\"#{options[:div_id]}\\\"\n \t};\n\n \tswfobject.embedSWF(\\\"#{KalturaFu.config.service_url}/kwidget/wid/_#{KalturaFu.config.partner_id}\"", "+", "player_conf_parameter", "+", "\"\\\",\\\"#{options[:div_id]}\\\",\\\"#{width}\\\",\\\"#{height}\\\",\\\"10.0.0\\\",\\\"http://ttv.mit.edu/swfs/expressinstall.swf\\\",flashVars,params,attributes);\n </script>\"", "end" ]
Returns the code needed to embed a KDPv3 player. @param [String] entry_id Kaltura entry_id @param [Hash] options the embed code options. @option options [String] :div_id ('kplayer') The div element that the flash object will be inserted into. @option options [Array] :size ([]) The [width,wight] of the player. @option options [Boolean] :use_url (false) flag to determine whether entry_id is an entry or a URL of a flash file. @option options [String] :player_conf_id (KalturaFu.config(:player_conf_id)) A UI Conf ID to override the player with. @return [String] returns a string representation of the html/javascript necessary to play a Kaltura entry.
[ "Returns", "the", "code", "needed", "to", "embed", "a", "KDPv3", "player", "." ]
539e476786d1fd2257b90dfb1e50c2c75ae75bdd
https://github.com/Velir/kaltura_fu/blob/539e476786d1fd2257b90dfb1e50c2c75ae75bdd/lib/kaltura_fu/view_helpers.rb#L75-L125
8,710
Velir/kaltura_fu
lib/kaltura_fu/view_helpers.rb
KalturaFu.ViewHelpers.kaltura_seek_link
def kaltura_seek_link(content,seek_time,options={}) options[:div_id] ||= "kplayer" options[:onclick] = "$(#{options[:div_id]}).get(0).sendNotification('doSeek',#{seek_time});window.scrollTo(0,0);return false;" options.delete(:div_id) link_to(content,"#", options) end
ruby
def kaltura_seek_link(content,seek_time,options={}) options[:div_id] ||= "kplayer" options[:onclick] = "$(#{options[:div_id]}).get(0).sendNotification('doSeek',#{seek_time});window.scrollTo(0,0);return false;" options.delete(:div_id) link_to(content,"#", options) end
[ "def", "kaltura_seek_link", "(", "content", ",", "seek_time", ",", "options", "=", "{", "}", ")", "options", "[", ":div_id", "]", "||=", "\"kplayer\"", "options", "[", ":onclick", "]", "=", "\"$(#{options[:div_id]}).get(0).sendNotification('doSeek',#{seek_time});window.scrollTo(0,0);return false;\"", "options", ".", "delete", "(", ":div_id", ")", "link_to", "(", "content", ",", "\"#\"", ",", "options", ")", "end" ]
Creates a link_to tag that seeks to a certain time on a KDPv3 player. @param [String] content The text in the link tag. @param [Integer] seek_time The time in seconds to seek the player to. @param [Hash] options @option options [String] :div_id ('kplayer') The div of the KDP player.
[ "Creates", "a", "link_to", "tag", "that", "seeks", "to", "a", "certain", "time", "on", "a", "KDPv3", "player", "." ]
539e476786d1fd2257b90dfb1e50c2c75ae75bdd
https://github.com/Velir/kaltura_fu/blob/539e476786d1fd2257b90dfb1e50c2c75ae75bdd/lib/kaltura_fu/view_helpers.rb#L173-L179
8,711
nerab/hms
lib/hms/duration.rb
HMS.Duration.op
def op(sym, o) case o when Duration Duration.new(@seconds.send(sym, o.to_i)) when Numeric Duration.new(@seconds.send(sym, o)) else a, b = o.coerce(self) a.send(sym, b) end end
ruby
def op(sym, o) case o when Duration Duration.new(@seconds.send(sym, o.to_i)) when Numeric Duration.new(@seconds.send(sym, o)) else a, b = o.coerce(self) a.send(sym, b) end end
[ "def", "op", "(", "sym", ",", "o", ")", "case", "o", "when", "Duration", "Duration", ".", "new", "(", "@seconds", ".", "send", "(", "sym", ",", "o", ".", "to_i", ")", ")", "when", "Numeric", "Duration", ".", "new", "(", "@seconds", ".", "send", "(", "sym", ",", "o", ")", ")", "else", "a", ",", "b", "=", "o", ".", "coerce", "(", "self", ")", "a", ".", "send", "(", "sym", ",", "b", ")", "end", "end" ]
generic operator implementation
[ "generic", "operator", "implementation" ]
9f373eb48847e5055110c90c6dde924ba4a2181b
https://github.com/nerab/hms/blob/9f373eb48847e5055110c90c6dde924ba4a2181b/lib/hms/duration.rb#L139-L149
8,712
wapcaplet/kelp
lib/kelp/navigation.rb
Kelp.Navigation.follow
def follow(link, scope={}) in_scope(scope) do begin click_link(link) rescue Capybara::ElementNotFound raise Kelp::MissingLink, "No link with title, id or text '#{link}' found" end end end
ruby
def follow(link, scope={}) in_scope(scope) do begin click_link(link) rescue Capybara::ElementNotFound raise Kelp::MissingLink, "No link with title, id or text '#{link}' found" end end end
[ "def", "follow", "(", "link", ",", "scope", "=", "{", "}", ")", "in_scope", "(", "scope", ")", "do", "begin", "click_link", "(", "link", ")", "rescue", "Capybara", "::", "ElementNotFound", "raise", "Kelp", "::", "MissingLink", ",", "\"No link with title, id or text '#{link}' found\"", "end", "end", "end" ]
Follow a link on the page. @example follow "Login" follow "Contact Us", :within => "#footer" @param [String] link Capybara locator expression (id, name, or link text) @param [Hash] scope Scoping keywords as understood by {#in_scope}
[ "Follow", "a", "link", "on", "the", "page", "." ]
592fe188db5a3d05e6120ed2157ad8d781601b7a
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/navigation.rb#L27-L36
8,713
wapcaplet/kelp
lib/kelp/navigation.rb
Kelp.Navigation.press
def press(button, scope={}) in_scope(scope) do begin click_button(button) rescue Capybara::ElementNotFound raise Kelp::MissingButton, "No button with value, id or text '#{button}' found" end end end
ruby
def press(button, scope={}) in_scope(scope) do begin click_button(button) rescue Capybara::ElementNotFound raise Kelp::MissingButton, "No button with value, id or text '#{button}' found" end end end
[ "def", "press", "(", "button", ",", "scope", "=", "{", "}", ")", "in_scope", "(", "scope", ")", "do", "begin", "click_button", "(", "button", ")", "rescue", "Capybara", "::", "ElementNotFound", "raise", "Kelp", "::", "MissingButton", ",", "\"No button with value, id or text '#{button}' found\"", "end", "end", "end" ]
Press a button on the page. @example press "Cancel" press "Submit", :within => "#survey" @param [String] button Capybara locator expression (id, name, or button text) @param [Hash] scope Scoping keywords as understood by {#in_scope}
[ "Press", "a", "button", "on", "the", "page", "." ]
592fe188db5a3d05e6120ed2157ad8d781601b7a
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/navigation.rb#L49-L58
8,714
wapcaplet/kelp
lib/kelp/navigation.rb
Kelp.Navigation.click_link_in_row
def click_link_in_row(link, text) begin row = find(:xpath, xpath_row_containing([link, text])) rescue Capybara::ElementNotFound raise Kelp::MissingRow, "No table row found containing '#{link}' and '#{text}'" end begin row.click_link(link) rescue Capybara::ElementNotFound raise Kelp::MissingLink, "No link with title, id or text '#{link}' found in the same row as '#{text}'" end end
ruby
def click_link_in_row(link, text) begin row = find(:xpath, xpath_row_containing([link, text])) rescue Capybara::ElementNotFound raise Kelp::MissingRow, "No table row found containing '#{link}' and '#{text}'" end begin row.click_link(link) rescue Capybara::ElementNotFound raise Kelp::MissingLink, "No link with title, id or text '#{link}' found in the same row as '#{text}'" end end
[ "def", "click_link_in_row", "(", "link", ",", "text", ")", "begin", "row", "=", "find", "(", ":xpath", ",", "xpath_row_containing", "(", "[", "link", ",", "text", "]", ")", ")", "rescue", "Capybara", "::", "ElementNotFound", "raise", "Kelp", "::", "MissingRow", ",", "\"No table row found containing '#{link}' and '#{text}'\"", "end", "begin", "row", ".", "click_link", "(", "link", ")", "rescue", "Capybara", "::", "ElementNotFound", "raise", "Kelp", "::", "MissingLink", ",", "\"No link with title, id or text '#{link}' found in the same row as '#{text}'\"", "end", "end" ]
Click a link in a table row containing the given text. @example click_link_in_row "Edit", "Pinky" @param [String] link Content of the link to click @param [String] text Other content that must be in the same row
[ "Click", "a", "link", "in", "a", "table", "row", "containing", "the", "given", "text", "." ]
592fe188db5a3d05e6120ed2157ad8d781601b7a
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/navigation.rb#L71-L84
8,715
wapcaplet/kelp
lib/kelp/navigation.rb
Kelp.Navigation.should_be_on_page
def should_be_on_page(page_name_or_path) # Use the path_to translator function if it's defined # (normally in features/support/paths.rb) if defined? path_to expect_path = path_to(page_name_or_path) # Otherwise, expect a raw path string else expect_path = page_name_or_path end actual_path = URI.parse(current_url).path if actual_path != expect_path raise Kelp::Unexpected, "Expected to be on page: '#{expect_path}'" + \ "\nActually on page: '#{actual_path}'" end end
ruby
def should_be_on_page(page_name_or_path) # Use the path_to translator function if it's defined # (normally in features/support/paths.rb) if defined? path_to expect_path = path_to(page_name_or_path) # Otherwise, expect a raw path string else expect_path = page_name_or_path end actual_path = URI.parse(current_url).path if actual_path != expect_path raise Kelp::Unexpected, "Expected to be on page: '#{expect_path}'" + \ "\nActually on page: '#{actual_path}'" end end
[ "def", "should_be_on_page", "(", "page_name_or_path", ")", "# Use the path_to translator function if it's defined", "# (normally in features/support/paths.rb)", "if", "defined?", "path_to", "expect_path", "=", "path_to", "(", "page_name_or_path", ")", "# Otherwise, expect a raw path string", "else", "expect_path", "=", "page_name_or_path", "end", "actual_path", "=", "URI", ".", "parse", "(", "current_url", ")", ".", "path", "if", "actual_path", "!=", "expect_path", "raise", "Kelp", "::", "Unexpected", ",", "\"Expected to be on page: '#{expect_path}'\"", "+", "\"\\nActually on page: '#{actual_path}'\"", "end", "end" ]
Verify that the current page matches the path of `page_name_or_path`. The cucumber-generated `path_to` function will be used, if it's defined, to translate human-readable names into URL paths. Otherwise, assume a raw, absolute path string. @example should_be_on_page 'home page' should_be_on_page '/admin/login' @param [String] page_name_or_path Human-readable page name (mapped to a pathname by your `path_to` function), or an absolute path beginning with `/`. @raise [Kelp::Unexpected] If actual page path doesn't match the expected path @since 0.1.9
[ "Verify", "that", "the", "current", "page", "matches", "the", "path", "of", "page_name_or_path", ".", "The", "cucumber", "-", "generated", "path_to", "function", "will", "be", "used", "if", "it", "s", "defined", "to", "translate", "human", "-", "readable", "names", "into", "URL", "paths", ".", "Otherwise", "assume", "a", "raw", "absolute", "path", "string", "." ]
592fe188db5a3d05e6120ed2157ad8d781601b7a
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/navigation.rb#L114-L129
8,716
wapcaplet/kelp
lib/kelp/navigation.rb
Kelp.Navigation.should_have_query
def should_have_query(params) query = URI.parse(current_url).query actual_params = query ? CGI.parse(query) : {} expected_params = {} params.each_pair do |k,v| expected_params[k] = v.split(',') end if actual_params != expected_params raise Kelp::Unexpected, "Expected query params: '#{expected_params.inspect}'" + \ "\nActual query params: '#{actual_params.inspect}'" end end
ruby
def should_have_query(params) query = URI.parse(current_url).query actual_params = query ? CGI.parse(query) : {} expected_params = {} params.each_pair do |k,v| expected_params[k] = v.split(',') end if actual_params != expected_params raise Kelp::Unexpected, "Expected query params: '#{expected_params.inspect}'" + \ "\nActual query params: '#{actual_params.inspect}'" end end
[ "def", "should_have_query", "(", "params", ")", "query", "=", "URI", ".", "parse", "(", "current_url", ")", ".", "query", "actual_params", "=", "query", "?", "CGI", ".", "parse", "(", "query", ")", ":", "{", "}", "expected_params", "=", "{", "}", "params", ".", "each_pair", "do", "|", "k", ",", "v", "|", "expected_params", "[", "k", "]", "=", "v", ".", "split", "(", "','", ")", "end", "if", "actual_params", "!=", "expected_params", "raise", "Kelp", "::", "Unexpected", ",", "\"Expected query params: '#{expected_params.inspect}'\"", "+", "\"\\nActual query params: '#{actual_params.inspect}'\"", "end", "end" ]
Verify that the current page has the given query parameters. @param [Hash] params Key => value parameters, as they would appear in the URL @raise [Kelp::Unexpected] If actual query parameters don't match expected parameters @since 0.1.9
[ "Verify", "that", "the", "current", "page", "has", "the", "given", "query", "parameters", "." ]
592fe188db5a3d05e6120ed2157ad8d781601b7a
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/navigation.rb#L142-L154
8,717
petebrowne/machined
lib/machined/static_compiler.rb
Machined.StaticCompiler.compile
def compile compiled_assets = {} machined.sprockets.each do |sprocket| next unless sprocket.compile? sprocket.each_logical_path do |logical_path| url = File.join(sprocket.config.url, logical_path) next unless compiled_assets[url].nil? && compile?(url) if asset = sprocket.find_asset(logical_path) compiled_assets[url] = write_asset(sprocket, asset) end end end compiled_assets end
ruby
def compile compiled_assets = {} machined.sprockets.each do |sprocket| next unless sprocket.compile? sprocket.each_logical_path do |logical_path| url = File.join(sprocket.config.url, logical_path) next unless compiled_assets[url].nil? && compile?(url) if asset = sprocket.find_asset(logical_path) compiled_assets[url] = write_asset(sprocket, asset) end end end compiled_assets end
[ "def", "compile", "compiled_assets", "=", "{", "}", "machined", ".", "sprockets", ".", "each", "do", "|", "sprocket", "|", "next", "unless", "sprocket", ".", "compile?", "sprocket", ".", "each_logical_path", "do", "|", "logical_path", "|", "url", "=", "File", ".", "join", "(", "sprocket", ".", "config", ".", "url", ",", "logical_path", ")", "next", "unless", "compiled_assets", "[", "url", "]", ".", "nil?", "&&", "compile?", "(", "url", ")", "if", "asset", "=", "sprocket", ".", "find_asset", "(", "logical_path", ")", "compiled_assets", "[", "url", "]", "=", "write_asset", "(", "sprocket", ",", "asset", ")", "end", "end", "end", "compiled_assets", "end" ]
Creates a new instance, which will compile the assets to the given +output_path+. Loop through and compile each available asset to the appropriate output path.
[ "Creates", "a", "new", "instance", "which", "will", "compile", "the", "assets", "to", "the", "given", "+", "output_path", "+", ".", "Loop", "through", "and", "compile", "each", "available", "asset", "to", "the", "appropriate", "output", "path", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/lib/machined/static_compiler.rb#L17-L31
8,718
petebrowne/machined
lib/machined/static_compiler.rb
Machined.StaticCompiler.write_asset
def write_asset(environment, asset) filename = path_for(environment, asset) FileUtils.mkdir_p File.dirname(filename) asset.write_to filename asset.write_to "#{filename}.gz" if gzip?(filename) asset.digest end
ruby
def write_asset(environment, asset) filename = path_for(environment, asset) FileUtils.mkdir_p File.dirname(filename) asset.write_to filename asset.write_to "#{filename}.gz" if gzip?(filename) asset.digest end
[ "def", "write_asset", "(", "environment", ",", "asset", ")", "filename", "=", "path_for", "(", "environment", ",", "asset", ")", "FileUtils", ".", "mkdir_p", "File", ".", "dirname", "(", "filename", ")", "asset", ".", "write_to", "filename", "asset", ".", "write_to", "\"#{filename}.gz\"", "if", "gzip?", "(", "filename", ")", "asset", ".", "digest", "end" ]
Writes the asset to its destination, also writing a gzipped version if necessary.
[ "Writes", "the", "asset", "to", "its", "destination", "also", "writing", "a", "gzipped", "version", "if", "necessary", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/lib/machined/static_compiler.rb#L42-L48
8,719
petebrowne/machined
lib/machined/static_compiler.rb
Machined.StaticCompiler.path_for
def path_for(environment, asset) # :nodoc: path = digest?(environment, asset) ? asset.digest_path : asset.logical_path File.join(machined.output_path, environment.config.url, path) end
ruby
def path_for(environment, asset) # :nodoc: path = digest?(environment, asset) ? asset.digest_path : asset.logical_path File.join(machined.output_path, environment.config.url, path) end
[ "def", "path_for", "(", "environment", ",", "asset", ")", "# :nodoc:", "path", "=", "digest?", "(", "environment", ",", "asset", ")", "?", "asset", ".", "digest_path", ":", "asset", ".", "logical_path", "File", ".", "join", "(", "machined", ".", "output_path", ",", "environment", ".", "config", ".", "url", ",", "path", ")", "end" ]
Gets the full output path for the given asset. If it's supposed to include a digest, it will return the digest_path.
[ "Gets", "the", "full", "output", "path", "for", "the", "given", "asset", ".", "If", "it", "s", "supposed", "to", "include", "a", "digest", "it", "will", "return", "the", "digest_path", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/lib/machined/static_compiler.rb#L55-L58
8,720
bilus/kawaii
lib/kawaii/route_handler.rb
Kawaii.RouteHandler.call
def call(env) @request = Rack::Request.new(env) @params = @path_params.merge(@request.params.symbolize_keys) process_response(instance_exec(self, params, request, &@block)) end
ruby
def call(env) @request = Rack::Request.new(env) @params = @path_params.merge(@request.params.symbolize_keys) process_response(instance_exec(self, params, request, &@block)) end
[ "def", "call", "(", "env", ")", "@request", "=", "Rack", "::", "Request", ".", "new", "(", "env", ")", "@params", "=", "@path_params", ".", "merge", "(", "@request", ".", "params", ".", "symbolize_keys", ")", "process_response", "(", "instance_exec", "(", "self", ",", "params", ",", "request", ",", "@block", ")", ")", "end" ]
Creates a new RouteHandler wrapping a handler block. @param path_params [Hash] named parameters from paths similar to /users/:id @param block [Proc] the actual route handler Invokes the handler as a normal Rack application. @param env [Hash] Rack environment @return [Array] Rack response array
[ "Creates", "a", "new", "RouteHandler", "wrapping", "a", "handler", "block", "." ]
a72be28e713b0ed2b2cfc180a38bebe0c968b0b3
https://github.com/bilus/kawaii/blob/a72be28e713b0ed2b2cfc180a38bebe0c968b0b3/lib/kawaii/route_handler.rb#L32-L36
8,721
ktonon/code_node
spec/fixtures/activerecord/src/active_record/associations/builder/has_and_belongs_to_many.rb
ActiveRecord::Associations::Builder.HasAndBelongsToMany.join_table_name
def join_table_name(first_table_name, second_table_name) if first_table_name < second_table_name join_table = "#{first_table_name}_#{second_table_name}" else join_table = "#{second_table_name}_#{first_table_name}" end model.table_name_prefix + join_table + model.table_name_suffix end
ruby
def join_table_name(first_table_name, second_table_name) if first_table_name < second_table_name join_table = "#{first_table_name}_#{second_table_name}" else join_table = "#{second_table_name}_#{first_table_name}" end model.table_name_prefix + join_table + model.table_name_suffix end
[ "def", "join_table_name", "(", "first_table_name", ",", "second_table_name", ")", "if", "first_table_name", "<", "second_table_name", "join_table", "=", "\"#{first_table_name}_#{second_table_name}\"", "else", "join_table", "=", "\"#{second_table_name}_#{first_table_name}\"", "end", "model", ".", "table_name_prefix", "+", "join_table", "+", "model", ".", "table_name_suffix", "end" ]
Generates a join table name from two provided table names. The names in the join table names end up in lexicographic order. join_table_name("members", "clubs") # => "clubs_members" join_table_name("members", "special_clubs") # => "members_special_clubs"
[ "Generates", "a", "join", "table", "name", "from", "two", "provided", "table", "names", ".", "The", "names", "in", "the", "join", "table", "names", "end", "up", "in", "lexicographic", "order", "." ]
48d5d1a7442d9cade602be4fb782a1b56c7677f5
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/associations/builder/has_and_belongs_to_many.rb#L47-L55
8,722
koppen/in_columns
lib/in_columns/columnizer.rb
InColumns.Columnizer.row_counts
def row_counts(number_of_columns) per_column = (number_of_elements / number_of_columns).floor counts = [per_column] * number_of_columns left_overs = number_of_elements % number_of_columns left_overs.times { |n| counts[n] = counts[n] + 1 } counts end
ruby
def row_counts(number_of_columns) per_column = (number_of_elements / number_of_columns).floor counts = [per_column] * number_of_columns left_overs = number_of_elements % number_of_columns left_overs.times { |n| counts[n] = counts[n] + 1 } counts end
[ "def", "row_counts", "(", "number_of_columns", ")", "per_column", "=", "(", "number_of_elements", "/", "number_of_columns", ")", ".", "floor", "counts", "=", "[", "per_column", "]", "*", "number_of_columns", "left_overs", "=", "number_of_elements", "%", "number_of_columns", "left_overs", ".", "times", "{", "|", "n", "|", "counts", "[", "n", "]", "=", "counts", "[", "n", "]", "+", "1", "}", "counts", "end" ]
Returns an array with an element for each column containing the number of rows for that column
[ "Returns", "an", "array", "with", "an", "element", "for", "each", "column", "containing", "the", "number", "of", "rows", "for", "that", "column" ]
de3abb612dada4d99b3720a8b885196864b5ce5b
https://github.com/koppen/in_columns/blob/de3abb612dada4d99b3720a8b885196864b5ce5b/lib/in_columns/columnizer.rb#L48-L58
8,723
26fe/dircat
lib/dircat/cat_on_sqlite/cat_on_sqlite.rb
SimpleCataloger.CatOnSqlite.require_models
def require_models model_dir = File.join(File.dirname(__FILE__), %w{ model }) unless Dir.exist? model_dir raise "model directory '#{model_dir}' not exists" end Dir[File.join(model_dir, '*.rb')].each do |f| # puts f require f end end
ruby
def require_models model_dir = File.join(File.dirname(__FILE__), %w{ model }) unless Dir.exist? model_dir raise "model directory '#{model_dir}' not exists" end Dir[File.join(model_dir, '*.rb')].each do |f| # puts f require f end end
[ "def", "require_models", "model_dir", "=", "File", ".", "join", "(", "File", ".", "dirname", "(", "__FILE__", ")", ",", "%w{", "model", "}", ")", "unless", "Dir", ".", "exist?", "model_dir", "raise", "\"model directory '#{model_dir}' not exists\"", "end", "Dir", "[", "File", ".", "join", "(", "model_dir", ",", "'*.rb'", ")", "]", ".", "each", "do", "|", "f", "|", "# puts f", "require", "f", "end", "end" ]
model must be loaded after the connection is established
[ "model", "must", "be", "loaded", "after", "the", "connection", "is", "established" ]
b36bc07562f6be4a7092b33b9153f807033ad670
https://github.com/26fe/dircat/blob/b36bc07562f6be4a7092b33b9153f807033ad670/lib/dircat/cat_on_sqlite/cat_on_sqlite.rb#L164-L173
8,724
samvera-deprecated/solrizer-fedora
lib/solrizer/fedora/solrizer.rb
Solrizer::Fedora.Solrizer.solrize_objects
def solrize_objects(opts={}) # retrieve a list of all the pids in the fedora repository num_docs = 1000000 # modify this number to guarantee that all the objects are retrieved from the repository puts "WARNING: You have turned off indexing of Full Text content. Be sure to re-run indexer with @@index_full_text set to true in main.rb" if index_full_text == false if @@index_list == false solrize_from_fedora_search(opts) else solrize_from_csv end end
ruby
def solrize_objects(opts={}) # retrieve a list of all the pids in the fedora repository num_docs = 1000000 # modify this number to guarantee that all the objects are retrieved from the repository puts "WARNING: You have turned off indexing of Full Text content. Be sure to re-run indexer with @@index_full_text set to true in main.rb" if index_full_text == false if @@index_list == false solrize_from_fedora_search(opts) else solrize_from_csv end end
[ "def", "solrize_objects", "(", "opts", "=", "{", "}", ")", "# retrieve a list of all the pids in the fedora repository", "num_docs", "=", "1000000", "# modify this number to guarantee that all the objects are retrieved from the repository", "puts", "\"WARNING: You have turned off indexing of Full Text content. Be sure to re-run indexer with @@index_full_text set to true in main.rb\"", "if", "index_full_text", "==", "false", "if", "@@index_list", "==", "false", "solrize_from_fedora_search", "(", "opts", ")", "else", "solrize_from_csv", "end", "end" ]
Retrieve a comprehensive list of all the unique identifiers in Fedora and solrize each object's full-text and facets into the search index @example Suppress errors using :suppress_errors option solrizer.solrize_objects( :suppress_errors=>true )
[ "Retrieve", "a", "comprehensive", "list", "of", "all", "the", "unique", "identifiers", "in", "Fedora", "and", "solrize", "each", "object", "s", "full", "-", "text", "and", "facets", "into", "the", "search", "index" ]
277fab50a93a761fbccd07e2cfa01b22736d5cff
https://github.com/samvera-deprecated/solrizer-fedora/blob/277fab50a93a761fbccd07e2cfa01b22736d5cff/lib/solrizer/fedora/solrizer.rb#L89-L99
8,725
mastermindg/farmstead
lib/farmstead/project.rb
Farmstead.Project.generate_files
def generate_files ip = local_ip version = Farmstead::VERSION scaffold_path = "#{File.dirname __FILE__}/scaffold" scaffold = Dir.glob("#{scaffold_path}/**/*.erb", File::FNM_DOTMATCH) scaffold.each do |file| basename = File.basename(file) folderstruct = file.match("#{scaffold_path}/(.*)")[1] if basename != folderstruct foldername = File.dirname(folderstruct) create_recursive("#{@name}/#{foldername}") end projectpath = "#{@name}/#{folderstruct}".chomp(".erb") template = File.read(file) results = ERB.new(template).result(binding) copy_to_directory(results, projectpath) end end
ruby
def generate_files ip = local_ip version = Farmstead::VERSION scaffold_path = "#{File.dirname __FILE__}/scaffold" scaffold = Dir.glob("#{scaffold_path}/**/*.erb", File::FNM_DOTMATCH) scaffold.each do |file| basename = File.basename(file) folderstruct = file.match("#{scaffold_path}/(.*)")[1] if basename != folderstruct foldername = File.dirname(folderstruct) create_recursive("#{@name}/#{foldername}") end projectpath = "#{@name}/#{folderstruct}".chomp(".erb") template = File.read(file) results = ERB.new(template).result(binding) copy_to_directory(results, projectpath) end end
[ "def", "generate_files", "ip", "=", "local_ip", "version", "=", "Farmstead", "::", "VERSION", "scaffold_path", "=", "\"#{File.dirname __FILE__}/scaffold\"", "scaffold", "=", "Dir", ".", "glob", "(", "\"#{scaffold_path}/**/*.erb\"", ",", "File", "::", "FNM_DOTMATCH", ")", "scaffold", ".", "each", "do", "|", "file", "|", "basename", "=", "File", ".", "basename", "(", "file", ")", "folderstruct", "=", "file", ".", "match", "(", "\"#{scaffold_path}/(.*)\"", ")", "[", "1", "]", "if", "basename", "!=", "folderstruct", "foldername", "=", "File", ".", "dirname", "(", "folderstruct", ")", "create_recursive", "(", "\"#{@name}/#{foldername}\"", ")", "end", "projectpath", "=", "\"#{@name}/#{folderstruct}\"", ".", "chomp", "(", "\".erb\"", ")", "template", "=", "File", ".", "read", "(", "file", ")", "results", "=", "ERB", ".", "new", "(", "template", ")", ".", "result", "(", "binding", ")", "copy_to_directory", "(", "results", ",", "projectpath", ")", "end", "end" ]
Generate from templates in scaffold
[ "Generate", "from", "templates", "in", "scaffold" ]
32ef99b902304a69c110b3c7727155c38dc8d278
https://github.com/mastermindg/farmstead/blob/32ef99b902304a69c110b3c7727155c38dc8d278/lib/farmstead/project.rb#L59-L76
8,726
erpe/acts_as_referred
lib/acts_as_referred/class_methods.rb
ActsAsReferred.ClassMethods.acts_as_referred
def acts_as_referred(options = {}) has_one :referee, as: :referable, dependent: :destroy, class_name: 'Referee' after_create :create_referrer include ActsAsReferred::InstanceMethods end
ruby
def acts_as_referred(options = {}) has_one :referee, as: :referable, dependent: :destroy, class_name: 'Referee' after_create :create_referrer include ActsAsReferred::InstanceMethods end
[ "def", "acts_as_referred", "(", "options", "=", "{", "}", ")", "has_one", ":referee", ",", "as", ":", ":referable", ",", "dependent", ":", ":destroy", ",", "class_name", ":", "'Referee'", "after_create", ":create_referrer", "include", "ActsAsReferred", "::", "InstanceMethods", "end" ]
Hook to serve behavior to ActiveRecord-Descendants
[ "Hook", "to", "serve", "behavior", "to", "ActiveRecord", "-", "Descendants" ]
d1ffb3208e6e358c9888cec71c7bd76d30a0fdd3
https://github.com/erpe/acts_as_referred/blob/d1ffb3208e6e358c9888cec71c7bd76d30a0fdd3/lib/acts_as_referred/class_methods.rb#L5-L11
8,727
ltello/drsi
lib/drsi/dci/role.rb
DCI.Role.add_role_reader_for!
def add_role_reader_for!(rolekey) return if private_method_defined?(rolekey) define_method(rolekey) {__context.send(rolekey)} private rolekey end
ruby
def add_role_reader_for!(rolekey) return if private_method_defined?(rolekey) define_method(rolekey) {__context.send(rolekey)} private rolekey end
[ "def", "add_role_reader_for!", "(", "rolekey", ")", "return", "if", "private_method_defined?", "(", "rolekey", ")", "define_method", "(", "rolekey", ")", "{", "__context", ".", "send", "(", "rolekey", ")", "}", "private", "rolekey", "end" ]
Defines a new private reader instance method for a context mate role, delegating it to the context object.
[ "Defines", "a", "new", "private", "reader", "instance", "method", "for", "a", "context", "mate", "role", "delegating", "it", "to", "the", "context", "object", "." ]
f584ee2c2f6438e341474b6922b568f43b3e1f25
https://github.com/ltello/drsi/blob/f584ee2c2f6438e341474b6922b568f43b3e1f25/lib/drsi/dci/role.rb#L11-L15
8,728
gotqn/railslider
lib/railslider/image.rb
Railslider.Image.render
def render @result_html = '' @result_html += "<div class=\"rs-container #{self.class.name}\" id=\"#{@id}\">" @result_html += render_controls.gsub("<option value=\"rs-#{@effect}\">", "<option value=\"rs-#{@effect}\" selected=\"selected\">") @result_html += "<div class=\"rs-wrapper\">" @result_html += "<div class=\"rs-shadow\"></div>" @result_html += '<div class="rs-images">' @images_urls.each do |url| @result_html += "<img src=\"#{url}\"/>" end @result_html += '</div>' @result_html += '<div class="rs-cover">' @result_html += '<a class="rs-animation-command rs-pause" href="javascript:void(0)">Play/Pause</a>' @result_html += "<img src=\"#{@images_urls.first}\"/>" @result_html += '</div>' @result_html += '<div class="rs-transition">' @result_html += render_flips @result_html += render_multi_flips @result_html += render_cubes @result_html += render_unfolds @result_html += '</div>' @result_html += '</div>' @result_html += render_bullets @result_html += '</div>' @result_html.html_safe end
ruby
def render @result_html = '' @result_html += "<div class=\"rs-container #{self.class.name}\" id=\"#{@id}\">" @result_html += render_controls.gsub("<option value=\"rs-#{@effect}\">", "<option value=\"rs-#{@effect}\" selected=\"selected\">") @result_html += "<div class=\"rs-wrapper\">" @result_html += "<div class=\"rs-shadow\"></div>" @result_html += '<div class="rs-images">' @images_urls.each do |url| @result_html += "<img src=\"#{url}\"/>" end @result_html += '</div>' @result_html += '<div class="rs-cover">' @result_html += '<a class="rs-animation-command rs-pause" href="javascript:void(0)">Play/Pause</a>' @result_html += "<img src=\"#{@images_urls.first}\"/>" @result_html += '</div>' @result_html += '<div class="rs-transition">' @result_html += render_flips @result_html += render_multi_flips @result_html += render_cubes @result_html += render_unfolds @result_html += '</div>' @result_html += '</div>' @result_html += render_bullets @result_html += '</div>' @result_html.html_safe end
[ "def", "render", "@result_html", "=", "''", "@result_html", "+=", "\"<div class=\\\"rs-container #{self.class.name}\\\" id=\\\"#{@id}\\\">\"", "@result_html", "+=", "render_controls", ".", "gsub", "(", "\"<option value=\\\"rs-#{@effect}\\\">\"", ",", "\"<option value=\\\"rs-#{@effect}\\\" selected=\\\"selected\\\">\"", ")", "@result_html", "+=", "\"<div class=\\\"rs-wrapper\\\">\"", "@result_html", "+=", "\"<div class=\\\"rs-shadow\\\"></div>\"", "@result_html", "+=", "'<div class=\"rs-images\">'", "@images_urls", ".", "each", "do", "|", "url", "|", "@result_html", "+=", "\"<img src=\\\"#{url}\\\"/>\"", "end", "@result_html", "+=", "'</div>'", "@result_html", "+=", "'<div class=\"rs-cover\">'", "@result_html", "+=", "'<a class=\"rs-animation-command rs-pause\" href=\"javascript:void(0)\">Play/Pause</a>'", "@result_html", "+=", "\"<img src=\\\"#{@images_urls.first}\\\"/>\"", "@result_html", "+=", "'</div>'", "@result_html", "+=", "'<div class=\"rs-transition\">'", "@result_html", "+=", "render_flips", "@result_html", "+=", "render_multi_flips", "@result_html", "+=", "render_cubes", "@result_html", "+=", "render_unfolds", "@result_html", "+=", "'</div>'", "@result_html", "+=", "'</div>'", "@result_html", "+=", "render_bullets", "@result_html", "+=", "'</div>'", "@result_html", ".", "html_safe", "end" ]
rendering images with rails slider effects
[ "rendering", "images", "with", "rails", "slider", "effects" ]
86084f5ce60a217a4ee7371511ee7987fb4af171
https://github.com/gotqn/railslider/blob/86084f5ce60a217a4ee7371511ee7987fb4af171/lib/railslider/image.rb#L44-L71
8,729
starpeak/gricer
lib/gricer/config.rb
Gricer.Config.admin_menu
def admin_menu @admin_menu ||= [ ['overview', :dashboard, {controller: 'gricer/dashboard', action: 'overview'}], ['visitors', :menu, [ ['entry_pages', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'entry_path'}], ['referers', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'referer_host'}], ['search_engines', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'search_engine'}], ['search_terms', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'search_query'}], ['countries', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'country'}], ['domains', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'domain'}], ['locales', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'requested_locale_major'}] ] ], ['pages', :menu, [ ['views', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'path'}], ['hosts', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'host'}], ['methods', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'method'}], ['protocols', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'protocol'}], ] ], ['browsers', :menu, [ ['browsers', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'agent.name'}], ['operating_systems', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'agent.os'}], ['engines', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'agent.engine_name'}], ['javascript', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'javascript'}], ['java', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'java'}], ['silverlight', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'silverlight_major_version'}], ['flash', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'flash_major_version'}], ['screen_sizes', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'screen_size'}], ['color_depths', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'screen_depth'}] ] ] ] end
ruby
def admin_menu @admin_menu ||= [ ['overview', :dashboard, {controller: 'gricer/dashboard', action: 'overview'}], ['visitors', :menu, [ ['entry_pages', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'entry_path'}], ['referers', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'referer_host'}], ['search_engines', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'search_engine'}], ['search_terms', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'search_query'}], ['countries', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'country'}], ['domains', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'domain'}], ['locales', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'requested_locale_major'}] ] ], ['pages', :menu, [ ['views', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'path'}], ['hosts', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'host'}], ['methods', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'method'}], ['protocols', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'protocol'}], ] ], ['browsers', :menu, [ ['browsers', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'agent.name'}], ['operating_systems', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'agent.os'}], ['engines', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'agent.engine_name'}], ['javascript', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'javascript'}], ['java', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'java'}], ['silverlight', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'silverlight_major_version'}], ['flash', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'flash_major_version'}], ['screen_sizes', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'screen_size'}], ['color_depths', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'screen_depth'}] ] ] ] end
[ "def", "admin_menu", "@admin_menu", "||=", "[", "[", "'overview'", ",", ":dashboard", ",", "{", "controller", ":", "'gricer/dashboard'", ",", "action", ":", "'overview'", "}", "]", ",", "[", "'visitors'", ",", ":menu", ",", "[", "[", "'entry_pages'", ",", ":spread", ",", "{", "controller", ":", "'gricer/requests'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'entry_path'", "}", "]", ",", "[", "'referers'", ",", ":spread", ",", "{", "controller", ":", "'gricer/requests'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'referer_host'", "}", "]", ",", "[", "'search_engines'", ",", ":spread", ",", "{", "controller", ":", "'gricer/requests'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'search_engine'", "}", "]", ",", "[", "'search_terms'", ",", ":spread", ",", "{", "controller", ":", "'gricer/requests'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'search_query'", "}", "]", ",", "[", "'countries'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'country'", "}", "]", ",", "[", "'domains'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'domain'", "}", "]", ",", "[", "'locales'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'requested_locale_major'", "}", "]", "]", "]", ",", "[", "'pages'", ",", ":menu", ",", "[", "[", "'views'", ",", ":spread", ",", "{", "controller", ":", "'gricer/requests'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'path'", "}", "]", ",", "[", "'hosts'", ",", ":spread", ",", "{", "controller", ":", "'gricer/requests'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'host'", "}", "]", ",", "[", "'methods'", ",", ":spread", ",", "{", "controller", ":", "'gricer/requests'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'method'", "}", "]", ",", "[", "'protocols'", ",", ":spread", ",", "{", "controller", ":", "'gricer/requests'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'protocol'", "}", "]", ",", "]", "]", ",", "[", "'browsers'", ",", ":menu", ",", "[", "[", "'browsers'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'agent.name'", "}", "]", ",", "[", "'operating_systems'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'agent.os'", "}", "]", ",", "[", "'engines'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'agent.engine_name'", "}", "]", ",", "[", "'javascript'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'javascript'", "}", "]", ",", "[", "'java'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'java'", "}", "]", ",", "[", "'silverlight'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'silverlight_major_version'", "}", "]", ",", "[", "'flash'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'flash_major_version'", "}", "]", ",", "[", "'screen_sizes'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'screen_size'", "}", "]", ",", "[", "'color_depths'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'screen_depth'", "}", "]", "]", "]", "]", "end" ]
Configure the structure of Gricer's admin menu Default value see source @return [Array]
[ "Configure", "the", "structure", "of", "Gricer", "s", "admin", "menu" ]
46bb77bd4fc7074ce294d0310ad459fef068f507
https://github.com/starpeak/gricer/blob/46bb77bd4fc7074ce294d0310ad459fef068f507/lib/gricer/config.rb#L61-L91
8,730
johnwunder/stix_schema_spy
lib/stix_schema_spy/models/has_children.rb
StixSchemaSpy.HasChildren.process_field
def process_field(child) if ['complexContent', 'simpleContent', 'sequence', 'group', 'choice', 'extension', 'restriction'].include?(child.name) child.elements.each {|grandchild| process_field(grandchild)} elsif child.name == 'element' element = Element.new(child, self.schema, self) @elements[element.name] = element elsif child.name == 'attribute' attribute = Attribute.new(child, self.schema, self) @attributes[attribute.name] = attribute elsif child.name == 'complexType' type = ComplexType.build(child, self.schema) @types[type.name] = type elsif child.name == 'simpleType' type = SimpleType.build(child, self.schema) @types[type.name] = type elsif child.name == 'anyAttribute' @special_fields << SpecialField.new("##anyAttribute") elsif child.name == 'anyElement' @special_fields << SpecialField.new("##anyElement") elsif child.name == 'attributeGroup' # The only special case here...essentially we'll' transparently roll attribute groups into parent nodes, # while at the schema level global attribute groups get created as a type if self.kind_of?(Schema) type = ComplexType.build(child, self.schema) @types[type.name] = type else Type.find(child.attributes['ref'].value, nil, stix_version).attributes.each {|attrib| @attributes[attrib.name] = attrib} end else $logger.debug "Skipping: #{child.name}" if defined?($logger) end end
ruby
def process_field(child) if ['complexContent', 'simpleContent', 'sequence', 'group', 'choice', 'extension', 'restriction'].include?(child.name) child.elements.each {|grandchild| process_field(grandchild)} elsif child.name == 'element' element = Element.new(child, self.schema, self) @elements[element.name] = element elsif child.name == 'attribute' attribute = Attribute.new(child, self.schema, self) @attributes[attribute.name] = attribute elsif child.name == 'complexType' type = ComplexType.build(child, self.schema) @types[type.name] = type elsif child.name == 'simpleType' type = SimpleType.build(child, self.schema) @types[type.name] = type elsif child.name == 'anyAttribute' @special_fields << SpecialField.new("##anyAttribute") elsif child.name == 'anyElement' @special_fields << SpecialField.new("##anyElement") elsif child.name == 'attributeGroup' # The only special case here...essentially we'll' transparently roll attribute groups into parent nodes, # while at the schema level global attribute groups get created as a type if self.kind_of?(Schema) type = ComplexType.build(child, self.schema) @types[type.name] = type else Type.find(child.attributes['ref'].value, nil, stix_version).attributes.each {|attrib| @attributes[attrib.name] = attrib} end else $logger.debug "Skipping: #{child.name}" if defined?($logger) end end
[ "def", "process_field", "(", "child", ")", "if", "[", "'complexContent'", ",", "'simpleContent'", ",", "'sequence'", ",", "'group'", ",", "'choice'", ",", "'extension'", ",", "'restriction'", "]", ".", "include?", "(", "child", ".", "name", ")", "child", ".", "elements", ".", "each", "{", "|", "grandchild", "|", "process_field", "(", "grandchild", ")", "}", "elsif", "child", ".", "name", "==", "'element'", "element", "=", "Element", ".", "new", "(", "child", ",", "self", ".", "schema", ",", "self", ")", "@elements", "[", "element", ".", "name", "]", "=", "element", "elsif", "child", ".", "name", "==", "'attribute'", "attribute", "=", "Attribute", ".", "new", "(", "child", ",", "self", ".", "schema", ",", "self", ")", "@attributes", "[", "attribute", ".", "name", "]", "=", "attribute", "elsif", "child", ".", "name", "==", "'complexType'", "type", "=", "ComplexType", ".", "build", "(", "child", ",", "self", ".", "schema", ")", "@types", "[", "type", ".", "name", "]", "=", "type", "elsif", "child", ".", "name", "==", "'simpleType'", "type", "=", "SimpleType", ".", "build", "(", "child", ",", "self", ".", "schema", ")", "@types", "[", "type", ".", "name", "]", "=", "type", "elsif", "child", ".", "name", "==", "'anyAttribute'", "@special_fields", "<<", "SpecialField", ".", "new", "(", "\"##anyAttribute\"", ")", "elsif", "child", ".", "name", "==", "'anyElement'", "@special_fields", "<<", "SpecialField", ".", "new", "(", "\"##anyElement\"", ")", "elsif", "child", ".", "name", "==", "'attributeGroup'", "# The only special case here...essentially we'll' transparently roll attribute groups into parent nodes,", "# while at the schema level global attribute groups get created as a type", "if", "self", ".", "kind_of?", "(", "Schema", ")", "type", "=", "ComplexType", ".", "build", "(", "child", ",", "self", ".", "schema", ")", "@types", "[", "type", ".", "name", "]", "=", "type", "else", "Type", ".", "find", "(", "child", ".", "attributes", "[", "'ref'", "]", ".", "value", ",", "nil", ",", "stix_version", ")", ".", "attributes", ".", "each", "{", "|", "attrib", "|", "@attributes", "[", "attrib", ".", "name", "]", "=", "attrib", "}", "end", "else", "$logger", ".", "debug", "\"Skipping: #{child.name}\"", "if", "defined?", "(", "$logger", ")", "end", "end" ]
Runs through the list of fields under this type and creates the appropriate objects
[ "Runs", "through", "the", "list", "of", "fields", "under", "this", "type", "and", "creates", "the", "appropriate", "objects" ]
2d551c6854d749eb330340e69f73baee1c4b52d3
https://github.com/johnwunder/stix_schema_spy/blob/2d551c6854d749eb330340e69f73baee1c4b52d3/lib/stix_schema_spy/models/has_children.rb#L50-L81
8,731
0000marcell/simple_commander
lib/simple_commander/runner.rb
SimpleCommander.Runner.helper_exist?
def helper_exist?(helper) Object.const_defined?(helper) && Object.const_get(helper).instance_of?(::Module) end
ruby
def helper_exist?(helper) Object.const_defined?(helper) && Object.const_get(helper).instance_of?(::Module) end
[ "def", "helper_exist?", "(", "helper", ")", "Object", ".", "const_defined?", "(", "helper", ")", "&&", "Object", ".", "const_get", "(", "helper", ")", ".", "instance_of?", "(", "::", "Module", ")", "end" ]
check if the helper exist
[ "check", "if", "the", "helper", "exist" ]
337c2e0d9926c643ce131b1a1ebd3740241e4424
https://github.com/0000marcell/simple_commander/blob/337c2e0d9926c643ce131b1a1ebd3740241e4424/lib/simple_commander/runner.rb#L58-L61
8,732
ktonon/code_node
spec/fixtures/activerecord/src/active_record/explain.rb
ActiveRecord.Explain.logging_query_plan
def logging_query_plan # :nodoc: return yield unless logger threshold = auto_explain_threshold_in_seconds current = Thread.current if threshold && current[:available_queries_for_explain].nil? begin queries = current[:available_queries_for_explain] = [] start = Time.now result = yield logger.warn(exec_explain(queries)) if Time.now - start > threshold result ensure current[:available_queries_for_explain] = nil end else yield end end
ruby
def logging_query_plan # :nodoc: return yield unless logger threshold = auto_explain_threshold_in_seconds current = Thread.current if threshold && current[:available_queries_for_explain].nil? begin queries = current[:available_queries_for_explain] = [] start = Time.now result = yield logger.warn(exec_explain(queries)) if Time.now - start > threshold result ensure current[:available_queries_for_explain] = nil end else yield end end
[ "def", "logging_query_plan", "# :nodoc:", "return", "yield", "unless", "logger", "threshold", "=", "auto_explain_threshold_in_seconds", "current", "=", "Thread", ".", "current", "if", "threshold", "&&", "current", "[", ":available_queries_for_explain", "]", ".", "nil?", "begin", "queries", "=", "current", "[", ":available_queries_for_explain", "]", "=", "[", "]", "start", "=", "Time", ".", "now", "result", "=", "yield", "logger", ".", "warn", "(", "exec_explain", "(", "queries", ")", ")", "if", "Time", ".", "now", "-", "start", ">", "threshold", "result", "ensure", "current", "[", ":available_queries_for_explain", "]", "=", "nil", "end", "else", "yield", "end", "end" ]
If auto explain is enabled, this method triggers EXPLAIN logging for the queries triggered by the block if it takes more than the threshold as a whole. That is, the threshold is not checked against each individual query, but against the duration of the entire block. This approach is convenient for relations. The available_queries_for_explain thread variable collects the queries to be explained. If the value is nil, it means queries are not being currently collected. A false value indicates collecting is turned off. Otherwise it is an array of queries.
[ "If", "auto", "explain", "is", "enabled", "this", "method", "triggers", "EXPLAIN", "logging", "for", "the", "queries", "triggered", "by", "the", "block", "if", "it", "takes", "more", "than", "the", "threshold", "as", "a", "whole", ".", "That", "is", "the", "threshold", "is", "not", "checked", "against", "each", "individual", "query", "but", "against", "the", "duration", "of", "the", "entire", "block", ".", "This", "approach", "is", "convenient", "for", "relations", "." ]
48d5d1a7442d9cade602be4fb782a1b56c7677f5
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/explain.rb#L24-L42
8,733
ktonon/code_node
spec/fixtures/activerecord/src/active_record/explain.rb
ActiveRecord.Explain.silence_auto_explain
def silence_auto_explain current = Thread.current original, current[:available_queries_for_explain] = current[:available_queries_for_explain], false yield ensure current[:available_queries_for_explain] = original end
ruby
def silence_auto_explain current = Thread.current original, current[:available_queries_for_explain] = current[:available_queries_for_explain], false yield ensure current[:available_queries_for_explain] = original end
[ "def", "silence_auto_explain", "current", "=", "Thread", ".", "current", "original", ",", "current", "[", ":available_queries_for_explain", "]", "=", "current", "[", ":available_queries_for_explain", "]", ",", "false", "yield", "ensure", "current", "[", ":available_queries_for_explain", "]", "=", "original", "end" ]
Silences automatic EXPLAIN logging for the duration of the block. This has high priority, no EXPLAINs will be run even if downwards the threshold is set to 0. As the name of the method suggests this only applies to automatic EXPLAINs, manual calls to +ActiveRecord::Relation#explain+ run.
[ "Silences", "automatic", "EXPLAIN", "logging", "for", "the", "duration", "of", "the", "block", "." ]
48d5d1a7442d9cade602be4fb782a1b56c7677f5
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/explain.rb#L77-L83
8,734
pwnedkeys/openssl-additions
lib/openssl/x509/spki.rb
OpenSSL::X509.SPKI.validate_spki
def validate_spki unless @spki.is_a?(OpenSSL::ASN1::Sequence) raise SPKIError, "SPKI data is not an ASN1 sequence (got a #{@spki.class})" end if @spki.value.length != 2 raise SPKIError, "SPKI top-level sequence must have two elements (length is #{@spki.value.length})" end alg_id, key_data = @spki.value unless alg_id.is_a?(OpenSSL::ASN1::Sequence) raise SPKIError, "SPKI algorithm_identifier must be a sequence (got a #{alg_id.class})" end unless (1..2) === alg_id.value.length raise SPKIError, "SPKI algorithm sequence must have one or two elements (got #{alg_id.value.length} elements)" end unless alg_id.value.first.is_a?(OpenSSL::ASN1::ObjectId) raise SPKIError, "SPKI algorithm identifier does not contain an object ID (got #{alg_id.value.first.class})" end unless key_data.is_a?(OpenSSL::ASN1::BitString) raise SPKIError, "SPKI publicKeyInfo field must be a BitString (got a #{@spki.value.last.class})" end end
ruby
def validate_spki unless @spki.is_a?(OpenSSL::ASN1::Sequence) raise SPKIError, "SPKI data is not an ASN1 sequence (got a #{@spki.class})" end if @spki.value.length != 2 raise SPKIError, "SPKI top-level sequence must have two elements (length is #{@spki.value.length})" end alg_id, key_data = @spki.value unless alg_id.is_a?(OpenSSL::ASN1::Sequence) raise SPKIError, "SPKI algorithm_identifier must be a sequence (got a #{alg_id.class})" end unless (1..2) === alg_id.value.length raise SPKIError, "SPKI algorithm sequence must have one or two elements (got #{alg_id.value.length} elements)" end unless alg_id.value.first.is_a?(OpenSSL::ASN1::ObjectId) raise SPKIError, "SPKI algorithm identifier does not contain an object ID (got #{alg_id.value.first.class})" end unless key_data.is_a?(OpenSSL::ASN1::BitString) raise SPKIError, "SPKI publicKeyInfo field must be a BitString (got a #{@spki.value.last.class})" end end
[ "def", "validate_spki", "unless", "@spki", ".", "is_a?", "(", "OpenSSL", "::", "ASN1", "::", "Sequence", ")", "raise", "SPKIError", ",", "\"SPKI data is not an ASN1 sequence (got a #{@spki.class})\"", "end", "if", "@spki", ".", "value", ".", "length", "!=", "2", "raise", "SPKIError", ",", "\"SPKI top-level sequence must have two elements (length is #{@spki.value.length})\"", "end", "alg_id", ",", "key_data", "=", "@spki", ".", "value", "unless", "alg_id", ".", "is_a?", "(", "OpenSSL", "::", "ASN1", "::", "Sequence", ")", "raise", "SPKIError", ",", "\"SPKI algorithm_identifier must be a sequence (got a #{alg_id.class})\"", "end", "unless", "(", "1", "..", "2", ")", "===", "alg_id", ".", "value", ".", "length", "raise", "SPKIError", ",", "\"SPKI algorithm sequence must have one or two elements (got #{alg_id.value.length} elements)\"", "end", "unless", "alg_id", ".", "value", ".", "first", ".", "is_a?", "(", "OpenSSL", "::", "ASN1", "::", "ObjectId", ")", "raise", "SPKIError", ",", "\"SPKI algorithm identifier does not contain an object ID (got #{alg_id.value.first.class})\"", "end", "unless", "key_data", ".", "is_a?", "(", "OpenSSL", "::", "ASN1", "::", "BitString", ")", "raise", "SPKIError", ",", "\"SPKI publicKeyInfo field must be a BitString (got a #{@spki.value.last.class})\"", "end", "end" ]
Make sure that the SPKI data we were passed is legit.
[ "Make", "sure", "that", "the", "SPKI", "data", "we", "were", "passed", "is", "legit", "." ]
e6d105cf39ff1ae901967644e7d46cb65f416c87
https://github.com/pwnedkeys/openssl-additions/blob/e6d105cf39ff1ae901967644e7d46cb65f416c87/lib/openssl/x509/spki.rb#L140-L172
8,735
celldee/ffi-rxs
lib/ffi-rxs/socket.rb
XS.CommonSocketBehavior.setsockopt
def setsockopt name, value, length = nil if 1 == @option_lookup[name] length = 8 pointer = LibC.malloc length pointer.write_long_long value elsif 0 == @option_lookup[name] length = 4 pointer = LibC.malloc length pointer.write_int value elsif 2 == @option_lookup[name] length ||= value.size # note: not checking errno for failed memory allocations :( pointer = LibC.malloc length pointer.write_string value end rc = LibXS.xs_setsockopt @socket, name, pointer, length LibC.free(pointer) unless pointer.nil? || pointer.null? rc end
ruby
def setsockopt name, value, length = nil if 1 == @option_lookup[name] length = 8 pointer = LibC.malloc length pointer.write_long_long value elsif 0 == @option_lookup[name] length = 4 pointer = LibC.malloc length pointer.write_int value elsif 2 == @option_lookup[name] length ||= value.size # note: not checking errno for failed memory allocations :( pointer = LibC.malloc length pointer.write_string value end rc = LibXS.xs_setsockopt @socket, name, pointer, length LibC.free(pointer) unless pointer.nil? || pointer.null? rc end
[ "def", "setsockopt", "name", ",", "value", ",", "length", "=", "nil", "if", "1", "==", "@option_lookup", "[", "name", "]", "length", "=", "8", "pointer", "=", "LibC", ".", "malloc", "length", "pointer", ".", "write_long_long", "value", "elsif", "0", "==", "@option_lookup", "[", "name", "]", "length", "=", "4", "pointer", "=", "LibC", ".", "malloc", "length", "pointer", ".", "write_int", "value", "elsif", "2", "==", "@option_lookup", "[", "name", "]", "length", "||=", "value", ".", "size", "# note: not checking errno for failed memory allocations :(", "pointer", "=", "LibC", ".", "malloc", "length", "pointer", ".", "write_string", "value", "end", "rc", "=", "LibXS", ".", "xs_setsockopt", "@socket", ",", "name", ",", "pointer", ",", "length", "LibC", ".", "free", "(", "pointer", ")", "unless", "pointer", ".", "nil?", "||", "pointer", ".", "null?", "rc", "end" ]
Allocates a socket of type +type+ for sending and receiving data. To avoid rescuing exceptions, use the factory method #create for all socket creation. By default, this class uses XS::Message for manual memory management. For automatic garbage collection of received messages, it is possible to override the :receiver_class to use XS::ManagedMessage. @example Socket creation sock = Socket.new(Context.new, XS::REQ, :receiver_class => XS::ManagedMessage) Advanced users may want to replace the receiver class with their own custom class. The custom class must conform to the same public API as XS::Message. Creation of a new Socket object can raise an exception. This occurs when the +context_ptr+ is null or when the allocation of the Crossroads socket within the context fails. @example begin socket = Socket.new(context.pointer, XS::REQ) rescue ContextError => e # error handling end @param pointer @param [Constant] type One of @XS::REQ@, @XS::REP@, @XS::PUB@, @XS::SUB@, @XS::PAIR@, @XS::PULL@, @XS::PUSH@, @XS::XREQ@, @XS::REP@, @XS::DEALER@ or @XS::ROUTER@ @param [Hash] options @return [Socket] when successful @return nil when unsuccessful Set the queue options on this socket @param [Constant] name numeric values One of @XS::AFFINITY@, @XS::RATE@, @XS::RECOVERY_IVL@, @XS::LINGER@, @XS::RECONNECT_IVL@, @XS::BACKLOG@, @XS::RECONNECT_IVL_MAX@, @XS::MAXMSGSIZE@, @XS::SNDHWM@, @XS::RCVHWM@, @XS::MULTICAST_HOPS@, @XS::RCVTIMEO@, @XS::SNDTIMEO@, @XS::IPV4ONLY@, @XS::KEEPALIVE@, @XS::SUBSCRIBE@, @XS::UNSUBSCRIBE@, @XS::IDENTITY@, @XS::SNDBUF@, @XS::RCVBUF@ @param [Constant] name string values One of @XS::IDENTITY@, @XS::SUBSCRIBE@ or @XS::UNSUBSCRIBE@ @param value @return 0 when the operation completed successfully @return -1 when this operation fails With a -1 return code, the user must check XS.errno to determine the cause. @example rc = socket.setsockopt(XS::LINGER, 1_000) XS::Util.resultcode_ok?(rc) ? puts("succeeded") : puts("failed")
[ "Allocates", "a", "socket", "of", "type", "+", "type", "+", "for", "sending", "and", "receiving", "data", "." ]
95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e
https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/socket.rb#L128-L150
8,736
celldee/ffi-rxs
lib/ffi-rxs/socket.rb
XS.CommonSocketBehavior.more_parts?
def more_parts? rc = getsockopt XS::RCVMORE, @more_parts_array Util.resultcode_ok?(rc) ? @more_parts_array.at(0) : false end
ruby
def more_parts? rc = getsockopt XS::RCVMORE, @more_parts_array Util.resultcode_ok?(rc) ? @more_parts_array.at(0) : false end
[ "def", "more_parts?", "rc", "=", "getsockopt", "XS", "::", "RCVMORE", ",", "@more_parts_array", "Util", ".", "resultcode_ok?", "(", "rc", ")", "?", "@more_parts_array", ".", "at", "(", "0", ")", ":", "false", "end" ]
Convenience method for checking on additional message parts. Equivalent to calling Socket#getsockopt with XS::RCVMORE. Warning: if the call to #getsockopt fails, this method will return false and swallow the error. @example message_parts = [] message = Message.new rc = socket.recvmsg(message) if XS::Util.resultcode_ok?(rc) message_parts << message while more_parts? message = Message.new rc = socket.recvmsg(message) message_parts.push(message) if resultcode_ok?(rc) end end @return true if more message parts @return false if not
[ "Convenience", "method", "for", "checking", "on", "additional", "message", "parts", "." ]
95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e
https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/socket.rb#L174-L178
8,737
celldee/ffi-rxs
lib/ffi-rxs/socket.rb
XS.CommonSocketBehavior.send_strings
def send_strings parts, flag = 0 return -1 if !parts || parts.empty? flag = NonBlocking if dontwait?(flag) parts[0..-2].each do |part| rc = send_string part, (flag | XS::SNDMORE) return rc unless Util.resultcode_ok?(rc) end send_string parts[-1], flag end
ruby
def send_strings parts, flag = 0 return -1 if !parts || parts.empty? flag = NonBlocking if dontwait?(flag) parts[0..-2].each do |part| rc = send_string part, (flag | XS::SNDMORE) return rc unless Util.resultcode_ok?(rc) end send_string parts[-1], flag end
[ "def", "send_strings", "parts", ",", "flag", "=", "0", "return", "-", "1", "if", "!", "parts", "||", "parts", ".", "empty?", "flag", "=", "NonBlocking", "if", "dontwait?", "(", "flag", ")", "parts", "[", "0", "..", "-", "2", "]", ".", "each", "do", "|", "part", "|", "rc", "=", "send_string", "part", ",", "(", "flag", "|", "XS", "::", "SNDMORE", ")", "return", "rc", "unless", "Util", ".", "resultcode_ok?", "(", "rc", ")", "end", "send_string", "parts", "[", "-", "1", "]", ",", "flag", "end" ]
Send a sequence of strings as a multipart message out of the +parts+ passed in for transmission. Every element of +parts+ should be a String. @param [Array] parts @param flag One of @0 (default)@ and @XS::NonBlocking@ @return 0 when the messages were successfully enqueued @return -1 under two conditions 1. A message could not be enqueued 2. When +flag+ is set with XS::NonBlocking and the socket returned EAGAIN. With a -1 return code, the user must check XS.errno to determine the cause.
[ "Send", "a", "sequence", "of", "strings", "as", "a", "multipart", "message", "out", "of", "the", "+", "parts", "+", "passed", "in", "for", "transmission", ".", "Every", "element", "of", "+", "parts", "+", "should", "be", "a", "String", "." ]
95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e
https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/socket.rb#L280-L290
8,738
celldee/ffi-rxs
lib/ffi-rxs/socket.rb
XS.CommonSocketBehavior.send_and_close
def send_and_close message, flag = 0 rc = sendmsg message, flag message.close rc end
ruby
def send_and_close message, flag = 0 rc = sendmsg message, flag message.close rc end
[ "def", "send_and_close", "message", ",", "flag", "=", "0", "rc", "=", "sendmsg", "message", ",", "flag", "message", ".", "close", "rc", "end" ]
Sends a message. This will automatically close the +message+ for both successful and failed sends. @param message @param flag One of @0 (default)@ and @XS::NonBlocking @return 0 when the message was successfully enqueued @return -1 under two conditions 1. The message could not be enqueued 2. When +flag+ is set with XS::NonBlocking and the socket returned EAGAIN. With a -1 return code, the user must check XS.errno to determine the cause.
[ "Sends", "a", "message", ".", "This", "will", "automatically", "close", "the", "+", "message", "+", "for", "both", "successful", "and", "failed", "sends", "." ]
95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e
https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/socket.rb#L333-L337
8,739
celldee/ffi-rxs
lib/ffi-rxs/socket.rb
XS.CommonSocketBehavior.recv_strings
def recv_strings list, flag = 0 array = [] rc = recvmsgs array, flag if Util.resultcode_ok?(rc) array.each do |message| list << message.copy_out_string message.close end end rc end
ruby
def recv_strings list, flag = 0 array = [] rc = recvmsgs array, flag if Util.resultcode_ok?(rc) array.each do |message| list << message.copy_out_string message.close end end rc end
[ "def", "recv_strings", "list", ",", "flag", "=", "0", "array", "=", "[", "]", "rc", "=", "recvmsgs", "array", ",", "flag", "if", "Util", ".", "resultcode_ok?", "(", "rc", ")", "array", ".", "each", "do", "|", "message", "|", "list", "<<", "message", ".", "copy_out_string", "message", ".", "close", "end", "end", "rc", "end" ]
Receive a multipart message as a list of strings. @param [Array] list @param flag One of @0 (default)@ and @XS::NonBlocking@. Any other flag will be removed. @return 0 if successful @return -1 if unsuccessful
[ "Receive", "a", "multipart", "message", "as", "a", "list", "of", "strings", "." ]
95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e
https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/socket.rb#L406-L418
8,740
celldee/ffi-rxs
lib/ffi-rxs/socket.rb
XS.CommonSocketBehavior.recv_multipart
def recv_multipart list, routing_envelope, flag = 0 parts = [] rc = recvmsgs parts, flag if Util.resultcode_ok?(rc) routing = true parts.each do |part| if routing routing_envelope << part routing = part.size > 0 else list << part end end end rc end
ruby
def recv_multipart list, routing_envelope, flag = 0 parts = [] rc = recvmsgs parts, flag if Util.resultcode_ok?(rc) routing = true parts.each do |part| if routing routing_envelope << part routing = part.size > 0 else list << part end end end rc end
[ "def", "recv_multipart", "list", ",", "routing_envelope", ",", "flag", "=", "0", "parts", "=", "[", "]", "rc", "=", "recvmsgs", "parts", ",", "flag", "if", "Util", ".", "resultcode_ok?", "(", "rc", ")", "routing", "=", "true", "parts", ".", "each", "do", "|", "part", "|", "if", "routing", "routing_envelope", "<<", "part", "routing", "=", "part", ".", "size", ">", "0", "else", "list", "<<", "part", "end", "end", "end", "rc", "end" ]
Should only be used for XREQ, XREP, DEALER and ROUTER type sockets. Takes a +list+ for receiving the message body parts and a +routing_envelope+ for receiving the message parts comprising the 0mq routing information. @param [Array] list @param routing_envelope @param flag One of @0 (default)@ and @XS::NonBlocking@ @return 0 if successful @return -1 if unsuccessful
[ "Should", "only", "be", "used", "for", "XREQ", "XREP", "DEALER", "and", "ROUTER", "type", "sockets", ".", "Takes", "a", "+", "list", "+", "for", "receiving", "the", "message", "body", "parts", "and", "a", "+", "routing_envelope", "+", "for", "receiving", "the", "message", "parts", "comprising", "the", "0mq", "routing", "information", "." ]
95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e
https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/socket.rb#L472-L489
8,741
celldee/ffi-rxs
lib/ffi-rxs/socket.rb
XS.CommonSocketBehavior.sockopt_buffers
def sockopt_buffers option_type if 1 == option_type # int64_t or uint64_t unless @longlong_cache length = FFI::MemoryPointer.new :size_t length.write_int 8 @longlong_cache = [FFI::MemoryPointer.new(:int64), length] end @longlong_cache elsif 0 == option_type # int, Crossroads assumes int is 4-bytes unless @int_cache length = FFI::MemoryPointer.new :size_t length.write_int 4 @int_cache = [FFI::MemoryPointer.new(:int32), length] end @int_cache elsif 2 == option_type length = FFI::MemoryPointer.new :size_t # could be a string of up to 255 bytes length.write_int 255 [FFI::MemoryPointer.new(255), length] else # uh oh, someone passed in an unknown option; use a slop buffer unless @int_cache length = FFI::MemoryPointer.new :size_t length.write_int 4 @int_cache = [FFI::MemoryPointer.new(:int32), length] end @int_cache end end
ruby
def sockopt_buffers option_type if 1 == option_type # int64_t or uint64_t unless @longlong_cache length = FFI::MemoryPointer.new :size_t length.write_int 8 @longlong_cache = [FFI::MemoryPointer.new(:int64), length] end @longlong_cache elsif 0 == option_type # int, Crossroads assumes int is 4-bytes unless @int_cache length = FFI::MemoryPointer.new :size_t length.write_int 4 @int_cache = [FFI::MemoryPointer.new(:int32), length] end @int_cache elsif 2 == option_type length = FFI::MemoryPointer.new :size_t # could be a string of up to 255 bytes length.write_int 255 [FFI::MemoryPointer.new(255), length] else # uh oh, someone passed in an unknown option; use a slop buffer unless @int_cache length = FFI::MemoryPointer.new :size_t length.write_int 4 @int_cache = [FFI::MemoryPointer.new(:int32), length] end @int_cache end end
[ "def", "sockopt_buffers", "option_type", "if", "1", "==", "option_type", "# int64_t or uint64_t", "unless", "@longlong_cache", "length", "=", "FFI", "::", "MemoryPointer", ".", "new", ":size_t", "length", ".", "write_int", "8", "@longlong_cache", "=", "[", "FFI", "::", "MemoryPointer", ".", "new", "(", ":int64", ")", ",", "length", "]", "end", "@longlong_cache", "elsif", "0", "==", "option_type", "# int, Crossroads assumes int is 4-bytes", "unless", "@int_cache", "length", "=", "FFI", "::", "MemoryPointer", ".", "new", ":size_t", "length", ".", "write_int", "4", "@int_cache", "=", "[", "FFI", "::", "MemoryPointer", ".", "new", "(", ":int32", ")", ",", "length", "]", "end", "@int_cache", "elsif", "2", "==", "option_type", "length", "=", "FFI", "::", "MemoryPointer", ".", "new", ":size_t", "# could be a string of up to 255 bytes", "length", ".", "write_int", "255", "[", "FFI", "::", "MemoryPointer", ".", "new", "(", "255", ")", ",", "length", "]", "else", "# uh oh, someone passed in an unknown option; use a slop buffer", "unless", "@int_cache", "length", "=", "FFI", "::", "MemoryPointer", ".", "new", ":size_t", "length", ".", "write_int", "4", "@int_cache", "=", "[", "FFI", "::", "MemoryPointer", ".", "new", "(", ":int32", ")", ",", "length", "]", "end", "@int_cache", "end", "end" ]
Calls to xs_getsockopt require us to pass in some pointers. We can cache and save those buffers for subsequent calls. This is a big perf win for calling RCVMORE which happens quite often. Cannot save the buffer for the IDENTITY. @param option_type @return cached number or string
[ "Calls", "to", "xs_getsockopt", "require", "us", "to", "pass", "in", "some", "pointers", ".", "We", "can", "cache", "and", "save", "those", "buffers", "for", "subsequent", "calls", ".", "This", "is", "a", "big", "perf", "win", "for", "calling", "RCVMORE", "which", "happens", "quite", "often", ".", "Cannot", "save", "the", "buffer", "for", "the", "IDENTITY", "." ]
95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e
https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/socket.rb#L528-L565
8,742
celldee/ffi-rxs
lib/ffi-rxs/socket.rb
XS.Socket.getsockopt
def getsockopt name, array rc = __getsockopt__ name, array if Util.resultcode_ok?(rc) && (RCVMORE == name) # convert to boolean array[0] = 1 == array[0] end rc end
ruby
def getsockopt name, array rc = __getsockopt__ name, array if Util.resultcode_ok?(rc) && (RCVMORE == name) # convert to boolean array[0] = 1 == array[0] end rc end
[ "def", "getsockopt", "name", ",", "array", "rc", "=", "__getsockopt__", "name", ",", "array", "if", "Util", ".", "resultcode_ok?", "(", "rc", ")", "&&", "(", "RCVMORE", "==", "name", ")", "# convert to boolean", "array", "[", "0", "]", "=", "1", "==", "array", "[", "0", "]", "end", "rc", "end" ]
Get the options set on this socket. @param name One of @XS::RCVMORE@, @XS::SNDHWM@, @XS::AFFINITY@, @XS::IDENTITY@, @XS::RATE@, @XS::RECOVERY_IVL@, @XS::SNDBUF@, @XS::RCVBUF@, @XS::FD@, @XS::EVENTS@, @XS::LINGER@, @XS::RECONNECT_IVL@, @XS::BACKLOG@, XS::RECONNECT_IVL_MAX@, @XS::RCVTIMEO@, @XS::SNDTIMEO@, @XS::IPV4ONLY@, @XS::TYPE@, @XS::RCVHWM@, @XS::MAXMSGSIZE@, @XS::MULTICAST_HOPS@, @XS::KEEPALIVE@ @param array should be an empty array; a result of the proper type (numeric, string, boolean) will be inserted into the first position. @return 0 when the operation completed successfully @return -1 when this operation failed With a -1 return code, the user must check XS.errno to determine the cause. @example Retrieve send high water mark array = [] rc = socket.getsockopt(XS::SNDHWM, array) sndhwm = array.first if XS::Util.resultcode_ok?(rc)
[ "Get", "the", "options", "set", "on", "this", "socket", "." ]
95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e
https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/socket.rb#L657-L666
8,743
kristianmandrup/roles_generic
lib/roles_generic/generic/user/implementation.rb
Roles::Generic::User.Implementation.role=
def role= role raise ArgumentError, '#add_role takes a single role String or Symbol as the argument' if !role || role.kind_of?(Array) self.roles = role end
ruby
def role= role raise ArgumentError, '#add_role takes a single role String or Symbol as the argument' if !role || role.kind_of?(Array) self.roles = role end
[ "def", "role", "=", "role", "raise", "ArgumentError", ",", "'#add_role takes a single role String or Symbol as the argument'", "if", "!", "role", "||", "role", ".", "kind_of?", "(", "Array", ")", "self", ".", "roles", "=", "role", "end" ]
set a single role
[ "set", "a", "single", "role" ]
94588ac58bcca1f44ace5695d1984da1bd98fe1a
https://github.com/kristianmandrup/roles_generic/blob/94588ac58bcca1f44ace5695d1984da1bd98fe1a/lib/roles_generic/generic/user/implementation.rb#L10-L13
8,744
kristianmandrup/roles_generic
lib/roles_generic/generic/user/implementation.rb
Roles::Generic::User.Implementation.add_role
def add_role role raise ArgumentError, '#add_role takes a single role String or Symbol as the argument' if !role || role.kind_of?(Array) add_roles role end
ruby
def add_role role raise ArgumentError, '#add_role takes a single role String or Symbol as the argument' if !role || role.kind_of?(Array) add_roles role end
[ "def", "add_role", "role", "raise", "ArgumentError", ",", "'#add_role takes a single role String or Symbol as the argument'", "if", "!", "role", "||", "role", ".", "kind_of?", "(", "Array", ")", "add_roles", "role", "end" ]
add a single role
[ "add", "a", "single", "role" ]
94588ac58bcca1f44ace5695d1984da1bd98fe1a
https://github.com/kristianmandrup/roles_generic/blob/94588ac58bcca1f44ace5695d1984da1bd98fe1a/lib/roles_generic/generic/user/implementation.rb#L16-L19
8,745
kristianmandrup/roles_generic
lib/roles_generic/generic/user/implementation.rb
Roles::Generic::User.Implementation.remove_role
def remove_role role raise ArgumentError, '#remove_role takes a single role String or Symbol as the argument' if !role || role.kind_of?(Array) remove_roles role end
ruby
def remove_role role raise ArgumentError, '#remove_role takes a single role String or Symbol as the argument' if !role || role.kind_of?(Array) remove_roles role end
[ "def", "remove_role", "role", "raise", "ArgumentError", ",", "'#remove_role takes a single role String or Symbol as the argument'", "if", "!", "role", "||", "role", ".", "kind_of?", "(", "Array", ")", "remove_roles", "role", "end" ]
remove a single role
[ "remove", "a", "single", "role" ]
94588ac58bcca1f44ace5695d1984da1bd98fe1a
https://github.com/kristianmandrup/roles_generic/blob/94588ac58bcca1f44ace5695d1984da1bd98fe1a/lib/roles_generic/generic/user/implementation.rb#L22-L25
8,746
zohararad/handlebarer
lib/handlebarer/compiler.rb
Handlebarer.Compiler.v8_context
def v8_context V8::C::Locker() do context = V8::Context.new context.eval(source) yield context end end
ruby
def v8_context V8::C::Locker() do context = V8::Context.new context.eval(source) yield context end end
[ "def", "v8_context", "V8", "::", "C", "::", "Locker", "(", ")", "do", "context", "=", "V8", "::", "Context", ".", "new", "context", ".", "eval", "(", "source", ")", "yield", "context", "end", "end" ]
V8 context with Handlerbars code compiled @yield [context] V8::Context compiled Handlerbars source code in V8 context
[ "V8", "context", "with", "Handlerbars", "code", "compiled" ]
f5b2db17cb72fd2874ebe8268cf6f2ae17e74002
https://github.com/zohararad/handlebarer/blob/f5b2db17cb72fd2874ebe8268cf6f2ae17e74002/lib/handlebarer/compiler.rb#L14-L20
8,747
zohararad/handlebarer
lib/handlebarer/compiler.rb
Handlebarer.Compiler.compile
def compile(template) v8_context do |context| template = template.read if template.respond_to?(:read) compiled_handlebars = context.eval("Handlebars.precompile(#{template.to_json})") "Handlebars.template(#{compiled_handlebars});" end end
ruby
def compile(template) v8_context do |context| template = template.read if template.respond_to?(:read) compiled_handlebars = context.eval("Handlebars.precompile(#{template.to_json})") "Handlebars.template(#{compiled_handlebars});" end end
[ "def", "compile", "(", "template", ")", "v8_context", "do", "|", "context", "|", "template", "=", "template", ".", "read", "if", "template", ".", "respond_to?", "(", ":read", ")", "compiled_handlebars", "=", "context", ".", "eval", "(", "\"Handlebars.precompile(#{template.to_json})\"", ")", "\"Handlebars.template(#{compiled_handlebars});\"", "end", "end" ]
Compile a Handlerbars template for client-side use with JST @param [String, File] template Handlerbars template file or text to compile @return [String] Handlerbars template compiled into Javascript and wrapped inside an anonymous function for JST
[ "Compile", "a", "Handlerbars", "template", "for", "client", "-", "side", "use", "with", "JST" ]
f5b2db17cb72fd2874ebe8268cf6f2ae17e74002
https://github.com/zohararad/handlebarer/blob/f5b2db17cb72fd2874ebe8268cf6f2ae17e74002/lib/handlebarer/compiler.rb#L33-L39
8,748
zohararad/handlebarer
lib/handlebarer/compiler.rb
Handlebarer.Compiler.render
def render(template, vars = {}) v8_context do |context| unless Handlebarer.configuration.nil? helpers = handlebars_helpers context.eval(helpers.join("\n")) if helpers.any? end context.eval("var fn = Handlebars.compile(#{template.to_json})") context.eval("fn(#{vars.to_hbs.to_json})") end end
ruby
def render(template, vars = {}) v8_context do |context| unless Handlebarer.configuration.nil? helpers = handlebars_helpers context.eval(helpers.join("\n")) if helpers.any? end context.eval("var fn = Handlebars.compile(#{template.to_json})") context.eval("fn(#{vars.to_hbs.to_json})") end end
[ "def", "render", "(", "template", ",", "vars", "=", "{", "}", ")", "v8_context", "do", "|", "context", "|", "unless", "Handlebarer", ".", "configuration", ".", "nil?", "helpers", "=", "handlebars_helpers", "context", ".", "eval", "(", "helpers", ".", "join", "(", "\"\\n\"", ")", ")", "if", "helpers", ".", "any?", "end", "context", ".", "eval", "(", "\"var fn = Handlebars.compile(#{template.to_json})\"", ")", "context", ".", "eval", "(", "\"fn(#{vars.to_hbs.to_json})\"", ")", "end", "end" ]
Compile and evaluate a Handlerbars template for server-side rendering @param [String] template Handlerbars template text to render @param [Hash] vars controller instance variables passed to the template @return [String] HTML output of compiled Handlerbars template
[ "Compile", "and", "evaluate", "a", "Handlerbars", "template", "for", "server", "-", "side", "rendering" ]
f5b2db17cb72fd2874ebe8268cf6f2ae17e74002
https://github.com/zohararad/handlebarer/blob/f5b2db17cb72fd2874ebe8268cf6f2ae17e74002/lib/handlebarer/compiler.rb#L45-L54
8,749
sue445/sengiri_yaml
lib/sengiri_yaml/writer.rb
SengiriYaml.Writer.divide
def divide(src_file, dst_dir) FileUtils.mkdir_p(dst_dir) unless File.exist?(dst_dir) src_content = YAML.load_file(src_file) filenames = [] case src_content when Hash src_content.each do |key, value| filename = "#{dst_dir}/#{key}.yml" File.open(filename, "wb") do |f| f.write({key => value}.to_yaml) end filenames << filename end when Array src_content.each_with_index do |element, index| filename = "#{dst_dir}/#{index}.yml" File.open(filename, "wb") do |f| f.write([element].to_yaml) end filenames << filename end else raise "Unknown type" end filenames end
ruby
def divide(src_file, dst_dir) FileUtils.mkdir_p(dst_dir) unless File.exist?(dst_dir) src_content = YAML.load_file(src_file) filenames = [] case src_content when Hash src_content.each do |key, value| filename = "#{dst_dir}/#{key}.yml" File.open(filename, "wb") do |f| f.write({key => value}.to_yaml) end filenames << filename end when Array src_content.each_with_index do |element, index| filename = "#{dst_dir}/#{index}.yml" File.open(filename, "wb") do |f| f.write([element].to_yaml) end filenames << filename end else raise "Unknown type" end filenames end
[ "def", "divide", "(", "src_file", ",", "dst_dir", ")", "FileUtils", ".", "mkdir_p", "(", "dst_dir", ")", "unless", "File", ".", "exist?", "(", "dst_dir", ")", "src_content", "=", "YAML", ".", "load_file", "(", "src_file", ")", "filenames", "=", "[", "]", "case", "src_content", "when", "Hash", "src_content", ".", "each", "do", "|", "key", ",", "value", "|", "filename", "=", "\"#{dst_dir}/#{key}.yml\"", "File", ".", "open", "(", "filename", ",", "\"wb\"", ")", "do", "|", "f", "|", "f", ".", "write", "(", "{", "key", "=>", "value", "}", ".", "to_yaml", ")", "end", "filenames", "<<", "filename", "end", "when", "Array", "src_content", ".", "each_with_index", "do", "|", "element", ",", "index", "|", "filename", "=", "\"#{dst_dir}/#{index}.yml\"", "File", ".", "open", "(", "filename", ",", "\"wb\"", ")", "do", "|", "f", "|", "f", ".", "write", "(", "[", "element", "]", ".", "to_yaml", ")", "end", "filenames", "<<", "filename", "end", "else", "raise", "\"Unknown type\"", "end", "filenames", "end" ]
divide yaml file @param src_file [String] @param dst_dir [String] @return [Array<String>] divided yaml filenames
[ "divide", "yaml", "file" ]
f9595c5c05802bbbdd5228e808e7cb2b9cc3a049
https://github.com/sue445/sengiri_yaml/blob/f9595c5c05802bbbdd5228e808e7cb2b9cc3a049/lib/sengiri_yaml/writer.rb#L10-L40
8,750
ltello/drsi
lib/drsi/dci/context.rb
DCI.Context.players_unplay_role!
def players_unplay_role!(extending_ticker) roles.keys.each do |rolekey| ::DCI::Multiplayer(@_players[rolekey]).each do |roleplayer| # puts " Context: #{self} - un-assigning role #{rolekey} to #{roleplayer}" roleplayer.__unplay_last_role! if extending_ticker["#{roleplayer.object_id}_#{rolekey}"] end # 'instance_variable_set(:"@#{rolekey}", nil) end end
ruby
def players_unplay_role!(extending_ticker) roles.keys.each do |rolekey| ::DCI::Multiplayer(@_players[rolekey]).each do |roleplayer| # puts " Context: #{self} - un-assigning role #{rolekey} to #{roleplayer}" roleplayer.__unplay_last_role! if extending_ticker["#{roleplayer.object_id}_#{rolekey}"] end # 'instance_variable_set(:"@#{rolekey}", nil) end end
[ "def", "players_unplay_role!", "(", "extending_ticker", ")", "roles", ".", "keys", ".", "each", "do", "|", "rolekey", "|", "::", "DCI", "::", "Multiplayer", "(", "@_players", "[", "rolekey", "]", ")", ".", "each", "do", "|", "roleplayer", "|", "# puts \" Context: #{self} - un-assigning role #{rolekey} to #{roleplayer}\"", "roleplayer", ".", "__unplay_last_role!", "if", "extending_ticker", "[", "\"#{roleplayer.object_id}_#{rolekey}\"", "]", "end", "# 'instance_variable_set(:\"@#{rolekey}\", nil)", "end", "end" ]
Disassociates every role from the playing object.
[ "Disassociates", "every", "role", "from", "the", "playing", "object", "." ]
f584ee2c2f6438e341474b6922b568f43b3e1f25
https://github.com/ltello/drsi/blob/f584ee2c2f6438e341474b6922b568f43b3e1f25/lib/drsi/dci/context.rb#L183-L191
8,751
jarrett/ichiban
lib/ichiban/watcher.rb
Ichiban.Watcher.on_change
def on_change(modified, added, deleted) # Modifications and additions are treated the same. (modified + added).uniq.each do |path| if file = Ichiban::ProjectFile.from_abs(path) begin @loader.change(file) # Tell the Loader that this file has changed file.update rescue Exception => exc Ichiban.logger.exception(exc) end end end # Deletions are handled specially. deleted.each do |path| Ichiban::Deleter.new.delete_dest(path) end # Finally, propagate this change to any dependent files. (modified + added + deleted).uniq.each do |path| begin Ichiban::Dependencies.propagate(path) rescue => exc Ichiban.logger.exception(exc) end end end
ruby
def on_change(modified, added, deleted) # Modifications and additions are treated the same. (modified + added).uniq.each do |path| if file = Ichiban::ProjectFile.from_abs(path) begin @loader.change(file) # Tell the Loader that this file has changed file.update rescue Exception => exc Ichiban.logger.exception(exc) end end end # Deletions are handled specially. deleted.each do |path| Ichiban::Deleter.new.delete_dest(path) end # Finally, propagate this change to any dependent files. (modified + added + deleted).uniq.each do |path| begin Ichiban::Dependencies.propagate(path) rescue => exc Ichiban.logger.exception(exc) end end end
[ "def", "on_change", "(", "modified", ",", "added", ",", "deleted", ")", "# Modifications and additions are treated the same.", "(", "modified", "+", "added", ")", ".", "uniq", ".", "each", "do", "|", "path", "|", "if", "file", "=", "Ichiban", "::", "ProjectFile", ".", "from_abs", "(", "path", ")", "begin", "@loader", ".", "change", "(", "file", ")", "# Tell the Loader that this file has changed", "file", ".", "update", "rescue", "Exception", "=>", "exc", "Ichiban", ".", "logger", ".", "exception", "(", "exc", ")", "end", "end", "end", "# Deletions are handled specially.", "deleted", ".", "each", "do", "|", "path", "|", "Ichiban", "::", "Deleter", ".", "new", ".", "delete_dest", "(", "path", ")", "end", "# Finally, propagate this change to any dependent files.", "(", "modified", "+", "added", "+", "deleted", ")", ".", "uniq", ".", "each", "do", "|", "path", "|", "begin", "Ichiban", "::", "Dependencies", ".", "propagate", "(", "path", ")", "rescue", "=>", "exc", "Ichiban", ".", "logger", ".", "exception", "(", "exc", ")", "end", "end", "end" ]
The test suite calls this method directly to bypass the Listen gem for certain tests.
[ "The", "test", "suite", "calls", "this", "method", "directly", "to", "bypass", "the", "Listen", "gem", "for", "certain", "tests", "." ]
310f96b0981ea19bf01246995f3732c986915d5b
https://github.com/jarrett/ichiban/blob/310f96b0981ea19bf01246995f3732c986915d5b/lib/ichiban/watcher.rb#L17-L43
8,752
niyireth/brownpapertickets
lib/brownpapertickets/event.rb
BrownPaperTickets.Event.all
def all events = Event.get("/eventlist", :query =>{"id" => @@id , "account" => @@account }) event_sales = Event.get("/eventsales", :query =>{"id" => @@id , "account" => @@account }) parsed_event = [] events.parsed_response["document"]["event"].each do |event| parsed_event << Event.new(@id,@account, event) end return parsed_event end
ruby
def all events = Event.get("/eventlist", :query =>{"id" => @@id , "account" => @@account }) event_sales = Event.get("/eventsales", :query =>{"id" => @@id , "account" => @@account }) parsed_event = [] events.parsed_response["document"]["event"].each do |event| parsed_event << Event.new(@id,@account, event) end return parsed_event end
[ "def", "all", "events", "=", "Event", ".", "get", "(", "\"/eventlist\"", ",", ":query", "=>", "{", "\"id\"", "=>", "@@id", ",", "\"account\"", "=>", "@@account", "}", ")", "event_sales", "=", "Event", ".", "get", "(", "\"/eventsales\"", ",", ":query", "=>", "{", "\"id\"", "=>", "@@id", ",", "\"account\"", "=>", "@@account", "}", ")", "parsed_event", "=", "[", "]", "events", ".", "parsed_response", "[", "\"document\"", "]", "[", "\"event\"", "]", ".", "each", "do", "|", "event", "|", "parsed_event", "<<", "Event", ".", "new", "(", "@id", ",", "@account", ",", "event", ")", "end", "return", "parsed_event", "end" ]
Returns all the account's events from brownpapersticker
[ "Returns", "all", "the", "account", "s", "events", "from", "brownpapersticker" ]
1eae1dc6f02b183c55090b79a62023e0f572fb57
https://github.com/niyireth/brownpapertickets/blob/1eae1dc6f02b183c55090b79a62023e0f572fb57/lib/brownpapertickets/event.rb#L26-L34
8,753
niyireth/brownpapertickets
lib/brownpapertickets/event.rb
BrownPaperTickets.Event.find
def find(event_id) event = Event.get("/eventlist",:query =>{"id" => @@id , "account" => @@account, "event_id" => event_id }) event_sales=Event.get("/eventsales",:query =>{"id" => @@id , "account" => @@account, "event_id" => event_id }) @attributes = event.parsed_response["document"]["event"] return self end
ruby
def find(event_id) event = Event.get("/eventlist",:query =>{"id" => @@id , "account" => @@account, "event_id" => event_id }) event_sales=Event.get("/eventsales",:query =>{"id" => @@id , "account" => @@account, "event_id" => event_id }) @attributes = event.parsed_response["document"]["event"] return self end
[ "def", "find", "(", "event_id", ")", "event", "=", "Event", ".", "get", "(", "\"/eventlist\"", ",", ":query", "=>", "{", "\"id\"", "=>", "@@id", ",", "\"account\"", "=>", "@@account", ",", "\"event_id\"", "=>", "event_id", "}", ")", "event_sales", "=", "Event", ".", "get", "(", "\"/eventsales\"", ",", ":query", "=>", "{", "\"id\"", "=>", "@@id", ",", "\"account\"", "=>", "@@account", ",", "\"event_id\"", "=>", "event_id", "}", ")", "@attributes", "=", "event", ".", "parsed_response", "[", "\"document\"", "]", "[", "\"event\"", "]", "return", "self", "end" ]
This method get an event from brownpapersticker. The event should belong to the account. @param [String] envent_id this is id of the event I want to find
[ "This", "method", "get", "an", "event", "from", "brownpapersticker", ".", "The", "event", "should", "belong", "to", "the", "account", "." ]
1eae1dc6f02b183c55090b79a62023e0f572fb57
https://github.com/niyireth/brownpapertickets/blob/1eae1dc6f02b183c55090b79a62023e0f572fb57/lib/brownpapertickets/event.rb#L39-L44
8,754
TheODI-UD2D/blocktrain
lib/blocktrain/lookups.rb
Blocktrain.Lookups.init!
def init! @lookups ||= {} @aliases ||= {} # Get unique list of keys from ES r = Aggregations::TermsAggregation.new(from: '2015-09-01 00:00:00Z', to: '2015-09-02 00:00:00Z', term: "memoryAddress").results addresses = r.map {|x| x["key"]} # Get a memory location for each key addresses.each do |address| r = Query.new(from: '2015-09-01 10:00:00Z', to: '2015-09-30 11:00:00Z', memory_addresses: address, limit: 1).results signal_name = remove_cruft(r.first["_source"]["signalName"].to_s) @lookups[signal_name] = address end # Read aliases from file aliases = OpenStruct.new fetch_yaml 'signal_aliases' aliases.each_pair do |key, value| @aliases[key.to_s] = @lookups[value] @lookups[key.to_s] = @lookups[value] end end
ruby
def init! @lookups ||= {} @aliases ||= {} # Get unique list of keys from ES r = Aggregations::TermsAggregation.new(from: '2015-09-01 00:00:00Z', to: '2015-09-02 00:00:00Z', term: "memoryAddress").results addresses = r.map {|x| x["key"]} # Get a memory location for each key addresses.each do |address| r = Query.new(from: '2015-09-01 10:00:00Z', to: '2015-09-30 11:00:00Z', memory_addresses: address, limit: 1).results signal_name = remove_cruft(r.first["_source"]["signalName"].to_s) @lookups[signal_name] = address end # Read aliases from file aliases = OpenStruct.new fetch_yaml 'signal_aliases' aliases.each_pair do |key, value| @aliases[key.to_s] = @lookups[value] @lookups[key.to_s] = @lookups[value] end end
[ "def", "init!", "@lookups", "||=", "{", "}", "@aliases", "||=", "{", "}", "# Get unique list of keys from ES", "r", "=", "Aggregations", "::", "TermsAggregation", ".", "new", "(", "from", ":", "'2015-09-01 00:00:00Z'", ",", "to", ":", "'2015-09-02 00:00:00Z'", ",", "term", ":", "\"memoryAddress\"", ")", ".", "results", "addresses", "=", "r", ".", "map", "{", "|", "x", "|", "x", "[", "\"key\"", "]", "}", "# Get a memory location for each key", "addresses", ".", "each", "do", "|", "address", "|", "r", "=", "Query", ".", "new", "(", "from", ":", "'2015-09-01 10:00:00Z'", ",", "to", ":", "'2015-09-30 11:00:00Z'", ",", "memory_addresses", ":", "address", ",", "limit", ":", "1", ")", ".", "results", "signal_name", "=", "remove_cruft", "(", "r", ".", "first", "[", "\"_source\"", "]", "[", "\"signalName\"", "]", ".", "to_s", ")", "@lookups", "[", "signal_name", "]", "=", "address", "end", "# Read aliases from file", "aliases", "=", "OpenStruct", ".", "new", "fetch_yaml", "'signal_aliases'", "aliases", ".", "each_pair", "do", "|", "key", ",", "value", "|", "@aliases", "[", "key", ".", "to_s", "]", "=", "@lookups", "[", "value", "]", "@lookups", "[", "key", ".", "to_s", "]", "=", "@lookups", "[", "value", "]", "end", "end" ]
Separate out initialization for testing purposes
[ "Separate", "out", "initialization", "for", "testing", "purposes" ]
ec415f48ebc1a1dd4e4107e21bddb2d0fe238efb
https://github.com/TheODI-UD2D/blocktrain/blob/ec415f48ebc1a1dd4e4107e21bddb2d0fe238efb/lib/blocktrain/lookups.rb#L20-L38
8,755
TheODI-UD2D/blocktrain
lib/blocktrain/lookups.rb
Blocktrain.Lookups.remove_cruft
def remove_cruft(signal) parts = signal.split(".") [ parts[0..-3].join('.'), parts.pop ].join('.') end
ruby
def remove_cruft(signal) parts = signal.split(".") [ parts[0..-3].join('.'), parts.pop ].join('.') end
[ "def", "remove_cruft", "(", "signal", ")", "parts", "=", "signal", ".", "split", "(", "\".\"", ")", "[", "parts", "[", "0", "..", "-", "3", "]", ".", "join", "(", "'.'", ")", ",", "parts", ".", "pop", "]", ".", "join", "(", "'.'", ")", "end" ]
This will go away once we get the correct signals in the DB
[ "This", "will", "go", "away", "once", "we", "get", "the", "correct", "signals", "in", "the", "DB" ]
ec415f48ebc1a1dd4e4107e21bddb2d0fe238efb
https://github.com/TheODI-UD2D/blocktrain/blob/ec415f48ebc1a1dd4e4107e21bddb2d0fe238efb/lib/blocktrain/lookups.rb#L47-L53
8,756
tubbo/active_copy
lib/active_copy/view_helper.rb
ActiveCopy.ViewHelper.render_copy
def render_copy from_source_path source_path = "#{ActiveCopy.content_path}/#{from_source_path}.md" if File.exists? source_path raw_source = IO.read source_path source = raw_source.split("---\n")[2] template = ActiveCopy::Markdown.new template.render(source).html_safe else raise ArgumentError.new "#{source_path} does not exist." end end
ruby
def render_copy from_source_path source_path = "#{ActiveCopy.content_path}/#{from_source_path}.md" if File.exists? source_path raw_source = IO.read source_path source = raw_source.split("---\n")[2] template = ActiveCopy::Markdown.new template.render(source).html_safe else raise ArgumentError.new "#{source_path} does not exist." end end
[ "def", "render_copy", "from_source_path", "source_path", "=", "\"#{ActiveCopy.content_path}/#{from_source_path}.md\"", "if", "File", ".", "exists?", "source_path", "raw_source", "=", "IO", ".", "read", "source_path", "source", "=", "raw_source", ".", "split", "(", "\"---\\n\"", ")", "[", "2", "]", "template", "=", "ActiveCopy", "::", "Markdown", ".", "new", "template", ".", "render", "(", "source", ")", ".", "html_safe", "else", "raise", "ArgumentError", ".", "new", "\"#{source_path} does not exist.\"", "end", "end" ]
Render a given relative content path to Markdown.
[ "Render", "a", "given", "relative", "content", "path", "to", "Markdown", "." ]
63716fdd9283231e9ed0d8ac6af97633d3e97210
https://github.com/tubbo/active_copy/blob/63716fdd9283231e9ed0d8ac6af97633d3e97210/lib/active_copy/view_helper.rb#L4-L15
8,757
analogeryuta/capistrano-sudo
lib/capistrano/sudo/dsl.rb
Capistrano.DSL.sudo!
def sudo!(*args) on roles(:all) do |host| key = "#{host.user}@#{host.hostname}" SSHKit::Sudo.password_cache[key] = "#{fetch(:password)}\n" # \n is enter end sudo(*args) end
ruby
def sudo!(*args) on roles(:all) do |host| key = "#{host.user}@#{host.hostname}" SSHKit::Sudo.password_cache[key] = "#{fetch(:password)}\n" # \n is enter end sudo(*args) end
[ "def", "sudo!", "(", "*", "args", ")", "on", "roles", "(", ":all", ")", "do", "|", "host", "|", "key", "=", "\"#{host.user}@#{host.hostname}\"", "SSHKit", "::", "Sudo", ".", "password_cache", "[", "key", "]", "=", "\"#{fetch(:password)}\\n\"", "# \\n is enter", "end", "sudo", "(", "args", ")", "end" ]
`sudo!` executes sudo command and provides password input.
[ "sudo!", "executes", "sudo", "command", "and", "provides", "password", "input", "." ]
20311986f3e3d2892dfcf5036d13d76bca7a3de0
https://github.com/analogeryuta/capistrano-sudo/blob/20311986f3e3d2892dfcf5036d13d76bca7a3de0/lib/capistrano/sudo/dsl.rb#L4-L10
8,758
antonversal/fake_service
lib/fake_service/middleware.rb
FakeService.Middleware.define_actions
def define_actions unless @action_defined hash = YAML.load(File.read(@file_path)) hash.each do |k, v| v.each do |key, value| @app.class.define_action!(value["request"], value["response"]) end end @action_defined = true end end
ruby
def define_actions unless @action_defined hash = YAML.load(File.read(@file_path)) hash.each do |k, v| v.each do |key, value| @app.class.define_action!(value["request"], value["response"]) end end @action_defined = true end end
[ "def", "define_actions", "unless", "@action_defined", "hash", "=", "YAML", ".", "load", "(", "File", ".", "read", "(", "@file_path", ")", ")", "hash", ".", "each", "do", "|", "k", ",", "v", "|", "v", ".", "each", "do", "|", "key", ",", "value", "|", "@app", ".", "class", ".", "define_action!", "(", "value", "[", "\"request\"", "]", ",", "value", "[", "\"response\"", "]", ")", "end", "end", "@action_defined", "=", "true", "end", "end" ]
defines actions for each request in yaml file.
[ "defines", "actions", "for", "each", "request", "in", "yaml", "file", "." ]
93a59f859447004bdea27b3b4226c4d73d197008
https://github.com/antonversal/fake_service/blob/93a59f859447004bdea27b3b4226c4d73d197008/lib/fake_service/middleware.rb#L9-L19
8,759
pikesley/insulin
lib/insulin/event.rb
Insulin.Event.save
def save mongo_handle # See above date_collection = self["date"] if self["time"] < @@cut_off_time date_collection = (Time.parse(self["date"]) - 86400).strftime "%F" end # Save to each of these collections clxns = [ "events", self["type"], self["subtype"], date_collection ] clxns.each do |c| if c mongo_handle.db.collection(c).update( { "serial" => self["serial"] }, self, { # Upsert: update if exists, otherwise insert :upsert => true } ) end end end
ruby
def save mongo_handle # See above date_collection = self["date"] if self["time"] < @@cut_off_time date_collection = (Time.parse(self["date"]) - 86400).strftime "%F" end # Save to each of these collections clxns = [ "events", self["type"], self["subtype"], date_collection ] clxns.each do |c| if c mongo_handle.db.collection(c).update( { "serial" => self["serial"] }, self, { # Upsert: update if exists, otherwise insert :upsert => true } ) end end end
[ "def", "save", "mongo_handle", "# See above", "date_collection", "=", "self", "[", "\"date\"", "]", "if", "self", "[", "\"time\"", "]", "<", "@@cut_off_time", "date_collection", "=", "(", "Time", ".", "parse", "(", "self", "[", "\"date\"", "]", ")", "-", "86400", ")", ".", "strftime", "\"%F\"", "end", "# Save to each of these collections", "clxns", "=", "[", "\"events\"", ",", "self", "[", "\"type\"", "]", ",", "self", "[", "\"subtype\"", "]", ",", "date_collection", "]", "clxns", ".", "each", "do", "|", "c", "|", "if", "c", "mongo_handle", ".", "db", ".", "collection", "(", "c", ")", ".", "update", "(", "{", "\"serial\"", "=>", "self", "[", "\"serial\"", "]", "}", ",", "self", ",", "{", "# Upsert: update if exists, otherwise insert", ":upsert", "=>", "true", "}", ")", "end", "end", "end" ]
Save the event to Mongo via mongo_handle
[ "Save", "the", "event", "to", "Mongo", "via", "mongo_handle" ]
0ef2fe0ec10afe030fb556e223cb994797456969
https://github.com/pikesley/insulin/blob/0ef2fe0ec10afe030fb556e223cb994797456969/lib/insulin/event.rb#L49-L79
8,760
zpatten/ztk
lib/ztk/logger.rb
ZTK.Logger.shift
def shift(severity, shift=0, &block) severity = ZTK::Logger.const_get(severity.to_s.upcase) add(severity, nil, nil, shift, &block) end
ruby
def shift(severity, shift=0, &block) severity = ZTK::Logger.const_get(severity.to_s.upcase) add(severity, nil, nil, shift, &block) end
[ "def", "shift", "(", "severity", ",", "shift", "=", "0", ",", "&", "block", ")", "severity", "=", "ZTK", "::", "Logger", ".", "const_get", "(", "severity", ".", "to_s", ".", "upcase", ")", "add", "(", "severity", ",", "nil", ",", "nil", ",", "shift", ",", "block", ")", "end" ]
Specialized logging. Logs messages in the same format, except has the option to shift the caller_at position to exposed the proper calling method. Very useful in situations of class inheritence, for example, where you might have logging statements in a base class, which are inherited by another class. When calling the base class method via the inherited class the log messages will indicate the base class as the caller. While this is technically true it is not always what we want to see in the logs because it is ambigious and does not show us where the call truly originated from.
[ "Specialized", "logging", ".", "Logs", "messages", "in", "the", "same", "format", "except", "has", "the", "option", "to", "shift", "the", "caller_at", "position", "to", "exposed", "the", "proper", "calling", "method", "." ]
9b0f35bef36f38428e1a57b36f25a806c240b3fb
https://github.com/zpatten/ztk/blob/9b0f35bef36f38428e1a57b36f25a806c240b3fb/lib/ztk/logger.rb#L112-L115
8,761
zpatten/ztk
lib/ztk/logger.rb
ZTK.Logger.add
def add(severity, message=nil, progname=nil, shift=0, &block) return if (@level > severity) message = block.call if message.nil? && block_given? return if message.nil? called_by = parse_caller(caller[1+shift]) message = [message.chomp, progname].flatten.compact.join(": ") message = "%19s.%06d|%05d|%5s|%s%s\n" % [Time.now.utc.strftime("%Y-%m-%d|%H:%M:%S"), Time.now.utc.usec, Process.pid, SEVERITIES[severity], called_by, message] @logdev.write(ZTK::ANSI.uncolor(message)) @logdev.respond_to?(:flush) and @logdev.flush true end
ruby
def add(severity, message=nil, progname=nil, shift=0, &block) return if (@level > severity) message = block.call if message.nil? && block_given? return if message.nil? called_by = parse_caller(caller[1+shift]) message = [message.chomp, progname].flatten.compact.join(": ") message = "%19s.%06d|%05d|%5s|%s%s\n" % [Time.now.utc.strftime("%Y-%m-%d|%H:%M:%S"), Time.now.utc.usec, Process.pid, SEVERITIES[severity], called_by, message] @logdev.write(ZTK::ANSI.uncolor(message)) @logdev.respond_to?(:flush) and @logdev.flush true end
[ "def", "add", "(", "severity", ",", "message", "=", "nil", ",", "progname", "=", "nil", ",", "shift", "=", "0", ",", "&", "block", ")", "return", "if", "(", "@level", ">", "severity", ")", "message", "=", "block", ".", "call", "if", "message", ".", "nil?", "&&", "block_given?", "return", "if", "message", ".", "nil?", "called_by", "=", "parse_caller", "(", "caller", "[", "1", "+", "shift", "]", ")", "message", "=", "[", "message", ".", "chomp", ",", "progname", "]", ".", "flatten", ".", "compact", ".", "join", "(", "\": \"", ")", "message", "=", "\"%19s.%06d|%05d|%5s|%s%s\\n\"", "%", "[", "Time", ".", "now", ".", "utc", ".", "strftime", "(", "\"%Y-%m-%d|%H:%M:%S\"", ")", ",", "Time", ".", "now", ".", "utc", ".", "usec", ",", "Process", ".", "pid", ",", "SEVERITIES", "[", "severity", "]", ",", "called_by", ",", "message", "]", "@logdev", ".", "write", "(", "ZTK", "::", "ANSI", ".", "uncolor", "(", "message", ")", ")", "@logdev", ".", "respond_to?", "(", ":flush", ")", "and", "@logdev", ".", "flush", "true", "end" ]
Writes a log message if the current log level is at or below the supplied severity. @param [Constant] severity Log level severity. @param [String] message Optional message to prefix the log entry with. @param [String] progname Optional name of the program to prefix the log entry with. @yieldreturn [String] The block should return the desired log message.
[ "Writes", "a", "log", "message", "if", "the", "current", "log", "level", "is", "at", "or", "below", "the", "supplied", "severity", "." ]
9b0f35bef36f38428e1a57b36f25a806c240b3fb
https://github.com/zpatten/ztk/blob/9b0f35bef36f38428e1a57b36f25a806c240b3fb/lib/ztk/logger.rb#L150-L165
8,762
zpatten/ztk
lib/ztk/logger.rb
ZTK.Logger.set_log_level
def set_log_level(level=nil) defined?(Rails) and (default = (Rails.env.production? ? "INFO" : "DEBUG")) or (default = "INFO") log_level = (ENV['LOG_LEVEL'] || level || default) self.level = ZTK::Logger.const_get(log_level.to_s.upcase) end
ruby
def set_log_level(level=nil) defined?(Rails) and (default = (Rails.env.production? ? "INFO" : "DEBUG")) or (default = "INFO") log_level = (ENV['LOG_LEVEL'] || level || default) self.level = ZTK::Logger.const_get(log_level.to_s.upcase) end
[ "def", "set_log_level", "(", "level", "=", "nil", ")", "defined?", "(", "Rails", ")", "and", "(", "default", "=", "(", "Rails", ".", "env", ".", "production?", "?", "\"INFO\"", ":", "\"DEBUG\"", ")", ")", "or", "(", "default", "=", "\"INFO\"", ")", "log_level", "=", "(", "ENV", "[", "'LOG_LEVEL'", "]", "||", "level", "||", "default", ")", "self", ".", "level", "=", "ZTK", "::", "Logger", ".", "const_get", "(", "log_level", ".", "to_s", ".", "upcase", ")", "end" ]
Sets the log level. @param [String] level Log level to use.
[ "Sets", "the", "log", "level", "." ]
9b0f35bef36f38428e1a57b36f25a806c240b3fb
https://github.com/zpatten/ztk/blob/9b0f35bef36f38428e1a57b36f25a806c240b3fb/lib/ztk/logger.rb#L170-L174
8,763
npepinpe/redstruct
lib/redstruct/list.rb
Redstruct.List.pop
def pop(size = 1, timeout: nil) raise ArgumentError, 'size must be positive' unless size.positive? if timeout.nil? return self.connection.rpop(@key) if size == 1 return shift_pop_script(keys: @key, argv: [-size, -1, 1]) else raise ArgumentError, 'timeout is only supported if size == 1' unless size == 1 return self.connection.brpop(@key, timeout: timeout)&.last end end
ruby
def pop(size = 1, timeout: nil) raise ArgumentError, 'size must be positive' unless size.positive? if timeout.nil? return self.connection.rpop(@key) if size == 1 return shift_pop_script(keys: @key, argv: [-size, -1, 1]) else raise ArgumentError, 'timeout is only supported if size == 1' unless size == 1 return self.connection.brpop(@key, timeout: timeout)&.last end end
[ "def", "pop", "(", "size", "=", "1", ",", "timeout", ":", "nil", ")", "raise", "ArgumentError", ",", "'size must be positive'", "unless", "size", ".", "positive?", "if", "timeout", ".", "nil?", "return", "self", ".", "connection", ".", "rpop", "(", "@key", ")", "if", "size", "==", "1", "return", "shift_pop_script", "(", "keys", ":", "@key", ",", "argv", ":", "[", "-", "size", ",", "-", "1", ",", "1", "]", ")", "else", "raise", "ArgumentError", ",", "'timeout is only supported if size == 1'", "unless", "size", "==", "1", "return", "self", ".", "connection", ".", "brpop", "(", "@key", ",", "timeout", ":", "timeout", ")", "&.", "last", "end", "end" ]
Pops an item from the list, optionally blocking to wait until the list is non-empty @param [Integer] timeout the amount of time to wait in seconds; if 0, waits indefinitely @return [nil, String] nil if the list was empty, otherwise the item
[ "Pops", "an", "item", "from", "the", "list", "optionally", "blocking", "to", "wait", "until", "the", "list", "is", "non", "-", "empty" ]
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/list.rb#L115-L125
8,764
npepinpe/redstruct
lib/redstruct/list.rb
Redstruct.List.shift
def shift(size = 1, timeout: nil) raise ArgumentError, 'size must be positive' unless size.positive? if timeout.nil? return self.connection.lpop(@key) if size == 1 return shift_pop_script(keys: @key, argv: [0, size - 1, 0]) else raise ArgumentError, 'timeout is only supported if size == 1' unless size == 1 return self.connection.blpop(@key, timeout: timeout)&.last end end
ruby
def shift(size = 1, timeout: nil) raise ArgumentError, 'size must be positive' unless size.positive? if timeout.nil? return self.connection.lpop(@key) if size == 1 return shift_pop_script(keys: @key, argv: [0, size - 1, 0]) else raise ArgumentError, 'timeout is only supported if size == 1' unless size == 1 return self.connection.blpop(@key, timeout: timeout)&.last end end
[ "def", "shift", "(", "size", "=", "1", ",", "timeout", ":", "nil", ")", "raise", "ArgumentError", ",", "'size must be positive'", "unless", "size", ".", "positive?", "if", "timeout", ".", "nil?", "return", "self", ".", "connection", ".", "lpop", "(", "@key", ")", "if", "size", "==", "1", "return", "shift_pop_script", "(", "keys", ":", "@key", ",", "argv", ":", "[", "0", ",", "size", "-", "1", ",", "0", "]", ")", "else", "raise", "ArgumentError", ",", "'timeout is only supported if size == 1'", "unless", "size", "==", "1", "return", "self", ".", "connection", ".", "blpop", "(", "@key", ",", "timeout", ":", "timeout", ")", "&.", "last", "end", "end" ]
Shifts an item from the list, optionally blocking to wait until the list is non-empty @param [Integer] timeout the amount of time to wait in seconds; if 0, waits indefinitely @return [nil, String] nil if the list was empty, otherwise the item
[ "Shifts", "an", "item", "from", "the", "list", "optionally", "blocking", "to", "wait", "until", "the", "list", "is", "non", "-", "empty" ]
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/list.rb#L130-L140
8,765
npepinpe/redstruct
lib/redstruct/list.rb
Redstruct.List.popshift
def popshift(list, timeout: nil) raise ArgumentError, 'list must respond to #key' unless list.respond_to?(:key) if timeout.nil? return self.connection.rpoplpush(@key, list.key) else return self.connection.brpoplpush(@key, list.key, timeout: timeout) end end
ruby
def popshift(list, timeout: nil) raise ArgumentError, 'list must respond to #key' unless list.respond_to?(:key) if timeout.nil? return self.connection.rpoplpush(@key, list.key) else return self.connection.brpoplpush(@key, list.key, timeout: timeout) end end
[ "def", "popshift", "(", "list", ",", "timeout", ":", "nil", ")", "raise", "ArgumentError", ",", "'list must respond to #key'", "unless", "list", ".", "respond_to?", "(", ":key", ")", "if", "timeout", ".", "nil?", "return", "self", ".", "connection", ".", "rpoplpush", "(", "@key", ",", "list", ".", "key", ")", "else", "return", "self", ".", "connection", ".", "brpoplpush", "(", "@key", ",", "list", ".", "key", ",", "timeout", ":", "timeout", ")", "end", "end" ]
Pops an element from this list and shifts it onto the given list. @param [Redstruct::List] list the list to shift the element onto @param [#to_i] timeout optional timeout to wait for in seconds @return [String] the element that was popped from the list and pushed onto the other
[ "Pops", "an", "element", "from", "this", "list", "and", "shifts", "it", "onto", "the", "given", "list", "." ]
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/list.rb#L146-L154
8,766
colstrom/ezmq
lib/ezmq/socket.rb
EZMQ.Socket.connect
def connect(transport: :tcp, address: '127.0.0.1', port: 5555) endpoint = "#{ transport }://#{ address }" endpoint << ":#{ port }" if %i(tcp pgm epgm).include? transport @socket.method(__callee__).call(endpoint) == 0 end
ruby
def connect(transport: :tcp, address: '127.0.0.1', port: 5555) endpoint = "#{ transport }://#{ address }" endpoint << ":#{ port }" if %i(tcp pgm epgm).include? transport @socket.method(__callee__).call(endpoint) == 0 end
[ "def", "connect", "(", "transport", ":", ":tcp", ",", "address", ":", "'127.0.0.1'", ",", "port", ":", "5555", ")", "endpoint", "=", "\"#{ transport }://#{ address }\"", "endpoint", "<<", "\":#{ port }\"", "if", "%i(", "tcp", "pgm", "epgm", ")", ".", "include?", "transport", "@socket", ".", "method", "(", "__callee__", ")", ".", "call", "(", "endpoint", ")", "==", "0", "end" ]
Connects the socket to the given address. @note This method can be called as #bind, in which case it binds to the specified address instead. @param [Symbol] transport (:tcp) transport for transport. @param [String] address ('127.0.0.1') address for endpoint. @note Binding to 'localhost' is not consistent on all platforms. Prefer '127.0.0.1' instead. @param [Fixnum] port (5555) port for endpoint. @note port is ignored unless transport is one of :tcp, :pgm or :epgm @return [Boolean] was connection successful?
[ "Connects", "the", "socket", "to", "the", "given", "address", "." ]
cd7f9f256d6c3f7a844871a3a77a89d7122d5836
https://github.com/colstrom/ezmq/blob/cd7f9f256d6c3f7a844871a3a77a89d7122d5836/lib/ezmq/socket.rb#L88-L92
8,767
abrandoned/multi_op_queue
lib/multi_op_queue.rb
MultiOpQueue.Queue.pop
def pop(non_block=false) handle_interrupt do @mutex.synchronize do while true if @que.empty? if non_block raise ThreadError, "queue empty" else begin @num_waiting += 1 @cond.wait @mutex ensure @num_waiting -= 1 end end else return @que.shift end end end end end
ruby
def pop(non_block=false) handle_interrupt do @mutex.synchronize do while true if @que.empty? if non_block raise ThreadError, "queue empty" else begin @num_waiting += 1 @cond.wait @mutex ensure @num_waiting -= 1 end end else return @que.shift end end end end end
[ "def", "pop", "(", "non_block", "=", "false", ")", "handle_interrupt", "do", "@mutex", ".", "synchronize", "do", "while", "true", "if", "@que", ".", "empty?", "if", "non_block", "raise", "ThreadError", ",", "\"queue empty\"", "else", "begin", "@num_waiting", "+=", "1", "@cond", ".", "wait", "@mutex", "ensure", "@num_waiting", "-=", "1", "end", "end", "else", "return", "@que", ".", "shift", "end", "end", "end", "end", "end" ]
Retrieves data from the queue. If the queue is empty, the calling thread is suspended until data is pushed onto the queue. If +non_block+ is true, the thread isn't suspended, and an exception is raised.
[ "Retrieves", "data", "from", "the", "queue", ".", "If", "the", "queue", "is", "empty", "the", "calling", "thread", "is", "suspended", "until", "data", "is", "pushed", "onto", "the", "queue", ".", "If", "+", "non_block", "+", "is", "true", "the", "thread", "isn", "t", "suspended", "and", "an", "exception", "is", "raised", "." ]
51cc58bd2fc20af2991e3c766d2bbd83c409ea0a
https://github.com/abrandoned/multi_op_queue/blob/51cc58bd2fc20af2991e3c766d2bbd83c409ea0a/lib/multi_op_queue.rb#L85-L106
8,768
abrandoned/multi_op_queue
lib/multi_op_queue.rb
MultiOpQueue.Queue.pop_up_to
def pop_up_to(num_to_pop = 1, opts = {}) case opts when TrueClass, FalseClass non_bock = opts when Hash timeout = opts.fetch(:timeout, nil) non_block = opts.fetch(:non_block, false) end handle_interrupt do @mutex.synchronize do while true if @que.empty? if non_block raise ThreadError, "queue empty" else begin @num_waiting += 1 @cond.wait(@mutex, timeout) return nil if @que.empty? ensure @num_waiting -= 1 end end else return @que.shift(num_to_pop) end end end end end
ruby
def pop_up_to(num_to_pop = 1, opts = {}) case opts when TrueClass, FalseClass non_bock = opts when Hash timeout = opts.fetch(:timeout, nil) non_block = opts.fetch(:non_block, false) end handle_interrupt do @mutex.synchronize do while true if @que.empty? if non_block raise ThreadError, "queue empty" else begin @num_waiting += 1 @cond.wait(@mutex, timeout) return nil if @que.empty? ensure @num_waiting -= 1 end end else return @que.shift(num_to_pop) end end end end end
[ "def", "pop_up_to", "(", "num_to_pop", "=", "1", ",", "opts", "=", "{", "}", ")", "case", "opts", "when", "TrueClass", ",", "FalseClass", "non_bock", "=", "opts", "when", "Hash", "timeout", "=", "opts", ".", "fetch", "(", ":timeout", ",", "nil", ")", "non_block", "=", "opts", ".", "fetch", "(", ":non_block", ",", "false", ")", "end", "handle_interrupt", "do", "@mutex", ".", "synchronize", "do", "while", "true", "if", "@que", ".", "empty?", "if", "non_block", "raise", "ThreadError", ",", "\"queue empty\"", "else", "begin", "@num_waiting", "+=", "1", "@cond", ".", "wait", "(", "@mutex", ",", "timeout", ")", "return", "nil", "if", "@que", ".", "empty?", "ensure", "@num_waiting", "-=", "1", "end", "end", "else", "return", "@que", ".", "shift", "(", "num_to_pop", ")", "end", "end", "end", "end", "end" ]
Retrieves data from the queue and returns array of contents. If +num_to_pop+ are available in the queue then multiple elements are returned in array response If the queue is empty, the calling thread is suspended until data is pushed onto the queue. If +non_block+ is true, the thread isn't suspended, and an exception is raised.
[ "Retrieves", "data", "from", "the", "queue", "and", "returns", "array", "of", "contents", ".", "If", "+", "num_to_pop", "+", "are", "available", "in", "the", "queue", "then", "multiple", "elements", "are", "returned", "in", "array", "response", "If", "the", "queue", "is", "empty", "the", "calling", "thread", "is", "suspended", "until", "data", "is", "pushed", "onto", "the", "queue", ".", "If", "+", "non_block", "+", "is", "true", "the", "thread", "isn", "t", "suspended", "and", "an", "exception", "is", "raised", "." ]
51cc58bd2fc20af2991e3c766d2bbd83c409ea0a
https://github.com/abrandoned/multi_op_queue/blob/51cc58bd2fc20af2991e3c766d2bbd83c409ea0a/lib/multi_op_queue.rb#L125-L155
8,769
yivo/confo-config
lib/confo/concerns/options_manager.rb
Confo.OptionsManager.raw_get
def raw_get(option) value = options_storage[option] Confo.callable_without_arguments?(value) ? value.call : value end
ruby
def raw_get(option) value = options_storage[option] Confo.callable_without_arguments?(value) ? value.call : value end
[ "def", "raw_get", "(", "option", ")", "value", "=", "options_storage", "[", "option", "]", "Confo", ".", "callable_without_arguments?", "(", "value", ")", "?", "value", ".", "call", ":", "value", "end" ]
Internal method to get an option. If value is callable without arguments it will be called and result will be returned.
[ "Internal", "method", "to", "get", "an", "option", ".", "If", "value", "is", "callable", "without", "arguments", "it", "will", "be", "called", "and", "result", "will", "be", "returned", "." ]
4d5be81947b450c6daa329bcc111096ae629cf46
https://github.com/yivo/confo-config/blob/4d5be81947b450c6daa329bcc111096ae629cf46/lib/confo/concerns/options_manager.rb#L72-L75
8,770
yivo/confo-config
lib/confo/concerns/options_manager.rb
Confo.OptionsManager.public_set
def public_set(option, value) # TODO Prevent subconfigs here method = "#{option}=" respond_to?(method) ? send(method, value) : raw_set(option, value) end
ruby
def public_set(option, value) # TODO Prevent subconfigs here method = "#{option}=" respond_to?(method) ? send(method, value) : raw_set(option, value) end
[ "def", "public_set", "(", "option", ",", "value", ")", "# TODO Prevent subconfigs here", "method", "=", "\"#{option}=\"", "respond_to?", "(", "method", ")", "?", "send", "(", "method", ",", "value", ")", ":", "raw_set", "(", "option", ",", "value", ")", "end" ]
Method to set an option. If there is an option accessor defined then it will be used. In other cases +raw_set+ will be used.
[ "Method", "to", "set", "an", "option", ".", "If", "there", "is", "an", "option", "accessor", "defined", "then", "it", "will", "be", "used", ".", "In", "other", "cases", "+", "raw_set", "+", "will", "be", "used", "." ]
4d5be81947b450c6daa329bcc111096ae629cf46
https://github.com/yivo/confo-config/blob/4d5be81947b450c6daa329bcc111096ae629cf46/lib/confo/concerns/options_manager.rb#L100-L104
8,771
yivo/confo-config
lib/confo/concerns/options_manager.rb
Confo.OptionsManager.set?
def set?(arg, *rest_args) if arg.kind_of?(Hash) arg.each { |k, v| set(k, v) unless set?(k) } nil elsif rest_args.size > 0 set(arg, rest_args.first) unless set?(arg) true else options_storage.has_key?(arg) end end
ruby
def set?(arg, *rest_args) if arg.kind_of?(Hash) arg.each { |k, v| set(k, v) unless set?(k) } nil elsif rest_args.size > 0 set(arg, rest_args.first) unless set?(arg) true else options_storage.has_key?(arg) end end
[ "def", "set?", "(", "arg", ",", "*", "rest_args", ")", "if", "arg", ".", "kind_of?", "(", "Hash", ")", "arg", ".", "each", "{", "|", "k", ",", "v", "|", "set", "(", "k", ",", "v", ")", "unless", "set?", "(", "k", ")", "}", "nil", "elsif", "rest_args", ".", "size", ">", "0", "set", "(", "arg", ",", "rest_args", ".", "first", ")", "unless", "set?", "(", "arg", ")", "true", "else", "options_storage", ".", "has_key?", "(", "arg", ")", "end", "end" ]
Checks if option is set. Works similar to set if value passed but sets only uninitialized options.
[ "Checks", "if", "option", "is", "set", ".", "Works", "similar", "to", "set", "if", "value", "passed", "but", "sets", "only", "uninitialized", "options", "." ]
4d5be81947b450c6daa329bcc111096ae629cf46
https://github.com/yivo/confo-config/blob/4d5be81947b450c6daa329bcc111096ae629cf46/lib/confo/concerns/options_manager.rb#L135-L145
8,772
galetahub/page_parts
lib/page_parts/extension.rb
PageParts.Extension.find_or_build_page_part
def find_or_build_page_part(attr_name) key = normalize_page_part_key(attr_name) page_parts.detect { |record| record.key.to_s == key } || page_parts.build(key: key) end
ruby
def find_or_build_page_part(attr_name) key = normalize_page_part_key(attr_name) page_parts.detect { |record| record.key.to_s == key } || page_parts.build(key: key) end
[ "def", "find_or_build_page_part", "(", "attr_name", ")", "key", "=", "normalize_page_part_key", "(", "attr_name", ")", "page_parts", ".", "detect", "{", "|", "record", "|", "record", ".", "key", ".", "to_s", "==", "key", "}", "||", "page_parts", ".", "build", "(", "key", ":", "key", ")", "end" ]
Find page part by key or build new record
[ "Find", "page", "part", "by", "key", "or", "build", "new", "record" ]
97650adc9574a15ebdec3086d9f737b46f1ae101
https://github.com/galetahub/page_parts/blob/97650adc9574a15ebdec3086d9f737b46f1ae101/lib/page_parts/extension.rb#L44-L47
8,773
oniram88/imdb-scan
lib/imdb/movie.rb
IMDB.Movie.poster
def poster src = doc.at("#img_primary img")["src"] rescue nil unless src.nil? if src.match(/\._V1/) return src.match(/(.*)\._V1.*(.jpg)/)[1, 2].join else return src end end src end
ruby
def poster src = doc.at("#img_primary img")["src"] rescue nil unless src.nil? if src.match(/\._V1/) return src.match(/(.*)\._V1.*(.jpg)/)[1, 2].join else return src end end src end
[ "def", "poster", "src", "=", "doc", ".", "at", "(", "\"#img_primary img\"", ")", "[", "\"src\"", "]", "rescue", "nil", "unless", "src", ".", "nil?", "if", "src", ".", "match", "(", "/", "\\.", "/", ")", "return", "src", ".", "match", "(", "/", "\\.", "/", ")", "[", "1", ",", "2", "]", ".", "join", "else", "return", "src", "end", "end", "src", "end" ]
Get movie poster address @return [String]
[ "Get", "movie", "poster", "address" ]
e358adaba3db178df42c711c79c894f14d83c742
https://github.com/oniram88/imdb-scan/blob/e358adaba3db178df42c711c79c894f14d83c742/lib/imdb/movie.rb#L32-L42
8,774
oniram88/imdb-scan
lib/imdb/movie.rb
IMDB.Movie.title
def title doc.at("//head/meta[@name='title']")["content"].split(/\(.*\)/)[0].strip! || doc.at("h1.header").children.first.text.strip end
ruby
def title doc.at("//head/meta[@name='title']")["content"].split(/\(.*\)/)[0].strip! || doc.at("h1.header").children.first.text.strip end
[ "def", "title", "doc", ".", "at", "(", "\"//head/meta[@name='title']\"", ")", "[", "\"content\"", "]", ".", "split", "(", "/", "\\(", "\\)", "/", ")", "[", "0", "]", ".", "strip!", "||", "doc", ".", "at", "(", "\"h1.header\"", ")", ".", "children", ".", "first", ".", "text", ".", "strip", "end" ]
Get movie title @return [String]
[ "Get", "movie", "title" ]
e358adaba3db178df42c711c79c894f14d83c742
https://github.com/oniram88/imdb-scan/blob/e358adaba3db178df42c711c79c894f14d83c742/lib/imdb/movie.rb#L46-L50
8,775
oniram88/imdb-scan
lib/imdb/movie.rb
IMDB.Movie.director_person
def director_person begin link=doc.xpath("//h4[contains(., 'Director')]/..").at('a[@href^="/name/nm"]') profile = link['href'].match(/\/name\/nm([0-9]+)/)[1] rescue nil IMDB::Person.new(profile) unless profile.nil? rescue nil end end
ruby
def director_person begin link=doc.xpath("//h4[contains(., 'Director')]/..").at('a[@href^="/name/nm"]') profile = link['href'].match(/\/name\/nm([0-9]+)/)[1] rescue nil IMDB::Person.new(profile) unless profile.nil? rescue nil end end
[ "def", "director_person", "begin", "link", "=", "doc", ".", "xpath", "(", "\"//h4[contains(., 'Director')]/..\"", ")", ".", "at", "(", "'a[@href^=\"/name/nm\"]'", ")", "profile", "=", "link", "[", "'href'", "]", ".", "match", "(", "/", "\\/", "\\/", "/", ")", "[", "1", "]", "rescue", "nil", "IMDB", "::", "Person", ".", "new", "(", "profile", ")", "unless", "profile", ".", "nil?", "rescue", "nil", "end", "end" ]
Get Director Person class @return [Person]
[ "Get", "Director", "Person", "class" ]
e358adaba3db178df42c711c79c894f14d83c742
https://github.com/oniram88/imdb-scan/blob/e358adaba3db178df42c711c79c894f14d83c742/lib/imdb/movie.rb#L103-L111
8,776
mLewisLogic/cisco-mse-client
lib/cisco-mse-client/stub.rb
CiscoMSE.Stub.stub!
def stub! CiscoMSE::Endpoints::Location.any_instance.stub(:clients).and_return( Stub::Data::Location::CLIENTS ) end
ruby
def stub! CiscoMSE::Endpoints::Location.any_instance.stub(:clients).and_return( Stub::Data::Location::CLIENTS ) end
[ "def", "stub!", "CiscoMSE", "::", "Endpoints", "::", "Location", ".", "any_instance", ".", "stub", "(", ":clients", ")", ".", "and_return", "(", "Stub", "::", "Data", "::", "Location", "::", "CLIENTS", ")", "end" ]
Setup stubbing for all endpoints
[ "Setup", "stubbing", "for", "all", "endpoints" ]
8d5a659349f7a42e5f130707780367c38061dfc6
https://github.com/mLewisLogic/cisco-mse-client/blob/8d5a659349f7a42e5f130707780367c38061dfc6/lib/cisco-mse-client/stub.rb#L11-L13
8,777
ideonetwork/lato-blog
lib/lato_blog/interfaces/posts.rb
LatoBlog.Interface::Posts.blog__clean_post_parents
def blog__clean_post_parents post_parents = LatoBlog::PostParent.all post_parents.map { |pp| pp.destroy if pp.posts.empty? } end
ruby
def blog__clean_post_parents post_parents = LatoBlog::PostParent.all post_parents.map { |pp| pp.destroy if pp.posts.empty? } end
[ "def", "blog__clean_post_parents", "post_parents", "=", "LatoBlog", "::", "PostParent", ".", "all", "post_parents", ".", "map", "{", "|", "pp", "|", "pp", ".", "destroy", "if", "pp", ".", "posts", ".", "empty?", "}", "end" ]
This function cleans all old post parents without any child.
[ "This", "function", "cleans", "all", "old", "post", "parents", "without", "any", "child", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/posts.rb#L7-L10
8,778
ideonetwork/lato-blog
lib/lato_blog/interfaces/posts.rb
LatoBlog.Interface::Posts.blog__get_posts
def blog__get_posts( order: nil, language: nil, category_permalink: nil, category_permalink_AND: false, category_id: nil, category_id_AND: false, tag_permalink: nil, tag_permalink_AND: false, tag_id: nil, tag_id_AND: false, search: nil, page: nil, per_page: nil ) posts = LatoBlog::Post.published.joins(:post_parent).where('lato_blog_post_parents.publication_datetime <= ?', DateTime.now) # apply filters order = order && order == 'ASC' ? 'ASC' : 'DESC' posts = _posts_filter_by_order(posts, order) posts = _posts_filter_by_language(posts, language) if category_permalink || category_id posts = posts.joins(:categories) posts = _posts_filter_by_category_permalink(posts, category_permalink, category_permalink_AND) posts = _posts_filter_category_id(posts, category_id, category_id_AND) end if tag_permalink || tag_id posts = posts.joins(:tags) posts = _posts_filter_by_tag_permalink(posts, tag_permalink, tag_permalink_AND) posts = _posts_filter_tag_id(posts, tag_id, tag_id_AND) end posts = _posts_filter_search(posts, search) # take posts uniqueness posts = posts.uniq(&:id) # save total posts total = posts.length # manage pagination page = page&.to_i || 1 per_page = per_page&.to_i || 20 posts = core__paginate_array(posts, per_page, page) # return result { posts: posts && !posts.empty? ? posts.map(&:serialize) : [], page: page, per_page: per_page, order: order, total: total } end
ruby
def blog__get_posts( order: nil, language: nil, category_permalink: nil, category_permalink_AND: false, category_id: nil, category_id_AND: false, tag_permalink: nil, tag_permalink_AND: false, tag_id: nil, tag_id_AND: false, search: nil, page: nil, per_page: nil ) posts = LatoBlog::Post.published.joins(:post_parent).where('lato_blog_post_parents.publication_datetime <= ?', DateTime.now) # apply filters order = order && order == 'ASC' ? 'ASC' : 'DESC' posts = _posts_filter_by_order(posts, order) posts = _posts_filter_by_language(posts, language) if category_permalink || category_id posts = posts.joins(:categories) posts = _posts_filter_by_category_permalink(posts, category_permalink, category_permalink_AND) posts = _posts_filter_category_id(posts, category_id, category_id_AND) end if tag_permalink || tag_id posts = posts.joins(:tags) posts = _posts_filter_by_tag_permalink(posts, tag_permalink, tag_permalink_AND) posts = _posts_filter_tag_id(posts, tag_id, tag_id_AND) end posts = _posts_filter_search(posts, search) # take posts uniqueness posts = posts.uniq(&:id) # save total posts total = posts.length # manage pagination page = page&.to_i || 1 per_page = per_page&.to_i || 20 posts = core__paginate_array(posts, per_page, page) # return result { posts: posts && !posts.empty? ? posts.map(&:serialize) : [], page: page, per_page: per_page, order: order, total: total } end
[ "def", "blog__get_posts", "(", "order", ":", "nil", ",", "language", ":", "nil", ",", "category_permalink", ":", "nil", ",", "category_permalink_AND", ":", "false", ",", "category_id", ":", "nil", ",", "category_id_AND", ":", "false", ",", "tag_permalink", ":", "nil", ",", "tag_permalink_AND", ":", "false", ",", "tag_id", ":", "nil", ",", "tag_id_AND", ":", "false", ",", "search", ":", "nil", ",", "page", ":", "nil", ",", "per_page", ":", "nil", ")", "posts", "=", "LatoBlog", "::", "Post", ".", "published", ".", "joins", "(", ":post_parent", ")", ".", "where", "(", "'lato_blog_post_parents.publication_datetime <= ?'", ",", "DateTime", ".", "now", ")", "# apply filters", "order", "=", "order", "&&", "order", "==", "'ASC'", "?", "'ASC'", ":", "'DESC'", "posts", "=", "_posts_filter_by_order", "(", "posts", ",", "order", ")", "posts", "=", "_posts_filter_by_language", "(", "posts", ",", "language", ")", "if", "category_permalink", "||", "category_id", "posts", "=", "posts", ".", "joins", "(", ":categories", ")", "posts", "=", "_posts_filter_by_category_permalink", "(", "posts", ",", "category_permalink", ",", "category_permalink_AND", ")", "posts", "=", "_posts_filter_category_id", "(", "posts", ",", "category_id", ",", "category_id_AND", ")", "end", "if", "tag_permalink", "||", "tag_id", "posts", "=", "posts", ".", "joins", "(", ":tags", ")", "posts", "=", "_posts_filter_by_tag_permalink", "(", "posts", ",", "tag_permalink", ",", "tag_permalink_AND", ")", "posts", "=", "_posts_filter_tag_id", "(", "posts", ",", "tag_id", ",", "tag_id_AND", ")", "end", "posts", "=", "_posts_filter_search", "(", "posts", ",", "search", ")", "# take posts uniqueness", "posts", "=", "posts", ".", "uniq", "(", ":id", ")", "# save total posts", "total", "=", "posts", ".", "length", "# manage pagination", "page", "=", "page", "&.", "to_i", "||", "1", "per_page", "=", "per_page", "&.", "to_i", "||", "20", "posts", "=", "core__paginate_array", "(", "posts", ",", "per_page", ",", "page", ")", "# return result", "{", "posts", ":", "posts", "&&", "!", "posts", ".", "empty?", "?", "posts", ".", "map", "(", ":serialize", ")", ":", "[", "]", ",", "page", ":", "page", ",", "per_page", ":", "per_page", ",", "order", ":", "order", ",", "total", ":", "total", "}", "end" ]
This function returns an object with the list of posts with some filters.
[ "This", "function", "returns", "an", "object", "with", "the", "list", "of", "posts", "with", "some", "filters", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/posts.rb#L13-L65
8,779
ideonetwork/lato-blog
lib/lato_blog/interfaces/posts.rb
LatoBlog.Interface::Posts.blog__get_post
def blog__get_post(id: nil, permalink: nil) return {} unless id || permalink if id post = LatoBlog::Post.find_by(id: id.to_i, meta_status: 'published') else post = LatoBlog::Post.find_by(meta_permalink: permalink, meta_status: 'published') end post.serialize end
ruby
def blog__get_post(id: nil, permalink: nil) return {} unless id || permalink if id post = LatoBlog::Post.find_by(id: id.to_i, meta_status: 'published') else post = LatoBlog::Post.find_by(meta_permalink: permalink, meta_status: 'published') end post.serialize end
[ "def", "blog__get_post", "(", "id", ":", "nil", ",", "permalink", ":", "nil", ")", "return", "{", "}", "unless", "id", "||", "permalink", "if", "id", "post", "=", "LatoBlog", "::", "Post", ".", "find_by", "(", "id", ":", "id", ".", "to_i", ",", "meta_status", ":", "'published'", ")", "else", "post", "=", "LatoBlog", "::", "Post", ".", "find_by", "(", "meta_permalink", ":", "permalink", ",", "meta_status", ":", "'published'", ")", "end", "post", ".", "serialize", "end" ]
This function returns a single post searched by id or permalink.
[ "This", "function", "returns", "a", "single", "post", "searched", "by", "id", "or", "permalink", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/posts.rb#L68-L78
8,780
3100/trahald
lib/trahald/redis-client.rb
Trahald.RedisClient.commit!
def commit!(message) date = Time.now @status_add.each{|name, body| json = Article.new(name, body, date).to_json zcard = @redis.zcard name @redis.zadd name, zcard+1, json @redis.sadd KEY_SET, name @summary_redis.update MarkdownBody.new(name, body, date).summary } @remove_add.each{|name, latest_rank| @redis.zremrange(name, 0, latest_rank) } @redis.set MODIFIED_DATE, date.to_s end
ruby
def commit!(message) date = Time.now @status_add.each{|name, body| json = Article.new(name, body, date).to_json zcard = @redis.zcard name @redis.zadd name, zcard+1, json @redis.sadd KEY_SET, name @summary_redis.update MarkdownBody.new(name, body, date).summary } @remove_add.each{|name, latest_rank| @redis.zremrange(name, 0, latest_rank) } @redis.set MODIFIED_DATE, date.to_s end
[ "def", "commit!", "(", "message", ")", "date", "=", "Time", ".", "now", "@status_add", ".", "each", "{", "|", "name", ",", "body", "|", "json", "=", "Article", ".", "new", "(", "name", ",", "body", ",", "date", ")", ".", "to_json", "zcard", "=", "@redis", ".", "zcard", "name", "@redis", ".", "zadd", "name", ",", "zcard", "+", "1", ",", "json", "@redis", ".", "sadd", "KEY_SET", ",", "name", "@summary_redis", ".", "update", "MarkdownBody", ".", "new", "(", "name", ",", "body", ",", "date", ")", ".", "summary", "}", "@remove_add", ".", "each", "{", "|", "name", ",", "latest_rank", "|", "@redis", ".", "zremrange", "(", "name", ",", "0", ",", "latest_rank", ")", "}", "@redis", ".", "set", "MODIFIED_DATE", ",", "date", ".", "to_s", "end" ]
message is not used.
[ "message", "is", "not", "used", "." ]
a32bdd61ee3db1579c194eee2e898ae364f99870
https://github.com/3100/trahald/blob/a32bdd61ee3db1579c194eee2e898ae364f99870/lib/trahald/redis-client.rb#L43-L56
8,781
gssbzn/slack-api-wrapper
lib/slack/request.rb
Slack.Request.make_query_string
def make_query_string(params) clean_params(params).collect do |k, v| CGI.escape(k) + '=' + CGI.escape(v) end.join('&') end
ruby
def make_query_string(params) clean_params(params).collect do |k, v| CGI.escape(k) + '=' + CGI.escape(v) end.join('&') end
[ "def", "make_query_string", "(", "params", ")", "clean_params", "(", "params", ")", ".", "collect", "do", "|", "k", ",", "v", "|", "CGI", ".", "escape", "(", "k", ")", "+", "'='", "+", "CGI", ".", "escape", "(", "v", ")", "end", ".", "join", "(", "'&'", ")", "end" ]
Convert params to query string @param [Hash] params API call arguments @return [String]
[ "Convert", "params", "to", "query", "string" ]
cba33ad720295d7afa193662ff69574308552def
https://github.com/gssbzn/slack-api-wrapper/blob/cba33ad720295d7afa193662ff69574308552def/lib/slack/request.rb#L9-L13
8,782
gssbzn/slack-api-wrapper
lib/slack/request.rb
Slack.Request.do_http
def do_http(uri, request) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true # Let then know about us request['User-Agent'] = 'SlackRubyAPIWrapper' begin http.request(request) rescue OpenSSL::SSL::SSLError => e raise Slack::Error, 'SSL error connecting to Slack.' end end
ruby
def do_http(uri, request) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true # Let then know about us request['User-Agent'] = 'SlackRubyAPIWrapper' begin http.request(request) rescue OpenSSL::SSL::SSLError => e raise Slack::Error, 'SSL error connecting to Slack.' end end
[ "def", "do_http", "(", "uri", ",", "request", ")", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "http", ".", "use_ssl", "=", "true", "# Let then know about us", "request", "[", "'User-Agent'", "]", "=", "'SlackRubyAPIWrapper'", "begin", "http", ".", "request", "(", "request", ")", "rescue", "OpenSSL", "::", "SSL", "::", "SSLError", "=>", "e", "raise", "Slack", "::", "Error", ",", "'SSL error connecting to Slack.'", "end", "end" ]
Handle http requests @param [URI::HTTPS] uri API uri @param [Object] request request object @return [Net::HTTPResponse]
[ "Handle", "http", "requests" ]
cba33ad720295d7afa193662ff69574308552def
https://github.com/gssbzn/slack-api-wrapper/blob/cba33ad720295d7afa193662ff69574308552def/lib/slack/request.rb#L21-L31
8,783
essfeed/ruby-ess
lib/ess/ess.rb
ESS.ESS.find_coming
def find_coming n=10, start_time=nil start_time = Time.now if start_time.nil? feeds = [] channel.feed_list.each do |feed| feed.dates.item_list.each do |item| if item.type_attr == "standalone" feeds << { :time => Time.parse(item.start.text!), :feed => feed } elsif item.type_attr == "recurrent" moments = parse_recurrent_date_item(item, n, start_time) moments.each do |moment| feeds << { :time => moment, :feed => feed } end elsif item.type_attr == "permanent" start = Time.parse(item.start.text!) if start > start_time feeds << { :time => start, :feed => feed } else feeds << { :time => start_time, :feed => feed } end else raise DTD::InvalidValueError, "the \"#{item.type_attr}\" is not valid for a date item type attribute" end end end feeds = feeds.delete_if { |x| x[:time] < start_time } feeds.sort! { |x, y| x[:time] <=> y[:time] } return feeds[0..n-1] end
ruby
def find_coming n=10, start_time=nil start_time = Time.now if start_time.nil? feeds = [] channel.feed_list.each do |feed| feed.dates.item_list.each do |item| if item.type_attr == "standalone" feeds << { :time => Time.parse(item.start.text!), :feed => feed } elsif item.type_attr == "recurrent" moments = parse_recurrent_date_item(item, n, start_time) moments.each do |moment| feeds << { :time => moment, :feed => feed } end elsif item.type_attr == "permanent" start = Time.parse(item.start.text!) if start > start_time feeds << { :time => start, :feed => feed } else feeds << { :time => start_time, :feed => feed } end else raise DTD::InvalidValueError, "the \"#{item.type_attr}\" is not valid for a date item type attribute" end end end feeds = feeds.delete_if { |x| x[:time] < start_time } feeds.sort! { |x, y| x[:time] <=> y[:time] } return feeds[0..n-1] end
[ "def", "find_coming", "n", "=", "10", ",", "start_time", "=", "nil", "start_time", "=", "Time", ".", "now", "if", "start_time", ".", "nil?", "feeds", "=", "[", "]", "channel", ".", "feed_list", ".", "each", "do", "|", "feed", "|", "feed", ".", "dates", ".", "item_list", ".", "each", "do", "|", "item", "|", "if", "item", ".", "type_attr", "==", "\"standalone\"", "feeds", "<<", "{", ":time", "=>", "Time", ".", "parse", "(", "item", ".", "start", ".", "text!", ")", ",", ":feed", "=>", "feed", "}", "elsif", "item", ".", "type_attr", "==", "\"recurrent\"", "moments", "=", "parse_recurrent_date_item", "(", "item", ",", "n", ",", "start_time", ")", "moments", ".", "each", "do", "|", "moment", "|", "feeds", "<<", "{", ":time", "=>", "moment", ",", ":feed", "=>", "feed", "}", "end", "elsif", "item", ".", "type_attr", "==", "\"permanent\"", "start", "=", "Time", ".", "parse", "(", "item", ".", "start", ".", "text!", ")", "if", "start", ">", "start_time", "feeds", "<<", "{", ":time", "=>", "start", ",", ":feed", "=>", "feed", "}", "else", "feeds", "<<", "{", ":time", "=>", "start_time", ",", ":feed", "=>", "feed", "}", "end", "else", "raise", "DTD", "::", "InvalidValueError", ",", "\"the \\\"#{item.type_attr}\\\" is not valid for a date item type attribute\"", "end", "end", "end", "feeds", "=", "feeds", ".", "delete_if", "{", "|", "x", "|", "x", "[", ":time", "]", "<", "start_time", "}", "feeds", ".", "sort!", "{", "|", "x", ",", "y", "|", "x", "[", ":time", "]", "<=>", "y", "[", ":time", "]", "}", "return", "feeds", "[", "0", "..", "n", "-", "1", "]", "end" ]
Returns the next n events from the moment specified in the second optional argument. === Parameters [n = 10] how many coming events should be returned [start_time] only events hapenning after this time will be considered === Returns A list of hashes, sorted by event start time, each hash having two keys: [:time] start time of the event [:feed] feed describing the event
[ "Returns", "the", "next", "n", "events", "from", "the", "moment", "specified", "in", "the", "second", "optional", "argument", "." ]
25708228acd64e4abd0557e323f6e6adabf6e930
https://github.com/essfeed/ruby-ess/blob/25708228acd64e4abd0557e323f6e6adabf6e930/lib/ess/ess.rb#L26-L53
8,784
essfeed/ruby-ess
lib/ess/ess.rb
ESS.ESS.find_between
def find_between start_time, end_time feeds = [] channel.feed_list.each do |feed| feed.dates.item_list.each do |item| if item.type_attr == "standalone" feed_start_time = Time.parse(item.start.text!) if feed_start_time.between?(start_time, end_time) feeds << { :time => feed_start_time, :feed => feed } end elsif item.type_attr == "recurrent" moments = parse_recurrent_date_item(item, end_time, start_time) moments.each do |moment| if moment.between?(start_time, end_time) feeds << { :time => moment, :feed => feed } end end elsif item.type_attr == "permanent" start = Time.parse(item.start.text!) unless start > end_time if start > start_time feeds << { :time => start, :feed => feed } else feeds << { :time => start_time, :feed => feed } end end else raise DTD::InvalidValueError, "the \"#{item.type_attr}\" is not valid for a date item type attribute" end end end feeds.sort! { |x, y| x[:time] <=> y[:time] } end
ruby
def find_between start_time, end_time feeds = [] channel.feed_list.each do |feed| feed.dates.item_list.each do |item| if item.type_attr == "standalone" feed_start_time = Time.parse(item.start.text!) if feed_start_time.between?(start_time, end_time) feeds << { :time => feed_start_time, :feed => feed } end elsif item.type_attr == "recurrent" moments = parse_recurrent_date_item(item, end_time, start_time) moments.each do |moment| if moment.between?(start_time, end_time) feeds << { :time => moment, :feed => feed } end end elsif item.type_attr == "permanent" start = Time.parse(item.start.text!) unless start > end_time if start > start_time feeds << { :time => start, :feed => feed } else feeds << { :time => start_time, :feed => feed } end end else raise DTD::InvalidValueError, "the \"#{item.type_attr}\" is not valid for a date item type attribute" end end end feeds.sort! { |x, y| x[:time] <=> y[:time] } end
[ "def", "find_between", "start_time", ",", "end_time", "feeds", "=", "[", "]", "channel", ".", "feed_list", ".", "each", "do", "|", "feed", "|", "feed", ".", "dates", ".", "item_list", ".", "each", "do", "|", "item", "|", "if", "item", ".", "type_attr", "==", "\"standalone\"", "feed_start_time", "=", "Time", ".", "parse", "(", "item", ".", "start", ".", "text!", ")", "if", "feed_start_time", ".", "between?", "(", "start_time", ",", "end_time", ")", "feeds", "<<", "{", ":time", "=>", "feed_start_time", ",", ":feed", "=>", "feed", "}", "end", "elsif", "item", ".", "type_attr", "==", "\"recurrent\"", "moments", "=", "parse_recurrent_date_item", "(", "item", ",", "end_time", ",", "start_time", ")", "moments", ".", "each", "do", "|", "moment", "|", "if", "moment", ".", "between?", "(", "start_time", ",", "end_time", ")", "feeds", "<<", "{", ":time", "=>", "moment", ",", ":feed", "=>", "feed", "}", "end", "end", "elsif", "item", ".", "type_attr", "==", "\"permanent\"", "start", "=", "Time", ".", "parse", "(", "item", ".", "start", ".", "text!", ")", "unless", "start", ">", "end_time", "if", "start", ">", "start_time", "feeds", "<<", "{", ":time", "=>", "start", ",", ":feed", "=>", "feed", "}", "else", "feeds", "<<", "{", ":time", "=>", "start_time", ",", ":feed", "=>", "feed", "}", "end", "end", "else", "raise", "DTD", "::", "InvalidValueError", ",", "\"the \\\"#{item.type_attr}\\\" is not valid for a date item type attribute\"", "end", "end", "end", "feeds", ".", "sort!", "{", "|", "x", ",", "y", "|", "x", "[", ":time", "]", "<=>", "y", "[", ":time", "]", "}", "end" ]
Returns all events starting after the time specified by the first parameter and before the time specified by the second parameter, which accept regular Time objects. === Parameters [start_time] will return only events starting after this moment [end_time] will return only events starting before this moment === Returns A list of hashes, sorted by event start time, each hash having two keys: [:time] start time of the event [:feed] feed describing the event
[ "Returns", "all", "events", "starting", "after", "the", "time", "specified", "by", "the", "first", "parameter", "and", "before", "the", "time", "specified", "by", "the", "second", "parameter", "which", "accept", "regular", "Time", "objects", "." ]
25708228acd64e4abd0557e323f6e6adabf6e930
https://github.com/essfeed/ruby-ess/blob/25708228acd64e4abd0557e323f6e6adabf6e930/lib/ess/ess.rb#L73-L104
8,785
mochnatiy/flexible_accessibility
lib/flexible_accessibility/filters.rb
FlexibleAccessibility.Filters.check_permission_to_route
def check_permission_to_route route_provider = RouteProvider.new(self.class) if route_provider.verifiable_routes_list.include?(current_action) if logged_user.nil? raise UserNotLoggedInException.new(current_route, nil) end is_permitted = AccessProvider.action_permitted_for_user?( current_route, logged_user ) is_permitted ? allow_route : deny_route elsif route_provider.non_verifiable_routes_list.include?(current_action) allow_route else deny_route end end
ruby
def check_permission_to_route route_provider = RouteProvider.new(self.class) if route_provider.verifiable_routes_list.include?(current_action) if logged_user.nil? raise UserNotLoggedInException.new(current_route, nil) end is_permitted = AccessProvider.action_permitted_for_user?( current_route, logged_user ) is_permitted ? allow_route : deny_route elsif route_provider.non_verifiable_routes_list.include?(current_action) allow_route else deny_route end end
[ "def", "check_permission_to_route", "route_provider", "=", "RouteProvider", ".", "new", "(", "self", ".", "class", ")", "if", "route_provider", ".", "verifiable_routes_list", ".", "include?", "(", "current_action", ")", "if", "logged_user", ".", "nil?", "raise", "UserNotLoggedInException", ".", "new", "(", "current_route", ",", "nil", ")", "end", "is_permitted", "=", "AccessProvider", ".", "action_permitted_for_user?", "(", "current_route", ",", "logged_user", ")", "is_permitted", "?", "allow_route", ":", "deny_route", "elsif", "route_provider", ".", "non_verifiable_routes_list", ".", "include?", "(", "current_action", ")", "allow_route", "else", "deny_route", "end", "end" ]
Check access to route and we expected the existing of current_user helper
[ "Check", "access", "to", "route", "and", "we", "expected", "the", "existing", "of", "current_user", "helper" ]
ffd7f76e0765aa28909625b3bfa282264b8a5195
https://github.com/mochnatiy/flexible_accessibility/blob/ffd7f76e0765aa28909625b3bfa282264b8a5195/lib/flexible_accessibility/filters.rb#L41-L59
8,786
bogrobotten/fetch
lib/fetch/base.rb
Fetch.Base.fetch
def fetch requests = instantiate_modules.select(&:fetch?).map(&:requests).flatten total, done = requests.size, 0 update_progress(total, done) before_fetch backend.new(requests).run do update_progress(total, done += 1) end after_fetch true rescue => e error(e) raise e end
ruby
def fetch requests = instantiate_modules.select(&:fetch?).map(&:requests).flatten total, done = requests.size, 0 update_progress(total, done) before_fetch backend.new(requests).run do update_progress(total, done += 1) end after_fetch true rescue => e error(e) raise e end
[ "def", "fetch", "requests", "=", "instantiate_modules", ".", "select", "(", ":fetch?", ")", ".", "map", "(", ":requests", ")", ".", "flatten", "total", ",", "done", "=", "requests", ".", "size", ",", "0", "update_progress", "(", "total", ",", "done", ")", "before_fetch", "backend", ".", "new", "(", "requests", ")", ".", "run", "do", "update_progress", "(", "total", ",", "done", "+=", "1", ")", "end", "after_fetch", "true", "rescue", "=>", "e", "error", "(", "e", ")", "raise", "e", "end" ]
Begin fetching. Will run synchronous fetches first and async fetches afterwards. Updates progress when each module finishes its fetch.
[ "Begin", "fetching", ".", "Will", "run", "synchronous", "fetches", "first", "and", "async", "fetches", "afterwards", ".", "Updates", "progress", "when", "each", "module", "finishes", "its", "fetch", "." ]
8a9e1fb42ed0719dd7b4d1a965d11b0f5decca4f
https://github.com/bogrobotten/fetch/blob/8a9e1fb42ed0719dd7b4d1a965d11b0f5decca4f/lib/fetch/base.rb#L35-L53
8,787
bogrobotten/fetch
lib/fetch/base.rb
Fetch.Base.instantiate_modules
def instantiate_modules mods = Array(modules) mods = load!(mods) if callback?(:load) Array(mods).map do |klass| init!(klass) || klass.new(fetchable) end end
ruby
def instantiate_modules mods = Array(modules) mods = load!(mods) if callback?(:load) Array(mods).map do |klass| init!(klass) || klass.new(fetchable) end end
[ "def", "instantiate_modules", "mods", "=", "Array", "(", "modules", ")", "mods", "=", "load!", "(", "mods", ")", "if", "callback?", "(", ":load", ")", "Array", "(", "mods", ")", ".", "map", "do", "|", "klass", "|", "init!", "(", "klass", ")", "||", "klass", ".", "new", "(", "fetchable", ")", "end", "end" ]
Array of instantiated fetch modules.
[ "Array", "of", "instantiated", "fetch", "modules", "." ]
8a9e1fb42ed0719dd7b4d1a965d11b0f5decca4f
https://github.com/bogrobotten/fetch/blob/8a9e1fb42ed0719dd7b4d1a965d11b0f5decca4f/lib/fetch/base.rb#L61-L67
8,788
bogrobotten/fetch
lib/fetch/base.rb
Fetch.Base.update_progress
def update_progress(total, done) percentage = total.zero? ? 100 : ((done.to_f / total) * 100).to_i progress(percentage) end
ruby
def update_progress(total, done) percentage = total.zero? ? 100 : ((done.to_f / total) * 100).to_i progress(percentage) end
[ "def", "update_progress", "(", "total", ",", "done", ")", "percentage", "=", "total", ".", "zero?", "?", "100", ":", "(", "(", "done", ".", "to_f", "/", "total", ")", "*", "100", ")", ".", "to_i", "progress", "(", "percentage", ")", "end" ]
Updates progress with a percentage calculated from +total+ and +done+.
[ "Updates", "progress", "with", "a", "percentage", "calculated", "from", "+", "total", "+", "and", "+", "done", "+", "." ]
8a9e1fb42ed0719dd7b4d1a965d11b0f5decca4f
https://github.com/bogrobotten/fetch/blob/8a9e1fb42ed0719dd7b4d1a965d11b0f5decca4f/lib/fetch/base.rb#L70-L73
8,789
Velir/kaltura_fu
lib/kaltura_fu/session.rb
KalturaFu.Session.generate_session_key
def generate_session_key self.check_for_client_session raise "Missing Administrator Secret" unless KalturaFu.config.administrator_secret @@session_key = @@client.session_service.start(KalturaFu.config.administrator_secret,'',Kaltura::Constants::SessionType::ADMIN) @@client.ks = @@session_key rescue Kaltura::APIError => e puts e.message end
ruby
def generate_session_key self.check_for_client_session raise "Missing Administrator Secret" unless KalturaFu.config.administrator_secret @@session_key = @@client.session_service.start(KalturaFu.config.administrator_secret,'',Kaltura::Constants::SessionType::ADMIN) @@client.ks = @@session_key rescue Kaltura::APIError => e puts e.message end
[ "def", "generate_session_key", "self", ".", "check_for_client_session", "raise", "\"Missing Administrator Secret\"", "unless", "KalturaFu", ".", "config", ".", "administrator_secret", "@@session_key", "=", "@@client", ".", "session_service", ".", "start", "(", "KalturaFu", ".", "config", ".", "administrator_secret", ",", "''", ",", "Kaltura", "::", "Constants", "::", "SessionType", "::", "ADMIN", ")", "@@client", ".", "ks", "=", "@@session_key", "rescue", "Kaltura", "::", "APIError", "=>", "e", "puts", "e", ".", "message", "end" ]
Generates a Kaltura ks and adds it to the KalturaFu client object. @return [String] a Kaltura KS.
[ "Generates", "a", "Kaltura", "ks", "and", "adds", "it", "to", "the", "KalturaFu", "client", "object", "." ]
539e476786d1fd2257b90dfb1e50c2c75ae75bdd
https://github.com/Velir/kaltura_fu/blob/539e476786d1fd2257b90dfb1e50c2c75ae75bdd/lib/kaltura_fu/session.rb#L54-L62
8,790
hexorx/oxmlk
lib/oxmlk/attr.rb
OxMlk.Attr.from_xml
def from_xml(data) procs.inject(XML::Node.from(data)[tag]) {|d,p| p.call(d) rescue d} end
ruby
def from_xml(data) procs.inject(XML::Node.from(data)[tag]) {|d,p| p.call(d) rescue d} end
[ "def", "from_xml", "(", "data", ")", "procs", ".", "inject", "(", "XML", "::", "Node", ".", "from", "(", "data", ")", "[", "tag", "]", ")", "{", "|", "d", ",", "p", "|", "p", ".", "call", "(", "d", ")", "rescue", "d", "}", "end" ]
Creates a new instance of Attr to be used as a template for converting XML to objects and from objects to XML @param [Symbol,String] name Sets the accessor methods for this attr. It is also used to guess defaults for :from and :as. For example if it ends with '?' and :as isn't set it will treat it as a boolean. @param [Hash] o the options for the new attr definition @option o [Symbol,String] :from (tag_proc.call(name)) Tells OxMlk what the name of the XML attribute is. It defaults to name processed by the tag_proc. @option o [Symbol,String,Proc,Array<Symbol,String,Proc>] :as Tells OxMlk how to translate the XML. The argument is coerced into a Proc and applied to the string found in the XML attribute. If an Array is passed each Proc is applied in order with the results of the first being passed to the second and so on. If it isn't set and name ends in '?' it processes it as if :bool was passed otherwise it treats it as a string with no processing. Includes the following named Procs: Integer, Float, String, Symbol and :bool. @option o [Proc] :tag_proc (proc {|x| x}) Proc used to guess :from. The Proc is applied to name and the results used to find the XML attribute if :from isn't set. @yield [String] Adds anothe Proc that is applied to the value. Finds @tag in data and applies procs.
[ "Creates", "a", "new", "instance", "of", "Attr", "to", "be", "used", "as", "a", "template", "for", "converting", "XML", "to", "objects", "and", "from", "objects", "to", "XML" ]
bf4be00ece9b13a3357d8eb324e2a571d2715f79
https://github.com/hexorx/oxmlk/blob/bf4be00ece9b13a3357d8eb324e2a571d2715f79/lib/oxmlk/attr.rb#L48-L50
8,791
erniebrodeur/bini
lib/bini/optparser.rb
Bini.OptionParser.mash
def mash(h) h.merge! @options @options.clear h.each {|k,v| self[k] = v} end
ruby
def mash(h) h.merge! @options @options.clear h.each {|k,v| self[k] = v} end
[ "def", "mash", "(", "h", ")", "h", ".", "merge!", "@options", "@options", ".", "clear", "h", ".", "each", "{", "|", "k", ",", "v", "|", "self", "[", "k", "]", "=", "v", "}", "end" ]
merge takes in a set of values and overwrites the previous values. mash does this in reverse.
[ "merge", "takes", "in", "a", "set", "of", "values", "and", "overwrites", "the", "previous", "values", ".", "mash", "does", "this", "in", "reverse", "." ]
4bcc1a90e877c7e77fcf97d4bf91b894d6824a2b
https://github.com/erniebrodeur/bini/blob/4bcc1a90e877c7e77fcf97d4bf91b894d6824a2b/lib/bini/optparser.rb#L47-L51
8,792
nicholas-johnson/content_driven
lib/content_driven/routes.rb
ContentDriven.Routes.content_for
def content_for route parts = route.split("/").delete_if &:empty? content = parts.inject(self) do |page, part| page.children[part.to_sym] if page end content end
ruby
def content_for route parts = route.split("/").delete_if &:empty? content = parts.inject(self) do |page, part| page.children[part.to_sym] if page end content end
[ "def", "content_for", "route", "parts", "=", "route", ".", "split", "(", "\"/\"", ")", ".", "delete_if", ":empty?", "content", "=", "parts", ".", "inject", "(", "self", ")", "do", "|", "page", ",", "part", "|", "page", ".", "children", "[", "part", ".", "to_sym", "]", "if", "page", "end", "content", "end" ]
Walks the tree based on a url and returns the requested page Will return nil if the page does not exist
[ "Walks", "the", "tree", "based", "on", "a", "url", "and", "returns", "the", "requested", "page", "Will", "return", "nil", "if", "the", "page", "does", "not", "exist" ]
ac362677810e45d95ce21975fed841d3d65f11d7
https://github.com/nicholas-johnson/content_driven/blob/ac362677810e45d95ce21975fed841d3d65f11d7/lib/content_driven/routes.rb#L5-L11
8,793
checkdin/checkdin-ruby
lib/checkdin/won_rewards.rb
Checkdin.WonRewards.won_rewards
def won_rewards(options={}) response = connection.get do |req| req.url "won_rewards", options end return_error_or_body(response) end
ruby
def won_rewards(options={}) response = connection.get do |req| req.url "won_rewards", options end return_error_or_body(response) end
[ "def", "won_rewards", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"won_rewards\"", ",", "options", "end", "return_error_or_body", "(", "response", ")", "end" ]
Get a list of all won rewards for the authenticating client. @param [Hash] options @option options Integer :campaign_id - Only return won rewards for this campaign. @option options Integer :user_id - Only return won rewards for this user. @option options Integer :promotion_id - Only return won rewards for this promotion. @option options Integer :limit - The maximum number of records to return.
[ "Get", "a", "list", "of", "all", "won", "rewards", "for", "the", "authenticating", "client", "." ]
c3c4b38b0f8c710e1f805100dcf3a70649215b48
https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/won_rewards.rb#L21-L26
8,794
octoai/gem-octocore-cassandra
lib/octocore-cassandra/models/enterprise/authorization.rb
Octo.Authorization.generate_password
def generate_password if(self.password.nil?) self.password = Digest::SHA1.hexdigest(self.username + self.enterprise_id) else self.password = Digest::SHA1.hexdigest(self.password + self.enterprise_id) end end
ruby
def generate_password if(self.password.nil?) self.password = Digest::SHA1.hexdigest(self.username + self.enterprise_id) else self.password = Digest::SHA1.hexdigest(self.password + self.enterprise_id) end end
[ "def", "generate_password", "if", "(", "self", ".", "password", ".", "nil?", ")", "self", ".", "password", "=", "Digest", "::", "SHA1", ".", "hexdigest", "(", "self", ".", "username", "+", "self", ".", "enterprise_id", ")", "else", "self", ".", "password", "=", "Digest", "::", "SHA1", ".", "hexdigest", "(", "self", ".", "password", "+", "self", ".", "enterprise_id", ")", "end", "end" ]
Check or Generate client password
[ "Check", "or", "Generate", "client", "password" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/models/enterprise/authorization.rb#L35-L41
8,795
octoai/gem-octocore-cassandra
lib/octocore-cassandra/models/enterprise/authorization.rb
Octo.Authorization.kong_requests
def kong_requests kong_config = Octo.get_config :kong if kong_config[:enabled] url = '/consumers/' payload = { username: self.username, custom_id: self.enterprise_id } process_kong_request(url, :PUT, payload) create_keyauth( self.username, self.apikey) end end
ruby
def kong_requests kong_config = Octo.get_config :kong if kong_config[:enabled] url = '/consumers/' payload = { username: self.username, custom_id: self.enterprise_id } process_kong_request(url, :PUT, payload) create_keyauth( self.username, self.apikey) end end
[ "def", "kong_requests", "kong_config", "=", "Octo", ".", "get_config", ":kong", "if", "kong_config", "[", ":enabled", "]", "url", "=", "'/consumers/'", "payload", "=", "{", "username", ":", "self", ".", "username", ",", "custom_id", ":", "self", ".", "enterprise_id", "}", "process_kong_request", "(", "url", ",", ":PUT", ",", "payload", ")", "create_keyauth", "(", "self", ".", "username", ",", "self", ".", "apikey", ")", "end", "end" ]
Perform Kong Operations after creating client
[ "Perform", "Kong", "Operations", "after", "creating", "client" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/models/enterprise/authorization.rb#L44-L56
8,796
redding/ns-options
lib/ns-options/proxy.rb
NsOptions::Proxy.ProxyMethods.option
def option(name, *args, &block) __proxy_options__.option(name, *args, &block) NsOptions::ProxyMethod.new(self, name, 'an option').define($stdout, caller) end
ruby
def option(name, *args, &block) __proxy_options__.option(name, *args, &block) NsOptions::ProxyMethod.new(self, name, 'an option').define($stdout, caller) end
[ "def", "option", "(", "name", ",", "*", "args", ",", "&", "block", ")", "__proxy_options__", ".", "option", "(", "name", ",", "args", ",", "block", ")", "NsOptions", "::", "ProxyMethod", ".", "new", "(", "self", ",", "name", ",", "'an option'", ")", ".", "define", "(", "$stdout", ",", "caller", ")", "end" ]
pass thru namespace methods to the proxied NAMESPACE handler
[ "pass", "thru", "namespace", "methods", "to", "the", "proxied", "NAMESPACE", "handler" ]
63618a18e7a1d270dffc5a3cfea70ef45569e061
https://github.com/redding/ns-options/blob/63618a18e7a1d270dffc5a3cfea70ef45569e061/lib/ns-options/proxy.rb#L78-L81
8,797
redding/ns-options
lib/ns-options/proxy.rb
NsOptions::Proxy.ProxyMethods.method_missing
def method_missing(meth, *args, &block) if (po = __proxy_options__) && po.respond_to?(meth.to_s) po.send(meth.to_s, *args, &block) else super end end
ruby
def method_missing(meth, *args, &block) if (po = __proxy_options__) && po.respond_to?(meth.to_s) po.send(meth.to_s, *args, &block) else super end end
[ "def", "method_missing", "(", "meth", ",", "*", "args", ",", "&", "block", ")", "if", "(", "po", "=", "__proxy_options__", ")", "&&", "po", ".", "respond_to?", "(", "meth", ".", "to_s", ")", "po", ".", "send", "(", "meth", ".", "to_s", ",", "args", ",", "block", ")", "else", "super", "end", "end" ]
for everything else, send to the proxied NAMESPACE handler at this point it really just enables dynamic options writers
[ "for", "everything", "else", "send", "to", "the", "proxied", "NAMESPACE", "handler", "at", "this", "point", "it", "really", "just", "enables", "dynamic", "options", "writers" ]
63618a18e7a1d270dffc5a3cfea70ef45569e061
https://github.com/redding/ns-options/blob/63618a18e7a1d270dffc5a3cfea70ef45569e061/lib/ns-options/proxy.rb#L110-L116
8,798
Ptico/sequoia
lib/sequoia/configurable.rb
Sequoia.Configurable.configure
def configure(env=:default, &block) environment = config_attributes[env.to_sym] Builder.new(environment, &block) end
ruby
def configure(env=:default, &block) environment = config_attributes[env.to_sym] Builder.new(environment, &block) end
[ "def", "configure", "(", "env", "=", ":default", ",", "&", "block", ")", "environment", "=", "config_attributes", "[", "env", ".", "to_sym", "]", "Builder", ".", "new", "(", "environment", ",", "block", ")", "end" ]
Add or merge environment configuration Params: - env {Symbol} Environment to set (optional, default: :default) Yields: block with key-value definitions Returns: {Sequoia::Builder} builder instance
[ "Add", "or", "merge", "environment", "configuration" ]
d3645d8bedd27eb0149928c09678d12c4082c787
https://github.com/Ptico/sequoia/blob/d3645d8bedd27eb0149928c09678d12c4082c787/lib/sequoia/configurable.rb#L19-L23
8,799
Ptico/sequoia
lib/sequoia/configurable.rb
Sequoia.Configurable.build_configuration
def build_configuration(env=nil) result = config_attributes[:default] result.deep_merge!(config_attributes[env.to_sym]) if env Entity.create(result) end
ruby
def build_configuration(env=nil) result = config_attributes[:default] result.deep_merge!(config_attributes[env.to_sym]) if env Entity.create(result) end
[ "def", "build_configuration", "(", "env", "=", "nil", ")", "result", "=", "config_attributes", "[", ":default", "]", "result", ".", "deep_merge!", "(", "config_attributes", "[", "env", ".", "to_sym", "]", ")", "if", "env", "Entity", ".", "create", "(", "result", ")", "end" ]
Build configuration object Params: - env {Symbol} Environment to build Returns: {Sequoia::Entity} builded configuration object
[ "Build", "configuration", "object" ]
d3645d8bedd27eb0149928c09678d12c4082c787
https://github.com/Ptico/sequoia/blob/d3645d8bedd27eb0149928c09678d12c4082c787/lib/sequoia/configurable.rb#L33-L37