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
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
messagemedia/messages-ruby-sdk
lib/message_media_messages/http/faraday_client.rb
MessageMediaMessages.FaradayClient.convert_response
def convert_response(response) HttpResponse.new(response.status, response.headers, response.body) end
ruby
def convert_response(response) HttpResponse.new(response.status, response.headers, response.body) end
[ "def", "convert_response", "(", "response", ")", "HttpResponse", ".", "new", "(", "response", ".", "status", ",", "response", ".", "headers", ",", "response", ".", "body", ")", "end" ]
Method overridden from HttpClient.
[ "Method", "overridden", "from", "HttpClient", "." ]
073f1f7ca5e4ff3df51b8eeafeaae2167ec6f311
https://github.com/messagemedia/messages-ruby-sdk/blob/073f1f7ca5e4ff3df51b8eeafeaae2167ec6f311/lib/message_media_messages/http/faraday_client.rb#L58-L60
train
dalpo/rails_admin_clone
lib/rails_admin_clone/model_cloner.rb
RailsAdminClone.ModelCloner.clone_object
def clone_object(old_object) object = build_from(old_object) assign_attributes_for(object, get_model_attributes_from(old_object)) object end
ruby
def clone_object(old_object) object = build_from(old_object) assign_attributes_for(object, get_model_attributes_from(old_object)) object end
[ "def", "clone_object", "(", "old_object", ")", "object", "=", "build_from", "(", "old_object", ")", "assign_attributes_for", "(", "object", ",", "get_model_attributes_from", "(", "old_object", ")", ")", "object", "end" ]
clone object without associations
[ "clone", "object", "without", "associations" ]
a56f005af9833fc1c7071a777f20ea154320ca72
https://github.com/dalpo/rails_admin_clone/blob/a56f005af9833fc1c7071a777f20ea154320ca72/lib/rails_admin_clone/model_cloner.rb#L82-L87
train
dalpo/rails_admin_clone
lib/rails_admin_clone/model_cloner.rb
RailsAdminClone.ModelCloner.clone_has_one
def clone_has_one(old_object, new_object) old_object.class.reflect_on_all_associations(:has_one).each do |association| old_association = old_object.send(association.name) build_has_one(new_object, association, old_association) if build_has_one?(old_object, association) end new_object end
ruby
def clone_has_one(old_object, new_object) old_object.class.reflect_on_all_associations(:has_one).each do |association| old_association = old_object.send(association.name) build_has_one(new_object, association, old_association) if build_has_one?(old_object, association) end new_object end
[ "def", "clone_has_one", "(", "old_object", ",", "new_object", ")", "old_object", ".", "class", ".", "reflect_on_all_associations", "(", ":has_one", ")", ".", "each", "do", "|", "association", "|", "old_association", "=", "old_object", ".", "send", "(", "association", ".", "name", ")", "build_has_one", "(", "new_object", ",", "association", ",", "old_association", ")", "if", "build_has_one?", "(", "old_object", ",", "association", ")", "end", "new_object", "end" ]
clone has_one associations
[ "clone", "has_one", "associations" ]
a56f005af9833fc1c7071a777f20ea154320ca72
https://github.com/dalpo/rails_admin_clone/blob/a56f005af9833fc1c7071a777f20ea154320ca72/lib/rails_admin_clone/model_cloner.rb#L90-L97
train
dalpo/rails_admin_clone
lib/rails_admin_clone/model_cloner.rb
RailsAdminClone.ModelCloner.clone_has_many
def clone_has_many(old_object, new_object) associations = old_object.class.reflect_on_all_associations(:has_many) .select{|a| !a.options.keys.include?(:through)} associations.each do |association| old_object.send(association.name).each do |old_association| new_object.send(association.name).build.tap do |new_association| assign_association(association, old_association, new_association) end end end new_object end
ruby
def clone_has_many(old_object, new_object) associations = old_object.class.reflect_on_all_associations(:has_many) .select{|a| !a.options.keys.include?(:through)} associations.each do |association| old_object.send(association.name).each do |old_association| new_object.send(association.name).build.tap do |new_association| assign_association(association, old_association, new_association) end end end new_object end
[ "def", "clone_has_many", "(", "old_object", ",", "new_object", ")", "associations", "=", "old_object", ".", "class", ".", "reflect_on_all_associations", "(", ":has_many", ")", ".", "select", "{", "|", "a", "|", "!", "a", ".", "options", ".", "keys", ".", "include?", "(", ":through", ")", "}", "associations", ".", "each", "do", "|", "association", "|", "old_object", ".", "send", "(", "association", ".", "name", ")", ".", "each", "do", "|", "old_association", "|", "new_object", ".", "send", "(", "association", ".", "name", ")", ".", "build", ".", "tap", "do", "|", "new_association", "|", "assign_association", "(", "association", ",", "old_association", ",", "new_association", ")", "end", "end", "end", "new_object", "end" ]
clone has_many associations
[ "clone", "has_many", "associations" ]
a56f005af9833fc1c7071a777f20ea154320ca72
https://github.com/dalpo/rails_admin_clone/blob/a56f005af9833fc1c7071a777f20ea154320ca72/lib/rails_admin_clone/model_cloner.rb#L110-L123
train
jkotests/watir-nokogiri
lib/watir-nokogiri/elements/button.rb
WatirNokogiri.Button.text
def text assert_exists tn = @element.node_name.downcase case tn when 'input' @element.get_attribute(:value) when 'button' @element.text else raise Exception::Error, "unknown tag name for button: #{tn}" end end
ruby
def text assert_exists tn = @element.node_name.downcase case tn when 'input' @element.get_attribute(:value) when 'button' @element.text else raise Exception::Error, "unknown tag name for button: #{tn}" end end
[ "def", "text", "assert_exists", "tn", "=", "@element", ".", "node_name", ".", "downcase", "case", "tn", "when", "'input'", "@element", ".", "get_attribute", "(", ":value", ")", "when", "'button'", "@element", ".", "text", "else", "raise", "Exception", "::", "Error", ",", "\"unknown tag name for button: #{tn}\"", "end", "end" ]
Returns the text of the button. For input elements, returns the "value" attribute. For button elements, returns the inner text. @return [String]
[ "Returns", "the", "text", "of", "the", "button", "." ]
32c783730bda83dfbeb97a78d7a21788bd726815
https://github.com/jkotests/watir-nokogiri/blob/32c783730bda83dfbeb97a78d7a21788bd726815/lib/watir-nokogiri/elements/button.rb#L26-L39
train
gupta-ankit/fitgem_oauth2
lib/fitgem_oauth2/activity.rb
FitgemOauth2.Client.intraday_activity_time_series
def intraday_activity_time_series(resource: nil, start_date: nil, end_date: nil, detail_level: nil, start_time: nil, end_time: nil) # converting to symbol to allow developer to use either 'calories' or :calories resource = resource.to_sym unless %i[calories steps distance floors elevation].include?(resource) raise FitgemOauth2::InvalidArgumentError, 'Must specify resource to fetch intraday time series data for.'\ ' One of (:calories, :steps, :distance, :floors, or :elevation) is required.' end unless start_date raise FitgemOauth2::InvalidArgumentError, 'Must specify the start_date to fetch intraday time series data' end end_date ||= '1d' unless detail_level && %w(1min 15min).include?(detail_level) raise FitgemOauth2::InvalidArgumentError, 'Must specify the data resolution to fetch intraday time series data for.'\ ' One of (\"1d\" or \"15min\") is required.' end resource_path = [ 'user', @user_id, 'activities', resource, 'date', format_date(start_date), end_date, detail_level ].join('/') if start_time || end_time resource_path = [resource_path, 'time', format_time(start_time), format_time(end_time)].join('/') end get_call("#{resource_path}.json") end
ruby
def intraday_activity_time_series(resource: nil, start_date: nil, end_date: nil, detail_level: nil, start_time: nil, end_time: nil) # converting to symbol to allow developer to use either 'calories' or :calories resource = resource.to_sym unless %i[calories steps distance floors elevation].include?(resource) raise FitgemOauth2::InvalidArgumentError, 'Must specify resource to fetch intraday time series data for.'\ ' One of (:calories, :steps, :distance, :floors, or :elevation) is required.' end unless start_date raise FitgemOauth2::InvalidArgumentError, 'Must specify the start_date to fetch intraday time series data' end end_date ||= '1d' unless detail_level && %w(1min 15min).include?(detail_level) raise FitgemOauth2::InvalidArgumentError, 'Must specify the data resolution to fetch intraday time series data for.'\ ' One of (\"1d\" or \"15min\") is required.' end resource_path = [ 'user', @user_id, 'activities', resource, 'date', format_date(start_date), end_date, detail_level ].join('/') if start_time || end_time resource_path = [resource_path, 'time', format_time(start_time), format_time(end_time)].join('/') end get_call("#{resource_path}.json") end
[ "def", "intraday_activity_time_series", "(", "resource", ":", "nil", ",", "start_date", ":", "nil", ",", "end_date", ":", "nil", ",", "detail_level", ":", "nil", ",", "start_time", ":", "nil", ",", "end_time", ":", "nil", ")", "resource", "=", "resource", ".", "to_sym", "unless", "%i[", "calories", "steps", "distance", "floors", "elevation", "]", ".", "include?", "(", "resource", ")", "raise", "FitgemOauth2", "::", "InvalidArgumentError", ",", "'Must specify resource to fetch intraday time series data for.'", "' One of (:calories, :steps, :distance, :floors, or :elevation) is required.'", "end", "unless", "start_date", "raise", "FitgemOauth2", "::", "InvalidArgumentError", ",", "'Must specify the start_date to fetch intraday time series data'", "end", "end_date", "||=", "'1d'", "unless", "detail_level", "&&", "%w(", "1min", "15min", ")", ".", "include?", "(", "detail_level", ")", "raise", "FitgemOauth2", "::", "InvalidArgumentError", ",", "'Must specify the data resolution to fetch intraday time series data for.'", "' One of (\\\"1d\\\" or \\\"15min\\\") is required.'", "end", "resource_path", "=", "[", "'user'", ",", "@user_id", ",", "'activities'", ",", "resource", ",", "'date'", ",", "format_date", "(", "start_date", ")", ",", "end_date", ",", "detail_level", "]", ".", "join", "(", "'/'", ")", "if", "start_time", "||", "end_time", "resource_path", "=", "[", "resource_path", ",", "'time'", ",", "format_time", "(", "start_time", ")", ",", "format_time", "(", "end_time", ")", "]", ".", "join", "(", "'/'", ")", "end", "get_call", "(", "\"#{resource_path}.json\"", ")", "end" ]
retrieves intraday activity time series. @param resource (required) for which the intrady series is retrieved. one of 'calories', 'steps', 'distance', 'floors', 'elevation' @param start_date (required) start date for the series @param end_date (optional) end date for the series, if not specified, the series is for 1 day @param detail_level (required) level of detail for the series @param start_time (optional)start time for the series @param end_time the (optional)end time for the series. specify both start_time and end_time, if using either
[ "retrieves", "intraday", "activity", "time", "series", "." ]
10caf154d351dcef54442d9092c445cd388ad09e
https://github.com/gupta-ankit/fitgem_oauth2/blob/10caf154d351dcef54442d9092c445cd388ad09e/lib/fitgem_oauth2/activity.rb#L62-L99
train
gupta-ankit/fitgem_oauth2
lib/fitgem_oauth2/activity.rb
FitgemOauth2.Client.activity_list
def activity_list(date, sort, limit) date_param = format_date(date) if sort == "asc" date_param = "afterDate=#{date_param}" elsif sort == "desc" date_param = "beforeDate=#{date_param}" else raise FitgemOauth2::InvalidArgumentError, "sort can either be asc or desc" end get_call("user/#{user_id}/activities/list.json?offset=0&limit=#{limit}&sort=#{sort}&#{date_param}") end
ruby
def activity_list(date, sort, limit) date_param = format_date(date) if sort == "asc" date_param = "afterDate=#{date_param}" elsif sort == "desc" date_param = "beforeDate=#{date_param}" else raise FitgemOauth2::InvalidArgumentError, "sort can either be asc or desc" end get_call("user/#{user_id}/activities/list.json?offset=0&limit=#{limit}&sort=#{sort}&#{date_param}") end
[ "def", "activity_list", "(", "date", ",", "sort", ",", "limit", ")", "date_param", "=", "format_date", "(", "date", ")", "if", "sort", "==", "\"asc\"", "date_param", "=", "\"afterDate=#{date_param}\"", "elsif", "sort", "==", "\"desc\"", "date_param", "=", "\"beforeDate=#{date_param}\"", "else", "raise", "FitgemOauth2", "::", "InvalidArgumentError", ",", "\"sort can either be asc or desc\"", "end", "get_call", "(", "\"user/#{user_id}/activities/list.json?offset=0&limit=#{limit}&sort=#{sort}&#{date_param}\"", ")", "end" ]
retrieves activity list for the user
[ "retrieves", "activity", "list", "for", "the", "user" ]
10caf154d351dcef54442d9092c445cd388ad09e
https://github.com/gupta-ankit/fitgem_oauth2/blob/10caf154d351dcef54442d9092c445cd388ad09e/lib/fitgem_oauth2/activity.rb#L119-L129
train
gupta-ankit/fitgem_oauth2
lib/fitgem_oauth2/activity.rb
FitgemOauth2.Client.update_activity_goals
def update_activity_goals(period, params) unless period && %w(daily weekly).include?(period) raise FitgemOauth2::InvalidArgumentError, "Goal period should either be 'daily' or 'weekly'" end post_call("user/#{user_id}/activities/goals/#{period}.json", params) end
ruby
def update_activity_goals(period, params) unless period && %w(daily weekly).include?(period) raise FitgemOauth2::InvalidArgumentError, "Goal period should either be 'daily' or 'weekly'" end post_call("user/#{user_id}/activities/goals/#{period}.json", params) end
[ "def", "update_activity_goals", "(", "period", ",", "params", ")", "unless", "period", "&&", "%w(", "daily", "weekly", ")", ".", "include?", "(", "period", ")", "raise", "FitgemOauth2", "::", "InvalidArgumentError", ",", "\"Goal period should either be 'daily' or 'weekly'\"", "end", "post_call", "(", "\"user/#{user_id}/activities/goals/#{period}.json\"", ",", "params", ")", "end" ]
update activity goals @param period period for the goal ('weekly' or 'daily') @param params the POST params for the request. Refer to Fitbit documentation for accepted format
[ "update", "activity", "goals" ]
10caf154d351dcef54442d9092c445cd388ad09e
https://github.com/gupta-ankit/fitgem_oauth2/blob/10caf154d351dcef54442d9092c445cd388ad09e/lib/fitgem_oauth2/activity.rb#L197-L202
train
gupta-ankit/fitgem_oauth2
lib/fitgem_oauth2/sleep.rb
FitgemOauth2.Client.sleep_time_series
def sleep_time_series(resource: nil, start_date: nil, end_date: nil, period: nil) unless start_date raise FitgemOauth2::InvalidArgumentError, 'Start date not provided.' end unless resource && SLEEP_RESOURCES.include?(resource) raise FitgemOauth2::InvalidArgumentError, "Invalid resource: #{resource}. Valid resources are #{SLEEP_RESOURCES}." end if period && end_date raise FitgemOauth2::InvalidArgumentError, 'Both end_date and period specified. Specify only one.' end if period && !SLEEP_PERIODS.include?(period) raise FitgemOauth2::InvalidArgumentError, "Invalid period: #{period}. Valid periods are #{SLEEP_PERIODS}." end second = period || format_date(end_date) url = ['user', user_id, 'sleep', resource, 'date', format_date(start_date), second].join('/') get_call(url + '.json') end
ruby
def sleep_time_series(resource: nil, start_date: nil, end_date: nil, period: nil) unless start_date raise FitgemOauth2::InvalidArgumentError, 'Start date not provided.' end unless resource && SLEEP_RESOURCES.include?(resource) raise FitgemOauth2::InvalidArgumentError, "Invalid resource: #{resource}. Valid resources are #{SLEEP_RESOURCES}." end if period && end_date raise FitgemOauth2::InvalidArgumentError, 'Both end_date and period specified. Specify only one.' end if period && !SLEEP_PERIODS.include?(period) raise FitgemOauth2::InvalidArgumentError, "Invalid period: #{period}. Valid periods are #{SLEEP_PERIODS}." end second = period || format_date(end_date) url = ['user', user_id, 'sleep', resource, 'date', format_date(start_date), second].join('/') get_call(url + '.json') end
[ "def", "sleep_time_series", "(", "resource", ":", "nil", ",", "start_date", ":", "nil", ",", "end_date", ":", "nil", ",", "period", ":", "nil", ")", "unless", "start_date", "raise", "FitgemOauth2", "::", "InvalidArgumentError", ",", "'Start date not provided.'", "end", "unless", "resource", "&&", "SLEEP_RESOURCES", ".", "include?", "(", "resource", ")", "raise", "FitgemOauth2", "::", "InvalidArgumentError", ",", "\"Invalid resource: #{resource}. Valid resources are #{SLEEP_RESOURCES}.\"", "end", "if", "period", "&&", "end_date", "raise", "FitgemOauth2", "::", "InvalidArgumentError", ",", "'Both end_date and period specified. Specify only one.'", "end", "if", "period", "&&", "!", "SLEEP_PERIODS", ".", "include?", "(", "period", ")", "raise", "FitgemOauth2", "::", "InvalidArgumentError", ",", "\"Invalid period: #{period}. Valid periods are #{SLEEP_PERIODS}.\"", "end", "second", "=", "period", "||", "format_date", "(", "end_date", ")", "url", "=", "[", "'user'", ",", "user_id", ",", "'sleep'", ",", "resource", ",", "'date'", ",", "format_date", "(", "start_date", ")", ",", "second", "]", ".", "join", "(", "'/'", ")", "get_call", "(", "url", "+", "'.json'", ")", "end" ]
retrieve time series data for sleep @param resource sleep resource to be requested @param start_date starting date for sleep time series @param end_date ending date for sleep time series @param period period for sleep time series
[ "retrieve", "time", "series", "data", "for", "sleep" ]
10caf154d351dcef54442d9092c445cd388ad09e
https://github.com/gupta-ankit/fitgem_oauth2/blob/10caf154d351dcef54442d9092c445cd388ad09e/lib/fitgem_oauth2/sleep.rb#L50-L72
train
jkotests/watir-nokogiri
lib/watir-nokogiri/elements/option.rb
WatirNokogiri.Option.text
def text assert_exists # A little unintuitive - we'll return the 'label' or 'text' attribute if # they exist, otherwise the inner text of the element attribute = [:label, :text].find { |a| attribute? a } if attribute @element.get_attribute(attribute) else @element.text end end
ruby
def text assert_exists # A little unintuitive - we'll return the 'label' or 'text' attribute if # they exist, otherwise the inner text of the element attribute = [:label, :text].find { |a| attribute? a } if attribute @element.get_attribute(attribute) else @element.text end end
[ "def", "text", "assert_exists", "attribute", "=", "[", ":label", ",", ":text", "]", ".", "find", "{", "|", "a", "|", "attribute?", "a", "}", "if", "attribute", "@element", ".", "get_attribute", "(", "attribute", ")", "else", "@element", ".", "text", "end", "end" ]
Returns the text of option. Note that the text is either one of the following respectively: * label attribute * text attribute * inner element text @return [String]
[ "Returns", "the", "text", "of", "option", "." ]
32c783730bda83dfbeb97a78d7a21788bd726815
https://github.com/jkotests/watir-nokogiri/blob/32c783730bda83dfbeb97a78d7a21788bd726815/lib/watir-nokogiri/elements/option.rb#L67-L80
train
jkotests/watir-nokogiri
lib/watir-nokogiri/elements/element.rb
WatirNokogiri.Element.style
def style(property = nil) assert_exists styles = attribute_value('style').to_s.strip if property properties = Hash[styles.downcase.split(";").map { |p| p.split(":").map(&:strip) }] properties[property] else styles end end
ruby
def style(property = nil) assert_exists styles = attribute_value('style').to_s.strip if property properties = Hash[styles.downcase.split(";").map { |p| p.split(":").map(&:strip) }] properties[property] else styles end end
[ "def", "style", "(", "property", "=", "nil", ")", "assert_exists", "styles", "=", "attribute_value", "(", "'style'", ")", ".", "to_s", ".", "strip", "if", "property", "properties", "=", "Hash", "[", "styles", ".", "downcase", ".", "split", "(", "\";\"", ")", ".", "map", "{", "|", "p", "|", "p", ".", "split", "(", "\":\"", ")", ".", "map", "(", "&", ":strip", ")", "}", "]", "properties", "[", "property", "]", "else", "styles", "end", "end" ]
Returns given style property of this element. @example html.a(:id => "foo").style #=> "display: block" html.a(:id => "foo").style "display" #=> "block" @param [String] property @return [String]
[ "Returns", "given", "style", "property", "of", "this", "element", "." ]
32c783730bda83dfbeb97a78d7a21788bd726815
https://github.com/jkotests/watir-nokogiri/blob/32c783730bda83dfbeb97a78d7a21788bd726815/lib/watir-nokogiri/elements/element.rb#L155-L164
train
jkotests/watir-nokogiri
lib/watir-nokogiri/elements/element.rb
WatirNokogiri.Element.parent
def parent assert_exists e = @element.parent if e.kind_of?(Nokogiri::XML::Element) WatirNokogiri.element_class_for(e.node_name.downcase).new(@parent, :element => e) end end
ruby
def parent assert_exists e = @element.parent if e.kind_of?(Nokogiri::XML::Element) WatirNokogiri.element_class_for(e.node_name.downcase).new(@parent, :element => e) end end
[ "def", "parent", "assert_exists", "e", "=", "@element", ".", "parent", "if", "e", ".", "kind_of?", "(", "Nokogiri", "::", "XML", "::", "Element", ")", "WatirNokogiri", ".", "element_class_for", "(", "e", ".", "node_name", ".", "downcase", ")", ".", "new", "(", "@parent", ",", ":element", "=>", "e", ")", "end", "end" ]
Returns parent element of current element.
[ "Returns", "parent", "element", "of", "current", "element", "." ]
32c783730bda83dfbeb97a78d7a21788bd726815
https://github.com/jkotests/watir-nokogiri/blob/32c783730bda83dfbeb97a78d7a21788bd726815/lib/watir-nokogiri/elements/element.rb#L170-L178
train
chetan/dht-sensor-ffi
lib/dht-sensor/app.rb
DhtSensor.App.to_hash
def to_hash(val) if @options[:humidity] then return {"humidity" => val.humidity} end if @options[:unit] == :c then if @options[:temperature] then return {"temperature" => val.temp} else return {"temperature" => val.temp, "humidity" => val.humidity} end else if @options[:temperature] then return {"temperature" => val.temp_f} else return {"temperature" => val.temp_f, "humidity" => val.humidity} end end end
ruby
def to_hash(val) if @options[:humidity] then return {"humidity" => val.humidity} end if @options[:unit] == :c then if @options[:temperature] then return {"temperature" => val.temp} else return {"temperature" => val.temp, "humidity" => val.humidity} end else if @options[:temperature] then return {"temperature" => val.temp_f} else return {"temperature" => val.temp_f, "humidity" => val.humidity} end end end
[ "def", "to_hash", "(", "val", ")", "if", "@options", "[", ":humidity", "]", "then", "return", "{", "\"humidity\"", "=>", "val", ".", "humidity", "}", "end", "if", "@options", "[", ":unit", "]", "==", ":c", "then", "if", "@options", "[", ":temperature", "]", "then", "return", "{", "\"temperature\"", "=>", "val", ".", "temp", "}", "else", "return", "{", "\"temperature\"", "=>", "val", ".", "temp", ",", "\"humidity\"", "=>", "val", ".", "humidity", "}", "end", "else", "if", "@options", "[", ":temperature", "]", "then", "return", "{", "\"temperature\"", "=>", "val", ".", "temp_f", "}", "else", "return", "{", "\"temperature\"", "=>", "val", ".", "temp_f", ",", "\"humidity\"", "=>", "val", ".", "humidity", "}", "end", "end", "end" ]
Convert to sensor reading to hash
[ "Convert", "to", "sensor", "reading", "to", "hash" ]
fe7d6d0c64dc9c258bd823f7d1d41f7edf129cd2
https://github.com/chetan/dht-sensor-ffi/blob/fe7d6d0c64dc9c258bd823f7d1d41f7edf129cd2/lib/dht-sensor/app.rb#L58-L76
train
chetan/dht-sensor-ffi
lib/dht-sensor/app.rb
DhtSensor.App.print
def print(val) if @options[:humidity] then puts sprintf("Humidity: %.2f%%", val.humidity) return end if @options[:unit] == :c then if @options[:temperature] then puts sprintf("Temperature: %.2f C", val.temp) else puts sprintf("Temperature: %.2f C Humidity: %.2f%%", val.temp, val.humidity) end else if @options[:temperature] then puts sprintf("Temperature: %.2f F", val.temp_f, val.humidity) else puts sprintf("Temperature: %.2f F Humidity: %.2f%%", val.temp_f, val.humidity) end end end
ruby
def print(val) if @options[:humidity] then puts sprintf("Humidity: %.2f%%", val.humidity) return end if @options[:unit] == :c then if @options[:temperature] then puts sprintf("Temperature: %.2f C", val.temp) else puts sprintf("Temperature: %.2f C Humidity: %.2f%%", val.temp, val.humidity) end else if @options[:temperature] then puts sprintf("Temperature: %.2f F", val.temp_f, val.humidity) else puts sprintf("Temperature: %.2f F Humidity: %.2f%%", val.temp_f, val.humidity) end end end
[ "def", "print", "(", "val", ")", "if", "@options", "[", ":humidity", "]", "then", "puts", "sprintf", "(", "\"Humidity: %.2f%%\"", ",", "val", ".", "humidity", ")", "return", "end", "if", "@options", "[", ":unit", "]", "==", ":c", "then", "if", "@options", "[", ":temperature", "]", "then", "puts", "sprintf", "(", "\"Temperature: %.2f C\"", ",", "val", ".", "temp", ")", "else", "puts", "sprintf", "(", "\"Temperature: %.2f C Humidity: %.2f%%\"", ",", "val", ".", "temp", ",", "val", ".", "humidity", ")", "end", "else", "if", "@options", "[", ":temperature", "]", "then", "puts", "sprintf", "(", "\"Temperature: %.2f F\"", ",", "val", ".", "temp_f", ",", "val", ".", "humidity", ")", "else", "puts", "sprintf", "(", "\"Temperature: %.2f F Humidity: %.2f%%\"", ",", "val", ".", "temp_f", ",", "val", ".", "humidity", ")", "end", "end", "end" ]
Print to stdout, taking the various output options into account
[ "Print", "to", "stdout", "taking", "the", "various", "output", "options", "into", "account" ]
fe7d6d0c64dc9c258bd823f7d1d41f7edf129cd2
https://github.com/chetan/dht-sensor-ffi/blob/fe7d6d0c64dc9c258bd823f7d1d41f7edf129cd2/lib/dht-sensor/app.rb#L79-L98
train
jkotests/watir-nokogiri
lib/watir-nokogiri/cell_container.rb
WatirNokogiri.CellContainer.cell
def cell(*args) cell = TableCell.new(self, extract_selector(args).merge(:tag_name => /^(th|td)$/)) cell.locator_class = ChildCellLocator cell end
ruby
def cell(*args) cell = TableCell.new(self, extract_selector(args).merge(:tag_name => /^(th|td)$/)) cell.locator_class = ChildCellLocator cell end
[ "def", "cell", "(", "*", "args", ")", "cell", "=", "TableCell", ".", "new", "(", "self", ",", "extract_selector", "(", "args", ")", ".", "merge", "(", ":tag_name", "=>", "/", "/", ")", ")", "cell", ".", "locator_class", "=", "ChildCellLocator", "cell", "end" ]
Returns table cell. @return [TableCell]
[ "Returns", "table", "cell", "." ]
32c783730bda83dfbeb97a78d7a21788bd726815
https://github.com/jkotests/watir-nokogiri/blob/32c783730bda83dfbeb97a78d7a21788bd726815/lib/watir-nokogiri/cell_container.rb#L10-L15
train
jkotests/watir-nokogiri
lib/watir-nokogiri/cell_container.rb
WatirNokogiri.CellContainer.cells
def cells(*args) cells = TableCellCollection.new(self, extract_selector(args).merge(:tag_name => /^(th|td)$/)) cells.locator_class = ChildCellLocator cells end
ruby
def cells(*args) cells = TableCellCollection.new(self, extract_selector(args).merge(:tag_name => /^(th|td)$/)) cells.locator_class = ChildCellLocator cells end
[ "def", "cells", "(", "*", "args", ")", "cells", "=", "TableCellCollection", ".", "new", "(", "self", ",", "extract_selector", "(", "args", ")", ".", "merge", "(", ":tag_name", "=>", "/", "/", ")", ")", "cells", ".", "locator_class", "=", "ChildCellLocator", "cells", "end" ]
Returns table cells collection. @return [TableCell]
[ "Returns", "table", "cells", "collection", "." ]
32c783730bda83dfbeb97a78d7a21788bd726815
https://github.com/jkotests/watir-nokogiri/blob/32c783730bda83dfbeb97a78d7a21788bd726815/lib/watir-nokogiri/cell_container.rb#L23-L28
train
messagemedia/messages-ruby-sdk
lib/message_media_messages/models/base_model.rb
MessageMediaMessages.BaseModel.to_hash
def to_hash hash = {} instance_variables.each do |name| value = instance_variable_get(name) next if value.nil? name = name[1..-1] key = self.class.names.key?(name) ? self.class.names[name] : name if value.instance_of? Array hash[key] = value.map { |v| v.is_a?(BaseModel) ? v.to_hash : v } elsif value.instance_of? Hash hash[key] = {} value.each do |k, v| hash[key][k] = v.is_a?(BaseModel) ? v.to_hash : v end else hash[key] = value.is_a?(BaseModel) ? value.to_hash : value end end hash end
ruby
def to_hash hash = {} instance_variables.each do |name| value = instance_variable_get(name) next if value.nil? name = name[1..-1] key = self.class.names.key?(name) ? self.class.names[name] : name if value.instance_of? Array hash[key] = value.map { |v| v.is_a?(BaseModel) ? v.to_hash : v } elsif value.instance_of? Hash hash[key] = {} value.each do |k, v| hash[key][k] = v.is_a?(BaseModel) ? v.to_hash : v end else hash[key] = value.is_a?(BaseModel) ? value.to_hash : value end end hash end
[ "def", "to_hash", "hash", "=", "{", "}", "instance_variables", ".", "each", "do", "|", "name", "|", "value", "=", "instance_variable_get", "(", "name", ")", "next", "if", "value", ".", "nil?", "name", "=", "name", "[", "1", "..", "-", "1", "]", "key", "=", "self", ".", "class", ".", "names", ".", "key?", "(", "name", ")", "?", "self", ".", "class", ".", "names", "[", "name", "]", ":", "name", "if", "value", ".", "instance_of?", "Array", "hash", "[", "key", "]", "=", "value", ".", "map", "{", "|", "v", "|", "v", ".", "is_a?", "(", "BaseModel", ")", "?", "v", ".", "to_hash", ":", "v", "}", "elsif", "value", ".", "instance_of?", "Hash", "hash", "[", "key", "]", "=", "{", "}", "value", ".", "each", "do", "|", "k", ",", "v", "|", "hash", "[", "key", "]", "[", "k", "]", "=", "v", ".", "is_a?", "(", "BaseModel", ")", "?", "v", ".", "to_hash", ":", "v", "end", "else", "hash", "[", "key", "]", "=", "value", ".", "is_a?", "(", "BaseModel", ")", "?", "value", ".", "to_hash", ":", "value", "end", "end", "hash", "end" ]
Returns a Hash representation of the current object.
[ "Returns", "a", "Hash", "representation", "of", "the", "current", "object", "." ]
073f1f7ca5e4ff3df51b8eeafeaae2167ec6f311
https://github.com/messagemedia/messages-ruby-sdk/blob/073f1f7ca5e4ff3df51b8eeafeaae2167ec6f311/lib/message_media_messages/models/base_model.rb#L10-L29
train
jkotests/watir-nokogiri
lib/watir-nokogiri/document.rb
WatirNokogiri.Document.goto
def goto(file_path) html = File.read(file_path) @driver = Nokogiri::HTML.parse(html) end
ruby
def goto(file_path) html = File.read(file_path) @driver = Nokogiri::HTML.parse(html) end
[ "def", "goto", "(", "file_path", ")", "html", "=", "File", ".", "read", "(", "file_path", ")", "@driver", "=", "Nokogiri", "::", "HTML", ".", "parse", "(", "html", ")", "end" ]
Reads the given file as HTML. @example browser.goto "www.google.com" @param [String] uri The url. @return [String] The url you end up at.
[ "Reads", "the", "given", "file", "as", "HTML", "." ]
32c783730bda83dfbeb97a78d7a21788bd726815
https://github.com/jkotests/watir-nokogiri/blob/32c783730bda83dfbeb97a78d7a21788bd726815/lib/watir-nokogiri/document.rb#L47-L50
train
simonrepp/titlekit
lib/titlekit/job.rb
Titlekit.Job.run
def run @wants.each do |want| @haves.each do |have| import(have) retime(have, want) cull(have) group(have) want.subtitles += have.subtitles.clone end polish(want) export(want) end return true rescue AbortJob return false end
ruby
def run @wants.each do |want| @haves.each do |have| import(have) retime(have, want) cull(have) group(have) want.subtitles += have.subtitles.clone end polish(want) export(want) end return true rescue AbortJob return false end
[ "def", "run", "@wants", ".", "each", "do", "|", "want", "|", "@haves", ".", "each", "do", "|", "have", "|", "import", "(", "have", ")", "retime", "(", "have", ",", "want", ")", "cull", "(", "have", ")", "group", "(", "have", ")", "want", ".", "subtitles", "+=", "have", ".", "subtitles", ".", "clone", "end", "polish", "(", "want", ")", "export", "(", "want", ")", "end", "return", "true", "rescue", "AbortJob", "return", "false", "end" ]
Starts a new job. A job requires at least one file you {Have} and one file you {Want} in order to be runable. Use {Job#have} and {Job#want} to add and obtain specification interfaces for the job. Runs the job. @return [Boolean] true if the job succeeds, false if it fails. {Job#report} provides information in case of failure.
[ "Starts", "a", "new", "job", "." ]
65d3743378aaf54544efb7c642cfc656085191db
https://github.com/simonrepp/titlekit/blob/65d3743378aaf54544efb7c642cfc656085191db/lib/titlekit/job.rb#L49-L67
train
simonrepp/titlekit
lib/titlekit/job.rb
Titlekit.Job.cull
def cull(have) have.subtitles.reject! { |subtitle| subtitle[:end] < 0 } have.subtitles.each do |subtitle| subtitle[:start] = 0 if subtitle[:start] < 0 end end
ruby
def cull(have) have.subtitles.reject! { |subtitle| subtitle[:end] < 0 } have.subtitles.each do |subtitle| subtitle[:start] = 0 if subtitle[:start] < 0 end end
[ "def", "cull", "(", "have", ")", "have", ".", "subtitles", ".", "reject!", "{", "|", "subtitle", "|", "subtitle", "[", ":end", "]", "<", "0", "}", "have", ".", "subtitles", ".", "each", "do", "|", "subtitle", "|", "subtitle", "[", ":start", "]", "=", "0", "if", "subtitle", "[", ":start", "]", "<", "0", "end", "end" ]
Cleans out subtitles that fell out of the usable time range @params have [Have] What we {Have}
[ "Cleans", "out", "subtitles", "that", "fell", "out", "of", "the", "usable", "time", "range" ]
65d3743378aaf54544efb7c642cfc656085191db
https://github.com/simonrepp/titlekit/blob/65d3743378aaf54544efb7c642cfc656085191db/lib/titlekit/job.rb#L265-L270
train
simonrepp/titlekit
lib/titlekit/job.rb
Titlekit.Job.retime_by_framerate
def retime_by_framerate(have, want) ratio = want.fps.to_f / have.fps.to_f have.subtitles.each do |subtitle| subtitle[:start] *= ratio subtitle[:end] *= ratio end end
ruby
def retime_by_framerate(have, want) ratio = want.fps.to_f / have.fps.to_f have.subtitles.each do |subtitle| subtitle[:start] *= ratio subtitle[:end] *= ratio end end
[ "def", "retime_by_framerate", "(", "have", ",", "want", ")", "ratio", "=", "want", ".", "fps", ".", "to_f", "/", "have", ".", "fps", ".", "to_f", "have", ".", "subtitles", ".", "each", "do", "|", "subtitle", "|", "subtitle", "[", ":start", "]", "*=", "ratio", "subtitle", "[", ":end", "]", "*=", "ratio", "end", "end" ]
Rescales timecodes based on two differing framerates. @param have [Have] the subtitles we {Have} @param want [Want] the subtitles we {Want}
[ "Rescales", "timecodes", "based", "on", "two", "differing", "framerates", "." ]
65d3743378aaf54544efb7c642cfc656085191db
https://github.com/simonrepp/titlekit/blob/65d3743378aaf54544efb7c642cfc656085191db/lib/titlekit/job.rb#L461-L467
train
messagemedia/messages-ruby-sdk
lib/message_media_messages/http/http_client.rb
MessageMediaMessages.HttpClient.get
def get(query_url, headers: {}) HttpRequest.new(HttpMethodEnum::GET, query_url, headers: headers) end
ruby
def get(query_url, headers: {}) HttpRequest.new(HttpMethodEnum::GET, query_url, headers: headers) end
[ "def", "get", "(", "query_url", ",", "headers", ":", "{", "}", ")", "HttpRequest", ".", "new", "(", "HttpMethodEnum", "::", "GET", ",", "query_url", ",", "headers", ":", "headers", ")", "end" ]
Get a GET HttpRequest object. @param [String] The URL to send the request to. @param [Hash, Optional] The headers for the HTTP Request.
[ "Get", "a", "GET", "HttpRequest", "object", "." ]
073f1f7ca5e4ff3df51b8eeafeaae2167ec6f311
https://github.com/messagemedia/messages-ruby-sdk/blob/073f1f7ca5e4ff3df51b8eeafeaae2167ec6f311/lib/message_media_messages/http/http_client.rb#L36-L41
train
messagemedia/messages-ruby-sdk
lib/message_media_messages/http/http_client.rb
MessageMediaMessages.HttpClient.head
def head(query_url, headers: {}) HttpRequest.new(HttpMethodEnum::HEAD, query_url, headers: headers) end
ruby
def head(query_url, headers: {}) HttpRequest.new(HttpMethodEnum::HEAD, query_url, headers: headers) end
[ "def", "head", "(", "query_url", ",", "headers", ":", "{", "}", ")", "HttpRequest", ".", "new", "(", "HttpMethodEnum", "::", "HEAD", ",", "query_url", ",", "headers", ":", "headers", ")", "end" ]
Get a HEAD HttpRequest object. @param [String] The URL to send the request to. @param [Hash, Optional] The headers for the HTTP Request.
[ "Get", "a", "HEAD", "HttpRequest", "object", "." ]
073f1f7ca5e4ff3df51b8eeafeaae2167ec6f311
https://github.com/messagemedia/messages-ruby-sdk/blob/073f1f7ca5e4ff3df51b8eeafeaae2167ec6f311/lib/message_media_messages/http/http_client.rb#L46-L51
train
messagemedia/messages-ruby-sdk
lib/message_media_messages/http/http_client.rb
MessageMediaMessages.HttpClient.post
def post(query_url, headers: {}, parameters: {}) HttpRequest.new(HttpMethodEnum::POST, query_url, headers: headers, parameters: parameters) end
ruby
def post(query_url, headers: {}, parameters: {}) HttpRequest.new(HttpMethodEnum::POST, query_url, headers: headers, parameters: parameters) end
[ "def", "post", "(", "query_url", ",", "headers", ":", "{", "}", ",", "parameters", ":", "{", "}", ")", "HttpRequest", ".", "new", "(", "HttpMethodEnum", "::", "POST", ",", "query_url", ",", "headers", ":", "headers", ",", "parameters", ":", "parameters", ")", "end" ]
Get a POST HttpRequest object. @param [String] The URL to send the request to. @param [Hash, Optional] The headers for the HTTP Request. @param [Hash, Optional] The parameters for the HTTP Request.
[ "Get", "a", "POST", "HttpRequest", "object", "." ]
073f1f7ca5e4ff3df51b8eeafeaae2167ec6f311
https://github.com/messagemedia/messages-ruby-sdk/blob/073f1f7ca5e4ff3df51b8eeafeaae2167ec6f311/lib/message_media_messages/http/http_client.rb#L57-L64
train
messagemedia/messages-ruby-sdk
lib/message_media_messages/http/http_client.rb
MessageMediaMessages.HttpClient.put
def put(query_url, headers: {}, parameters: {}) HttpRequest.new(HttpMethodEnum::PUT, query_url, headers: headers, parameters: parameters) end
ruby
def put(query_url, headers: {}, parameters: {}) HttpRequest.new(HttpMethodEnum::PUT, query_url, headers: headers, parameters: parameters) end
[ "def", "put", "(", "query_url", ",", "headers", ":", "{", "}", ",", "parameters", ":", "{", "}", ")", "HttpRequest", ".", "new", "(", "HttpMethodEnum", "::", "PUT", ",", "query_url", ",", "headers", ":", "headers", ",", "parameters", ":", "parameters", ")", "end" ]
Get a PUT HttpRequest object. @param [String] The URL to send the request to. @param [Hash, Optional] The headers for the HTTP Request. @param [Hash, Optional] The parameters for the HTTP Request.
[ "Get", "a", "PUT", "HttpRequest", "object", "." ]
073f1f7ca5e4ff3df51b8eeafeaae2167ec6f311
https://github.com/messagemedia/messages-ruby-sdk/blob/073f1f7ca5e4ff3df51b8eeafeaae2167ec6f311/lib/message_media_messages/http/http_client.rb#L70-L77
train
messagemedia/messages-ruby-sdk
lib/message_media_messages/http/http_client.rb
MessageMediaMessages.HttpClient.patch
def patch(query_url, headers: {}, parameters: {}) HttpRequest.new(HttpMethodEnum::PATCH, query_url, headers: headers, parameters: parameters) end
ruby
def patch(query_url, headers: {}, parameters: {}) HttpRequest.new(HttpMethodEnum::PATCH, query_url, headers: headers, parameters: parameters) end
[ "def", "patch", "(", "query_url", ",", "headers", ":", "{", "}", ",", "parameters", ":", "{", "}", ")", "HttpRequest", ".", "new", "(", "HttpMethodEnum", "::", "PATCH", ",", "query_url", ",", "headers", ":", "headers", ",", "parameters", ":", "parameters", ")", "end" ]
Get a PATCH HttpRequest object. @param [String] The URL to send the request to. @param [Hash, Optional] The headers for the HTTP Request. @param [Hash, Optional] The parameters for the HTTP Request.
[ "Get", "a", "PATCH", "HttpRequest", "object", "." ]
073f1f7ca5e4ff3df51b8eeafeaae2167ec6f311
https://github.com/messagemedia/messages-ruby-sdk/blob/073f1f7ca5e4ff3df51b8eeafeaae2167ec6f311/lib/message_media_messages/http/http_client.rb#L83-L90
train
messagemedia/messages-ruby-sdk
lib/message_media_messages/http/http_client.rb
MessageMediaMessages.HttpClient.delete
def delete(query_url, headers: {}, parameters: {}) HttpRequest.new(HttpMethodEnum::DELETE, query_url, headers: headers, parameters: parameters) end
ruby
def delete(query_url, headers: {}, parameters: {}) HttpRequest.new(HttpMethodEnum::DELETE, query_url, headers: headers, parameters: parameters) end
[ "def", "delete", "(", "query_url", ",", "headers", ":", "{", "}", ",", "parameters", ":", "{", "}", ")", "HttpRequest", ".", "new", "(", "HttpMethodEnum", "::", "DELETE", ",", "query_url", ",", "headers", ":", "headers", ",", "parameters", ":", "parameters", ")", "end" ]
Get a DELETE HttpRequest object. @param [String] The URL to send the request to. @param [Hash, Optional] The headers for the HTTP Request.
[ "Get", "a", "DELETE", "HttpRequest", "object", "." ]
073f1f7ca5e4ff3df51b8eeafeaae2167ec6f311
https://github.com/messagemedia/messages-ruby-sdk/blob/073f1f7ca5e4ff3df51b8eeafeaae2167ec6f311/lib/message_media_messages/http/http_client.rb#L95-L102
train
jnewland/capistrano-log_with_awesome
lib/capistrano/log_with_awesome.rb
Capistrano.LogWithAwesome.log
def log(level, message, line_prefix=nil) if level <= self.level indent = "%*s" % [Capistrano::Logger::MAX_LEVEL, "*" * (Capistrano::Logger::MAX_LEVEL - level)] (RUBY_VERSION >= "1.9" ? message.lines : message).each do |line| if line_prefix self.class.log_with_awesome "#{indent} [#{line_prefix}] #{line.strip}" else self.class.log_with_awesome "#{indent} #{line.strip}" end end end super(level, message, line_prefix) end
ruby
def log(level, message, line_prefix=nil) if level <= self.level indent = "%*s" % [Capistrano::Logger::MAX_LEVEL, "*" * (Capistrano::Logger::MAX_LEVEL - level)] (RUBY_VERSION >= "1.9" ? message.lines : message).each do |line| if line_prefix self.class.log_with_awesome "#{indent} [#{line_prefix}] #{line.strip}" else self.class.log_with_awesome "#{indent} #{line.strip}" end end end super(level, message, line_prefix) end
[ "def", "log", "(", "level", ",", "message", ",", "line_prefix", "=", "nil", ")", "if", "level", "<=", "self", ".", "level", "indent", "=", "\"%*s\"", "%", "[", "Capistrano", "::", "Logger", "::", "MAX_LEVEL", ",", "\"*\"", "*", "(", "Capistrano", "::", "Logger", "::", "MAX_LEVEL", "-", "level", ")", "]", "(", "RUBY_VERSION", ">=", "\"1.9\"", "?", "message", ".", "lines", ":", "message", ")", ".", "each", "do", "|", "line", "|", "if", "line_prefix", "self", ".", "class", ".", "log_with_awesome", "\"#{indent} [#{line_prefix}] #{line.strip}\"", "else", "self", ".", "class", ".", "log_with_awesome", "\"#{indent} #{line.strip}\"", "end", "end", "end", "super", "(", "level", ",", "message", ",", "line_prefix", ")", "end" ]
Log and do awesome things I wish there was a nicer way to do this. Hax on device.puts, maybe?
[ "Log", "and", "do", "awesome", "things", "I", "wish", "there", "was", "a", "nicer", "way", "to", "do", "this", ".", "Hax", "on", "device", ".", "puts", "maybe?" ]
863ced8128d7f78342e5c8953e32a4af8f81a725
https://github.com/jnewland/capistrano-log_with_awesome/blob/863ced8128d7f78342e5c8953e32a4af8f81a725/lib/capistrano/log_with_awesome.rb#L23-L35
train
jkraemer/acts_as_ferret
lib/acts_as_ferret/class_methods.rb
ActsAsFerret.ClassMethods.records_for_rebuild
def records_for_rebuild(batch_size = 1000) transaction do if use_fast_batches? offset = 0 while (rows = where([ "#{table_name}.id > ?", offset ]).limit(batch_size).all).any? offset = rows.last.id yield rows, offset end else order = "#{primary_key} ASC" # fixes #212 0.step(self.count, batch_size) do |offset| yield scoped.limit(batch_size).offset(offset).order(order).all, offset end end end end
ruby
def records_for_rebuild(batch_size = 1000) transaction do if use_fast_batches? offset = 0 while (rows = where([ "#{table_name}.id > ?", offset ]).limit(batch_size).all).any? offset = rows.last.id yield rows, offset end else order = "#{primary_key} ASC" # fixes #212 0.step(self.count, batch_size) do |offset| yield scoped.limit(batch_size).offset(offset).order(order).all, offset end end end end
[ "def", "records_for_rebuild", "(", "batch_size", "=", "1000", ")", "transaction", "do", "if", "use_fast_batches?", "offset", "=", "0", "while", "(", "rows", "=", "where", "(", "[", "\"#{table_name}.id > ?\"", ",", "offset", "]", ")", ".", "limit", "(", "batch_size", ")", ".", "all", ")", ".", "any?", "offset", "=", "rows", ".", "last", ".", "id", "yield", "rows", ",", "offset", "end", "else", "order", "=", "\"#{primary_key} ASC\"", "0", ".", "step", "(", "self", ".", "count", ",", "batch_size", ")", "do", "|", "offset", "|", "yield", "scoped", ".", "limit", "(", "batch_size", ")", ".", "offset", "(", "offset", ")", ".", "order", "(", "order", ")", ".", "all", ",", "offset", "end", "end", "end", "end" ]
runs across all records yielding those to be indexed when the index is rebuilt
[ "runs", "across", "all", "records", "yielding", "those", "to", "be", "indexed", "when", "the", "index", "is", "rebuilt" ]
1c3330c51a4d07298e6b89347077742636d9e3cf
https://github.com/jkraemer/acts_as_ferret/blob/1c3330c51a4d07298e6b89347077742636d9e3cf/lib/acts_as_ferret/class_methods.rb#L73-L88
train
jkraemer/acts_as_ferret
lib/acts_as_ferret/class_methods.rb
ActsAsFerret.ClassMethods.records_for_bulk_index
def records_for_bulk_index(ids, batch_size = 1000) transaction do offset = 0 ids.each_slice(batch_size) do |id_slice| records = where(:id => id_slice).all #yield records, offset yield where(:id => id_slice).all, offset offset += batch_size end end end
ruby
def records_for_bulk_index(ids, batch_size = 1000) transaction do offset = 0 ids.each_slice(batch_size) do |id_slice| records = where(:id => id_slice).all #yield records, offset yield where(:id => id_slice).all, offset offset += batch_size end end end
[ "def", "records_for_bulk_index", "(", "ids", ",", "batch_size", "=", "1000", ")", "transaction", "do", "offset", "=", "0", "ids", ".", "each_slice", "(", "batch_size", ")", "do", "|", "id_slice", "|", "records", "=", "where", "(", ":id", "=>", "id_slice", ")", ".", "all", "yield", "where", "(", ":id", "=>", "id_slice", ")", ".", "all", ",", "offset", "offset", "+=", "batch_size", "end", "end", "end" ]
yields the records with the given ids, in batches of batch_size
[ "yields", "the", "records", "with", "the", "given", "ids", "in", "batches", "of", "batch_size" ]
1c3330c51a4d07298e6b89347077742636d9e3cf
https://github.com/jkraemer/acts_as_ferret/blob/1c3330c51a4d07298e6b89347077742636d9e3cf/lib/acts_as_ferret/class_methods.rb#L91-L101
train
jimweirich/sorcerer
lib/sorcerer/subexpression.rb
Sorcerer.Subexpression.within_method_sexp
def within_method_sexp(sexp) case sexp.first when :call # [:call, target, ".", meth] recur(sexp[1]) when :method_add_block # [:method_add_block, call, block] within_method_sexp(sexp[1]) when :method_add_arg # [:method_add_arg, call, args] recur(sexp[2]) within_method_sexp(sexp[1]) else recur(sexp) end end
ruby
def within_method_sexp(sexp) case sexp.first when :call # [:call, target, ".", meth] recur(sexp[1]) when :method_add_block # [:method_add_block, call, block] within_method_sexp(sexp[1]) when :method_add_arg # [:method_add_arg, call, args] recur(sexp[2]) within_method_sexp(sexp[1]) else recur(sexp) end end
[ "def", "within_method_sexp", "(", "sexp", ")", "case", "sexp", ".", "first", "when", ":call", "recur", "(", "sexp", "[", "1", "]", ")", "when", ":method_add_block", "within_method_sexp", "(", "sexp", "[", "1", "]", ")", "when", ":method_add_arg", "recur", "(", "sexp", "[", "2", "]", ")", "within_method_sexp", "(", "sexp", "[", "1", "]", ")", "else", "recur", "(", "sexp", ")", "end", "end" ]
When already handling a method call, we don't need to recur on some items.
[ "When", "already", "handling", "a", "method", "call", "we", "don", "t", "need", "to", "recur", "on", "some", "items", "." ]
438adba3ce0d9231fd657b72166f4f035422f53a
https://github.com/jimweirich/sorcerer/blob/438adba3ce0d9231fd657b72166f4f035422f53a/lib/sorcerer/subexpression.rb#L78-L90
train
blackwinter/brice
lib/brice/colours.rb
Brice.Colours.enable_irb
def enable_irb IRB::Inspector.class_eval { unless method_defined?(:inspect_value_with_colour) alias_method :inspect_value_without_colour, :inspect_value def inspect_value_with_colour(value) Colours.colourize(inspect_value_without_colour(value)) end end alias_method :inspect_value, :inspect_value_with_colour } end
ruby
def enable_irb IRB::Inspector.class_eval { unless method_defined?(:inspect_value_with_colour) alias_method :inspect_value_without_colour, :inspect_value def inspect_value_with_colour(value) Colours.colourize(inspect_value_without_colour(value)) end end alias_method :inspect_value, :inspect_value_with_colour } end
[ "def", "enable_irb", "IRB", "::", "Inspector", ".", "class_eval", "{", "unless", "method_defined?", "(", ":inspect_value_with_colour", ")", "alias_method", ":inspect_value_without_colour", ",", ":inspect_value", "def", "inspect_value_with_colour", "(", "value", ")", "Colours", ".", "colourize", "(", "inspect_value_without_colour", "(", "value", ")", ")", "end", "end", "alias_method", ":inspect_value", ",", ":inspect_value_with_colour", "}", "end" ]
Enable colourized IRb results.
[ "Enable", "colourized", "IRb", "results", "." ]
abe86570bbc65d9d0f3f62c86cd8f88a65882254
https://github.com/blackwinter/brice/blob/abe86570bbc65d9d0f3f62c86cd8f88a65882254/lib/brice/colours.rb#L111-L123
train
blackwinter/brice
lib/brice/colours.rb
Brice.Colours.colourize
def colourize(str) ''.tap { |res| Tokenizer.tokenize(str.to_s) { |token, value| res << colourize_string(value, colours[token]) } } rescue => err Brice.error(self, __method__, err) str end
ruby
def colourize(str) ''.tap { |res| Tokenizer.tokenize(str.to_s) { |token, value| res << colourize_string(value, colours[token]) } } rescue => err Brice.error(self, __method__, err) str end
[ "def", "colourize", "(", "str", ")", "''", ".", "tap", "{", "|", "res", "|", "Tokenizer", ".", "tokenize", "(", "str", ".", "to_s", ")", "{", "|", "token", ",", "value", "|", "res", "<<", "colourize_string", "(", "value", ",", "colours", "[", "token", "]", ")", "}", "}", "rescue", "=>", "err", "Brice", ".", "error", "(", "self", ",", "__method__", ",", "err", ")", "str", "end" ]
Colourize the results of inspect
[ "Colourize", "the", "results", "of", "inspect" ]
abe86570bbc65d9d0f3f62c86cd8f88a65882254
https://github.com/blackwinter/brice/blob/abe86570bbc65d9d0f3f62c86cd8f88a65882254/lib/brice/colours.rb#L192-L199
train
postmodern/gscraper
lib/gscraper/has_pages.rb
GScraper.HasPages.each_page
def each_page(indices) unless block_given? enum_for(:each_page,indices) else indices.map { |index| yield page_cache[index] } end end
ruby
def each_page(indices) unless block_given? enum_for(:each_page,indices) else indices.map { |index| yield page_cache[index] } end end
[ "def", "each_page", "(", "indices", ")", "unless", "block_given?", "enum_for", "(", ":each_page", ",", "indices", ")", "else", "indices", ".", "map", "{", "|", "index", "|", "yield", "page_cache", "[", "index", "]", "}", "end", "end" ]
Iterates over the pages at the specified indices. @param [Array, Range] indices The indices. @yield [page] The given block will be passed each page. @yieldparam [Page] page A page at one of the given indices.
[ "Iterates", "over", "the", "pages", "at", "the", "specified", "indices", "." ]
8370880a7b0c03b3c12a5ba3dfc19a6230187d6a
https://github.com/postmodern/gscraper/blob/8370880a7b0c03b3c12a5ba3dfc19a6230187d6a/lib/gscraper/has_pages.rb#L73-L79
train
postmodern/gscraper
lib/gscraper/has_pages.rb
GScraper.HasPages.each
def each return enum_for(:each) unless block_given? index = 1 until ((next_page = page_cache[index]).empty?) do yield next_page index = index + 1 end return self end
ruby
def each return enum_for(:each) unless block_given? index = 1 until ((next_page = page_cache[index]).empty?) do yield next_page index = index + 1 end return self end
[ "def", "each", "return", "enum_for", "(", ":each", ")", "unless", "block_given?", "index", "=", "1", "until", "(", "(", "next_page", "=", "page_cache", "[", "index", "]", ")", ".", "empty?", ")", "do", "yield", "next_page", "index", "=", "index", "+", "1", "end", "return", "self", "end" ]
Iterates over all the pages of the query, until an empty page is encountered. @yield [page] A page with results from the query. @yieldparam [Page] page A non-empty page from the query.
[ "Iterates", "over", "all", "the", "pages", "of", "the", "query", "until", "an", "empty", "page", "is", "encountered", "." ]
8370880a7b0c03b3c12a5ba3dfc19a6230187d6a
https://github.com/postmodern/gscraper/blob/8370880a7b0c03b3c12a5ba3dfc19a6230187d6a/lib/gscraper/has_pages.rb#L91-L102
train
postmodern/gscraper
lib/gscraper/has_pages.rb
GScraper.HasPages.page_cache
def page_cache @page_cache ||= Hash.new { |hash,key| hash[key] = page(key.to_i) } end
ruby
def page_cache @page_cache ||= Hash.new { |hash,key| hash[key] = page(key.to_i) } end
[ "def", "page_cache", "@page_cache", "||=", "Hash", ".", "new", "{", "|", "hash", ",", "key", "|", "hash", "[", "key", "]", "=", "page", "(", "key", ".", "to_i", ")", "}", "end" ]
The cache of previously requested pages. @return [Hash]
[ "The", "cache", "of", "previously", "requested", "pages", "." ]
8370880a7b0c03b3c12a5ba3dfc19a6230187d6a
https://github.com/postmodern/gscraper/blob/8370880a7b0c03b3c12a5ba3dfc19a6230187d6a/lib/gscraper/has_pages.rb#L167-L169
train
jkraemer/acts_as_ferret
lib/acts_as_ferret/index.rb
ActsAsFerret.AbstractIndex.change_index_dir
def change_index_dir(new_dir) logger.debug "[#{index_name}] changing index dir to #{new_dir}" index_definition[:index_dir] = index_definition[:ferret][:path] = new_dir reopen! logger.debug "[#{index_name}] index dir is now #{new_dir}" end
ruby
def change_index_dir(new_dir) logger.debug "[#{index_name}] changing index dir to #{new_dir}" index_definition[:index_dir] = index_definition[:ferret][:path] = new_dir reopen! logger.debug "[#{index_name}] index dir is now #{new_dir}" end
[ "def", "change_index_dir", "(", "new_dir", ")", "logger", ".", "debug", "\"[#{index_name}] changing index dir to #{new_dir}\"", "index_definition", "[", ":index_dir", "]", "=", "index_definition", "[", ":ferret", "]", "[", ":path", "]", "=", "new_dir", "reopen!", "logger", ".", "debug", "\"[#{index_name}] index dir is now #{new_dir}\"", "end" ]
Switches the index to a new index directory. Used by the DRb server when switching to a new index version.
[ "Switches", "the", "index", "to", "a", "new", "index", "directory", ".", "Used", "by", "the", "DRb", "server", "when", "switching", "to", "a", "new", "index", "version", "." ]
1c3330c51a4d07298e6b89347077742636d9e3cf
https://github.com/jkraemer/acts_as_ferret/blob/1c3330c51a4d07298e6b89347077742636d9e3cf/lib/acts_as_ferret/index.rb#L88-L93
train
xcres/xcres
lib/xcres/model/xcassets/bundle.rb
XCRes::XCAssets.Bundle.read
def read @resource_paths = Dir.chdir(path) do Dir['**/Contents.json'].map { |p| Pathname(p) + '..' } end @resources = @resource_paths.map do |path| Resource.new(self, path) end self end
ruby
def read @resource_paths = Dir.chdir(path) do Dir['**/Contents.json'].map { |p| Pathname(p) + '..' } end @resources = @resource_paths.map do |path| Resource.new(self, path) end self end
[ "def", "read", "@resource_paths", "=", "Dir", ".", "chdir", "(", "path", ")", "do", "Dir", "[", "'**/Contents.json'", "]", ".", "map", "{", "|", "p", "|", "Pathname", "(", "p", ")", "+", "'..'", "}", "end", "@resources", "=", "@resource_paths", ".", "map", "do", "|", "path", "|", "Resource", ".", "new", "(", "self", ",", "path", ")", "end", "self", "end" ]
Initialize a new file with given path @param [Pathname] path the location of the container Read the resources from disk @return [XCAssets::Bundle]
[ "Initialize", "a", "new", "file", "with", "given", "path" ]
4747b072ab316e7c6f389db9a3cad584e814fe43
https://github.com/xcres/xcres/blob/4747b072ab316e7c6f389db9a3cad584e814fe43/lib/xcres/model/xcassets/bundle.rb#L44-L52
train
xcres/xcres
lib/xcres/analyzer/strings_analyzer.rb
XCRes.StringsAnalyzer.build_section
def build_section selected_file_refs = selected_strings_file_refs # Apply ignore list file_paths = filter_exclusions(selected_file_refs.map(&:path)) filtered_file_refs = selected_file_refs.select { |file_ref| file_paths.include? file_ref.path } rel_file_paths = filtered_file_refs.map { |p| p.real_path.relative_path_from(Pathname.pwd) } log 'Non-ignored .strings files: %s', rel_file_paths.map(&:to_s) keys_by_file = {} for path in rel_file_paths keys_by_file[path] = keys_by_file(path) end items = keys_by_file.values.reduce({}, :merge) new_section('Strings', items) end
ruby
def build_section selected_file_refs = selected_strings_file_refs # Apply ignore list file_paths = filter_exclusions(selected_file_refs.map(&:path)) filtered_file_refs = selected_file_refs.select { |file_ref| file_paths.include? file_ref.path } rel_file_paths = filtered_file_refs.map { |p| p.real_path.relative_path_from(Pathname.pwd) } log 'Non-ignored .strings files: %s', rel_file_paths.map(&:to_s) keys_by_file = {} for path in rel_file_paths keys_by_file[path] = keys_by_file(path) end items = keys_by_file.values.reduce({}, :merge) new_section('Strings', items) end
[ "def", "build_section", "selected_file_refs", "=", "selected_strings_file_refs", "file_paths", "=", "filter_exclusions", "(", "selected_file_refs", ".", "map", "(", "&", ":path", ")", ")", "filtered_file_refs", "=", "selected_file_refs", ".", "select", "{", "|", "file_ref", "|", "file_paths", ".", "include?", "file_ref", ".", "path", "}", "rel_file_paths", "=", "filtered_file_refs", ".", "map", "{", "|", "p", "|", "p", ".", "real_path", ".", "relative_path_from", "(", "Pathname", ".", "pwd", ")", "}", "log", "'Non-ignored .strings files: %s'", ",", "rel_file_paths", ".", "map", "(", "&", ":to_s", ")", "keys_by_file", "=", "{", "}", "for", "path", "in", "rel_file_paths", "keys_by_file", "[", "path", "]", "=", "keys_by_file", "(", "path", ")", "end", "items", "=", "keys_by_file", ".", "values", ".", "reduce", "(", "{", "}", ",", ":merge", ")", "new_section", "(", "'Strings'", ",", "items", ")", "end" ]
Build the section @return [Section]
[ "Build", "the", "section" ]
4747b072ab316e7c6f389db9a3cad584e814fe43
https://github.com/xcres/xcres/blob/4747b072ab316e7c6f389db9a3cad584e814fe43/lib/xcres/analyzer/strings_analyzer.rb#L43-L60
train
xcres/xcres
lib/xcres/analyzer/strings_analyzer.rb
XCRes.StringsAnalyzer.info_plist_paths
def info_plist_paths @info_plist_paths ||= target.build_configurations.map do |config| config.build_settings['INFOPLIST_FILE'] end.compact.map { |file| Pathname(file) }.flatten.to_set end
ruby
def info_plist_paths @info_plist_paths ||= target.build_configurations.map do |config| config.build_settings['INFOPLIST_FILE'] end.compact.map { |file| Pathname(file) }.flatten.to_set end
[ "def", "info_plist_paths", "@info_plist_paths", "||=", "target", ".", "build_configurations", ".", "map", "do", "|", "config", "|", "config", ".", "build_settings", "[", "'INFOPLIST_FILE'", "]", "end", ".", "compact", ".", "map", "{", "|", "file", "|", "Pathname", "(", "file", ")", "}", ".", "flatten", ".", "to_set", "end" ]
Discover Info.plist files by build settings of the application target @return [Set<Pathname>] the relative paths to the .plist-files
[ "Discover", "Info", ".", "plist", "files", "by", "build", "settings", "of", "the", "application", "target" ]
4747b072ab316e7c6f389db9a3cad584e814fe43
https://github.com/xcres/xcres/blob/4747b072ab316e7c6f389db9a3cad584e814fe43/lib/xcres/analyzer/strings_analyzer.rb#L124-L128
train
xcres/xcres
lib/xcres/analyzer/strings_analyzer.rb
XCRes.StringsAnalyzer.native_dev_languages
def native_dev_languages @native_dev_languages ||= absolute_info_plist_paths.map do |path| begin read_plist_key(path, :CFBundleDevelopmentRegion) rescue ArgumentError => e warn e end end.compact.to_set end
ruby
def native_dev_languages @native_dev_languages ||= absolute_info_plist_paths.map do |path| begin read_plist_key(path, :CFBundleDevelopmentRegion) rescue ArgumentError => e warn e end end.compact.to_set end
[ "def", "native_dev_languages", "@native_dev_languages", "||=", "absolute_info_plist_paths", ".", "map", "do", "|", "path", "|", "begin", "read_plist_key", "(", "path", ",", ":CFBundleDevelopmentRegion", ")", "rescue", "ArgumentError", "=>", "e", "warn", "e", "end", "end", ".", "compact", ".", "to_set", "end" ]
Find the native development languages by trying to use the "Localization native development region" from Info.plist @return [Set<String>]
[ "Find", "the", "native", "development", "languages", "by", "trying", "to", "use", "the", "Localization", "native", "development", "region", "from", "Info", ".", "plist" ]
4747b072ab316e7c6f389db9a3cad584e814fe43
https://github.com/xcres/xcres/blob/4747b072ab316e7c6f389db9a3cad584e814fe43/lib/xcres/analyzer/strings_analyzer.rb#L154-L162
train
xcres/xcres
lib/xcres/analyzer/strings_analyzer.rb
XCRes.StringsAnalyzer.keys_by_file
def keys_by_file(path) begin # Load strings file contents strings = read_strings_file(path) # Reject generated identifiers used by Interface Builder strings.reject! { |key, _| /^[a-zA-Z0-9]{3}-[a-zA-Z0-9]{2,3}-[a-zA-Z0-9]{3}/.match(key) } keys = Hash[strings.map do |key, value| [key, { value: key, comment: value.gsub(/[\r\n]/, ' ') }] end] log 'Found %s keys in file %s', keys.count, path keys rescue ArgumentError => error raise ArgumentError, 'Error while reading %s: %s' % [path, error] end end
ruby
def keys_by_file(path) begin # Load strings file contents strings = read_strings_file(path) # Reject generated identifiers used by Interface Builder strings.reject! { |key, _| /^[a-zA-Z0-9]{3}-[a-zA-Z0-9]{2,3}-[a-zA-Z0-9]{3}/.match(key) } keys = Hash[strings.map do |key, value| [key, { value: key, comment: value.gsub(/[\r\n]/, ' ') }] end] log 'Found %s keys in file %s', keys.count, path keys rescue ArgumentError => error raise ArgumentError, 'Error while reading %s: %s' % [path, error] end end
[ "def", "keys_by_file", "(", "path", ")", "begin", "strings", "=", "read_strings_file", "(", "path", ")", "strings", ".", "reject!", "{", "|", "key", ",", "_", "|", "/", "/", ".", "match", "(", "key", ")", "}", "keys", "=", "Hash", "[", "strings", ".", "map", "do", "|", "key", ",", "value", "|", "[", "key", ",", "{", "value", ":", "key", ",", "comment", ":", "value", ".", "gsub", "(", "/", "\\r", "\\n", "/", ",", "' '", ")", "}", "]", "end", "]", "log", "'Found %s keys in file %s'", ",", "keys", ".", "count", ",", "path", "keys", "rescue", "ArgumentError", "=>", "error", "raise", "ArgumentError", ",", "'Error while reading %s: %s'", "%", "[", "path", ",", "error", "]", "end", "end" ]
Read a file and collect all its keys @param [Pathname] path the path to the .strings file to read @return [Hash{String => Hash}]
[ "Read", "a", "file", "and", "collect", "all", "its", "keys" ]
4747b072ab316e7c6f389db9a3cad584e814fe43
https://github.com/xcres/xcres/blob/4747b072ab316e7c6f389db9a3cad584e814fe43/lib/xcres/analyzer/strings_analyzer.rb#L230-L248
train
jkraemer/acts_as_ferret
lib/acts_as_ferret/instance_methods.rb
ActsAsFerret.InstanceMethods.ferret_enabled?
def ferret_enabled?(is_bulk_index = false) @ferret_disabled.nil? && (is_bulk_index || self.class.ferret_enabled?) && (aaf_configuration[:if].nil? || aaf_configuration[:if].call(self)) end
ruby
def ferret_enabled?(is_bulk_index = false) @ferret_disabled.nil? && (is_bulk_index || self.class.ferret_enabled?) && (aaf_configuration[:if].nil? || aaf_configuration[:if].call(self)) end
[ "def", "ferret_enabled?", "(", "is_bulk_index", "=", "false", ")", "@ferret_disabled", ".", "nil?", "&&", "(", "is_bulk_index", "||", "self", ".", "class", ".", "ferret_enabled?", ")", "&&", "(", "aaf_configuration", "[", ":if", "]", ".", "nil?", "||", "aaf_configuration", "[", ":if", "]", ".", "call", "(", "self", ")", ")", "end" ]
compatibility returns true if ferret indexing is enabled for this record. The optional is_bulk_index parameter will be true if the method is called by rebuild_index or bulk_index, and false otherwise. If is_bulk_index is true, the class level ferret_enabled state will be ignored by this method (per-instance ferret_enabled checks however will take place, so if you override this method to forbid indexing of certain records you're still safe).
[ "compatibility", "returns", "true", "if", "ferret", "indexing", "is", "enabled", "for", "this", "record", "." ]
1c3330c51a4d07298e6b89347077742636d9e3cf
https://github.com/jkraemer/acts_as_ferret/blob/1c3330c51a4d07298e6b89347077742636d9e3cf/lib/acts_as_ferret/instance_methods.rb#L49-L51
train
enebo/jmx
lib/jmx/notifier.rb
JMX.RubyNotificationEmitter.removeNotificationListener
def removeNotificationListener(listener, filter=nil, handback=nil) found = false listeners.delete_if do |clistener, (cfilter, chandback)| v = listener == clistener && filter == cfilter && handback == chandback found = true if v v end raise javax.management.ListenerNotFoundException.new unless found end
ruby
def removeNotificationListener(listener, filter=nil, handback=nil) found = false listeners.delete_if do |clistener, (cfilter, chandback)| v = listener == clistener && filter == cfilter && handback == chandback found = true if v v end raise javax.management.ListenerNotFoundException.new unless found end
[ "def", "removeNotificationListener", "(", "listener", ",", "filter", "=", "nil", ",", "handback", "=", "nil", ")", "found", "=", "false", "listeners", ".", "delete_if", "do", "|", "clistener", ",", "(", "cfilter", ",", "chandback", ")", "|", "v", "=", "listener", "==", "clistener", "&&", "filter", "==", "cfilter", "&&", "handback", "==", "chandback", "found", "=", "true", "if", "v", "v", "end", "raise", "javax", ".", "management", ".", "ListenerNotFoundException", ".", "new", "unless", "found", "end" ]
NotificationListener listener, NotificationFilter filter, Object handback
[ "NotificationListener", "listener", "NotificationFilter", "filter", "Object", "handback" ]
2418d7fcf941b2a5ee08a7881cff8c016dfd3ca7
https://github.com/enebo/jmx/blob/2418d7fcf941b2a5ee08a7881cff8c016dfd3ca7/lib/jmx/notifier.rb#L21-L29
train
enebo/jmx
lib/jmx/mbean_proxy.rb
JMX.MBeanProxy.[]
def [](name) attribute = @server.getAttribute(@object_name, name.to_s) return attribute.value if attribute.kind_of? javax.management.Attribute attribute end
ruby
def [](name) attribute = @server.getAttribute(@object_name, name.to_s) return attribute.value if attribute.kind_of? javax.management.Attribute attribute end
[ "def", "[]", "(", "name", ")", "attribute", "=", "@server", ".", "getAttribute", "(", "@object_name", ",", "name", ".", "to_s", ")", "return", "attribute", ".", "value", "if", "attribute", ".", "kind_of?", "javax", ".", "management", ".", "Attribute", "attribute", "end" ]
Get MBean attribute specified by name. If it is just a plain attribute then unwrap the attribute and just return the value.
[ "Get", "MBean", "attribute", "specified", "by", "name", ".", "If", "it", "is", "just", "a", "plain", "attribute", "then", "unwrap", "the", "attribute", "and", "just", "return", "the", "value", "." ]
2418d7fcf941b2a5ee08a7881cff8c016dfd3ca7
https://github.com/enebo/jmx/blob/2418d7fcf941b2a5ee08a7881cff8c016dfd3ca7/lib/jmx/mbean_proxy.rb#L61-L65
train
enebo/jmx
lib/jmx/mbean_proxy.rb
JMX.MBeanProxy.[]=
def []=(name, value) @server.setAttribute @object_name, javax.management.Attribute.new(name.to_s, value) end
ruby
def []=(name, value) @server.setAttribute @object_name, javax.management.Attribute.new(name.to_s, value) end
[ "def", "[]=", "(", "name", ",", "value", ")", "@server", ".", "setAttribute", "@object_name", ",", "javax", ".", "management", ".", "Attribute", ".", "new", "(", "name", ".", "to_s", ",", "value", ")", "end" ]
Set MBean attribute specified by name to value
[ "Set", "MBean", "attribute", "specified", "by", "name", "to", "value" ]
2418d7fcf941b2a5ee08a7881cff8c016dfd3ca7
https://github.com/enebo/jmx/blob/2418d7fcf941b2a5ee08a7881cff8c016dfd3ca7/lib/jmx/mbean_proxy.rb#L69-L71
train
enebo/jmx
lib/jmx/mbean_proxy.rb
JMX.MBeanProxy.invoke
def invoke(name, *params) op = @info.operations.find { |o| o.name == name.to_s } raise NoMethodError.new("No such operation #{name}") unless op jargs, jtypes = java_args(op.signature, params) @server.invoke @object_name, op.name, jargs, jtypes end
ruby
def invoke(name, *params) op = @info.operations.find { |o| o.name == name.to_s } raise NoMethodError.new("No such operation #{name}") unless op jargs, jtypes = java_args(op.signature, params) @server.invoke @object_name, op.name, jargs, jtypes end
[ "def", "invoke", "(", "name", ",", "*", "params", ")", "op", "=", "@info", ".", "operations", ".", "find", "{", "|", "o", "|", "o", ".", "name", "==", "name", ".", "to_s", "}", "raise", "NoMethodError", ".", "new", "(", "\"No such operation #{name}\"", ")", "unless", "op", "jargs", ",", "jtypes", "=", "java_args", "(", "op", ".", "signature", ",", "params", ")", "@server", ".", "invoke", "@object_name", ",", "op", ".", "name", ",", "jargs", ",", "jtypes", "end" ]
Invoke an operation. A NoMethodError will be thrown if this MBean cannot respond to the operation. FIXME: Add scoring to pick best match instead of first found
[ "Invoke", "an", "operation", ".", "A", "NoMethodError", "will", "be", "thrown", "if", "this", "MBean", "cannot", "respond", "to", "the", "operation", "." ]
2418d7fcf941b2a5ee08a7881cff8c016dfd3ca7
https://github.com/enebo/jmx/blob/2418d7fcf941b2a5ee08a7881cff8c016dfd3ca7/lib/jmx/mbean_proxy.rb#L78-L85
train
enebo/jmx
lib/jmx/mbean_proxy.rb
JMX.MBeanProxy.java_types
def java_types(params) return nil if params.nil? params.map {|e| e.class.java_class.name }.to_java(:string) end
ruby
def java_types(params) return nil if params.nil? params.map {|e| e.class.java_class.name }.to_java(:string) end
[ "def", "java_types", "(", "params", ")", "return", "nil", "if", "params", ".", "nil?", "params", ".", "map", "{", "|", "e", "|", "e", ".", "class", ".", "java_class", ".", "name", "}", ".", "to_java", "(", ":string", ")", "end" ]
Convert a collection of java objects to their Java class name equivalents
[ "Convert", "a", "collection", "of", "java", "objects", "to", "their", "Java", "class", "name", "equivalents" ]
2418d7fcf941b2a5ee08a7881cff8c016dfd3ca7
https://github.com/enebo/jmx/blob/2418d7fcf941b2a5ee08a7881cff8c016dfd3ca7/lib/jmx/mbean_proxy.rb#L154-L158
train
jmatsu/danger-apkstats
lib/apkstats/command/executable.rb
Apkstats::Command.Executable.compare_with
def compare_with(apk_filepath, other_apk_filepath) base = Apkstats::Entity::ApkInfo.new(self, apk_filepath) other = Apkstats::Entity::ApkInfo.new(self, other_apk_filepath) Apkstats::Entity::ApkInfoDiff.new(base, other).to_h end
ruby
def compare_with(apk_filepath, other_apk_filepath) base = Apkstats::Entity::ApkInfo.new(self, apk_filepath) other = Apkstats::Entity::ApkInfo.new(self, other_apk_filepath) Apkstats::Entity::ApkInfoDiff.new(base, other).to_h end
[ "def", "compare_with", "(", "apk_filepath", ",", "other_apk_filepath", ")", "base", "=", "Apkstats", "::", "Entity", "::", "ApkInfo", ".", "new", "(", "self", ",", "apk_filepath", ")", "other", "=", "Apkstats", "::", "Entity", "::", "ApkInfo", ".", "new", "(", "self", ",", "other_apk_filepath", ")", "Apkstats", "::", "Entity", "::", "ApkInfoDiff", ".", "new", "(", "base", ",", "other", ")", ".", "to_h", "end" ]
Compare two apk files and return results. { base: { file_size: Integer, download_size: Integer, required_features: Array<String>, non_required_features: Array<String>, permissions: Array<String>, min_sdk: String, target_sdk: String, method_reference_count: Integer, dex_count: Integer, }, other: { file_size: Integer, download_size: Integer, required_features: Array<String>, non_required_features: Array<String>, permissions: Array<String>, min_sdk: String, target_sdk: String, method_reference_count: Integer, dex_count: Integer, }, diff: { file_size: Integer, download_size: Integer, required_features: { new: Array<String>, removed: Array<String>, }, non_required_features:{ new: Array<String>, removed: Array<String>, }, permissions: { new: Array<String>, removed: Array<String>, }, min_sdk: Array<String>, target_sdk: Array<String>, method_reference_count: Integer, dex_count: Integer, } } @return [Hash]
[ "Compare", "two", "apk", "files", "and", "return", "results", "." ]
bc450681dc7bcc2bd340997f6f167ed3b430376e
https://github.com/jmatsu/danger-apkstats/blob/bc450681dc7bcc2bd340997f6f167ed3b430376e/lib/apkstats/command/executable.rb#L61-L66
train
xcres/xcres
lib/xcres/analyzer/analyzer.rb
XCRes.Analyzer.new_section
def new_section(name, data, options={}) XCRes::Section.new(name, data, self.options.merge(options)) end
ruby
def new_section(name, data, options={}) XCRes::Section.new(name, data, self.options.merge(options)) end
[ "def", "new_section", "(", "name", ",", "data", ",", "options", "=", "{", "}", ")", "XCRes", "::", "Section", ".", "new", "(", "name", ",", "data", ",", "self", ".", "options", ".", "merge", "(", "options", ")", ")", "end" ]
Create a new +Section+. @param [String] name see Section#name @param [Hash] items see Section#items @param [Hash] options see Section#options @return [XCRes::Section]
[ "Create", "a", "new", "+", "Section", "+", "." ]
4747b072ab316e7c6f389db9a3cad584e814fe43
https://github.com/xcres/xcres/blob/4747b072ab316e7c6f389db9a3cad584e814fe43/lib/xcres/analyzer/analyzer.rb#L80-L82
train
xcres/xcres
lib/xcres/analyzer/analyzer.rb
XCRes.Analyzer.filter_exclusions
def filter_exclusions file_paths file_paths.reject do |path| exclude_file_patterns.any? { |pattern| File.fnmatch("#{pattern}", path) || File.fnmatch("**/#{pattern}", path) } end end
ruby
def filter_exclusions file_paths file_paths.reject do |path| exclude_file_patterns.any? { |pattern| File.fnmatch("#{pattern}", path) || File.fnmatch("**/#{pattern}", path) } end end
[ "def", "filter_exclusions", "file_paths", "file_paths", ".", "reject", "do", "|", "path", "|", "exclude_file_patterns", ".", "any?", "{", "|", "pattern", "|", "File", ".", "fnmatch", "(", "\"#{pattern}\"", ",", "path", ")", "||", "File", ".", "fnmatch", "(", "\"**/#{pattern}\"", ",", "path", ")", "}", "end", "end" ]
Apply the configured exclude file patterns to a list of files @param [Array<Pathname>] file_paths the list of files to filter @param [Array<Pathname>] the filtered list of files
[ "Apply", "the", "configured", "exclude", "file", "patterns", "to", "a", "list", "of", "files" ]
4747b072ab316e7c6f389db9a3cad584e814fe43
https://github.com/xcres/xcres/blob/4747b072ab316e7c6f389db9a3cad584e814fe43/lib/xcres/analyzer/analyzer.rb#L92-L96
train
xcres/xcres
lib/xcres/analyzer/analyzer.rb
XCRes.Analyzer.find_file_refs_by_extname
def find_file_refs_by_extname(extname) project.files.select do |file_ref| File.extname(file_ref.path) == extname \ && is_file_ref_included_in_application_target?(file_ref) end end
ruby
def find_file_refs_by_extname(extname) project.files.select do |file_ref| File.extname(file_ref.path) == extname \ && is_file_ref_included_in_application_target?(file_ref) end end
[ "def", "find_file_refs_by_extname", "(", "extname", ")", "project", ".", "files", ".", "select", "do", "|", "file_ref", "|", "File", ".", "extname", "(", "file_ref", ".", "path", ")", "==", "extname", "&&", "is_file_ref_included_in_application_target?", "(", "file_ref", ")", "end", "end" ]
Discover all references to files with a specific extension in project, which belong to a resources build phase of an application target. @param [String] extname the extname, which contains a leading dot e.g.: '.bundle', '.strings' @return [Array<PBXFileReference>]
[ "Discover", "all", "references", "to", "files", "with", "a", "specific", "extension", "in", "project", "which", "belong", "to", "a", "resources", "build", "phase", "of", "an", "application", "target", "." ]
4747b072ab316e7c6f389db9a3cad584e814fe43
https://github.com/xcres/xcres/blob/4747b072ab316e7c6f389db9a3cad584e814fe43/lib/xcres/analyzer/analyzer.rb#L107-L112
train
xcres/xcres
lib/xcres/analyzer/analyzer.rb
XCRes.Analyzer.resources_files
def resources_files target.resources_build_phase.files.map do |build_file| if build_file.file_ref.is_a?(Xcodeproj::Project::Object::PBXGroup) build_file.file_ref.recursive_children else [build_file.file_ref] end end.flatten.compact end
ruby
def resources_files target.resources_build_phase.files.map do |build_file| if build_file.file_ref.is_a?(Xcodeproj::Project::Object::PBXGroup) build_file.file_ref.recursive_children else [build_file.file_ref] end end.flatten.compact end
[ "def", "resources_files", "target", ".", "resources_build_phase", ".", "files", ".", "map", "do", "|", "build_file", "|", "if", "build_file", ".", "file_ref", ".", "is_a?", "(", "Xcodeproj", "::", "Project", "::", "Object", "::", "PBXGroup", ")", "build_file", ".", "file_ref", ".", "recursive_children", "else", "[", "build_file", ".", "file_ref", "]", "end", "end", ".", "flatten", ".", "compact", "end" ]
Find files in resources build phases of application targets @return [Array<PBXFileReference>]
[ "Find", "files", "in", "resources", "build", "phases", "of", "application", "targets" ]
4747b072ab316e7c6f389db9a3cad584e814fe43
https://github.com/xcres/xcres/blob/4747b072ab316e7c6f389db9a3cad584e814fe43/lib/xcres/analyzer/analyzer.rb#L130-L138
train
siong1987/mongoid_shortener
app/controllers/mongoid_shortener/shortened_urls_controller.rb
MongoidShortener.ShortenedUrlsController.translate
def translate # pull the link out of the db sl = ShortenedUrl.where(:unique_key => params[:unique_key][1..-1]).first if sl sl.inc(:use_count, 1) # do a 301 redirect to the destination url head :moved_permanently, :location => sl.url else # if we don't find the shortened link, redirect to the root # make this configurable in future versions head :moved_permanently, :location => MongoidShortener.root_url end end
ruby
def translate # pull the link out of the db sl = ShortenedUrl.where(:unique_key => params[:unique_key][1..-1]).first if sl sl.inc(:use_count, 1) # do a 301 redirect to the destination url head :moved_permanently, :location => sl.url else # if we don't find the shortened link, redirect to the root # make this configurable in future versions head :moved_permanently, :location => MongoidShortener.root_url end end
[ "def", "translate", "sl", "=", "ShortenedUrl", ".", "where", "(", ":unique_key", "=>", "params", "[", ":unique_key", "]", "[", "1", "..", "-", "1", "]", ")", ".", "first", "if", "sl", "sl", ".", "inc", "(", ":use_count", ",", "1", ")", "head", ":moved_permanently", ",", ":location", "=>", "sl", ".", "url", "else", "head", ":moved_permanently", ",", ":location", "=>", "MongoidShortener", ".", "root_url", "end", "end" ]
find the real link for the shortened link key and redirect
[ "find", "the", "real", "link", "for", "the", "shortened", "link", "key", "and", "redirect" ]
32888cef58d9980d01d04d2ef42ad49ae5d06d04
https://github.com/siong1987/mongoid_shortener/blob/32888cef58d9980d01d04d2ef42ad49ae5d06d04/app/controllers/mongoid_shortener/shortened_urls_controller.rb#L4-L17
train
jkraemer/acts_as_ferret
lib/acts_as_ferret/act_methods.rb
ActsAsFerret.ActMethods.acts_as_ferret
def acts_as_ferret(options={}) extend ClassMethods include InstanceMethods include MoreLikeThis::InstanceMethods if options[:rdig] cattr_accessor :rdig_configuration self.rdig_configuration = options[:rdig] require 'rdig_adapter' include ActsAsFerret::RdigAdapter end unless included_modules.include?(ActsAsFerret::WithoutAR) # set up AR hooks after_create :ferret_create after_update :ferret_update after_destroy :ferret_destroy end cattr_accessor :aaf_configuration # apply default config for rdig based models if options[:rdig] options[:fields] ||= { :title => { :boost => 3, :store => :yes }, :content => { :store => :yes } } end # name of this index index_name = options.delete(:index) || self.name.underscore index = ActsAsFerret::register_class_with_index(self, index_name, options) self.aaf_configuration = index.index_definition.dup # logger.debug "configured index for class #{self.name}:\n#{aaf_configuration.inspect}" # update our copy of the global index config with options local to this class aaf_configuration[:class_name] ||= self.name aaf_configuration[:if] ||= options[:if] # add methods for retrieving field values add_fields options[:fields] add_fields options[:additional_fields] add_fields aaf_configuration[:fields] add_fields aaf_configuration[:additional_fields] end
ruby
def acts_as_ferret(options={}) extend ClassMethods include InstanceMethods include MoreLikeThis::InstanceMethods if options[:rdig] cattr_accessor :rdig_configuration self.rdig_configuration = options[:rdig] require 'rdig_adapter' include ActsAsFerret::RdigAdapter end unless included_modules.include?(ActsAsFerret::WithoutAR) # set up AR hooks after_create :ferret_create after_update :ferret_update after_destroy :ferret_destroy end cattr_accessor :aaf_configuration # apply default config for rdig based models if options[:rdig] options[:fields] ||= { :title => { :boost => 3, :store => :yes }, :content => { :store => :yes } } end # name of this index index_name = options.delete(:index) || self.name.underscore index = ActsAsFerret::register_class_with_index(self, index_name, options) self.aaf_configuration = index.index_definition.dup # logger.debug "configured index for class #{self.name}:\n#{aaf_configuration.inspect}" # update our copy of the global index config with options local to this class aaf_configuration[:class_name] ||= self.name aaf_configuration[:if] ||= options[:if] # add methods for retrieving field values add_fields options[:fields] add_fields options[:additional_fields] add_fields aaf_configuration[:fields] add_fields aaf_configuration[:additional_fields] end
[ "def", "acts_as_ferret", "(", "options", "=", "{", "}", ")", "extend", "ClassMethods", "include", "InstanceMethods", "include", "MoreLikeThis", "::", "InstanceMethods", "if", "options", "[", ":rdig", "]", "cattr_accessor", ":rdig_configuration", "self", ".", "rdig_configuration", "=", "options", "[", ":rdig", "]", "require", "'rdig_adapter'", "include", "ActsAsFerret", "::", "RdigAdapter", "end", "unless", "included_modules", ".", "include?", "(", "ActsAsFerret", "::", "WithoutAR", ")", "after_create", ":ferret_create", "after_update", ":ferret_update", "after_destroy", ":ferret_destroy", "end", "cattr_accessor", ":aaf_configuration", "if", "options", "[", ":rdig", "]", "options", "[", ":fields", "]", "||=", "{", ":title", "=>", "{", ":boost", "=>", "3", ",", ":store", "=>", ":yes", "}", ",", ":content", "=>", "{", ":store", "=>", ":yes", "}", "}", "end", "index_name", "=", "options", ".", "delete", "(", ":index", ")", "||", "self", ".", "name", ".", "underscore", "index", "=", "ActsAsFerret", "::", "register_class_with_index", "(", "self", ",", "index_name", ",", "options", ")", "self", ".", "aaf_configuration", "=", "index", ".", "index_definition", ".", "dup", "aaf_configuration", "[", ":class_name", "]", "||=", "self", ".", "name", "aaf_configuration", "[", ":if", "]", "||=", "options", "[", ":if", "]", "add_fields", "options", "[", ":fields", "]", "add_fields", "options", "[", ":additional_fields", "]", "add_fields", "aaf_configuration", "[", ":fields", "]", "add_fields", "aaf_configuration", "[", ":additional_fields", "]", "end" ]
declares a class as ferret-searchable. ====options: fields:: names all fields to include in the index. If not given, all attributes of the class will be indexed. You may also give symbols pointing to instance methods of your model here, i.e. to retrieve and index data from a related model. additional_fields:: names fields to include in the index, in addition to those derived from the db scheme. use if you want to add custom fields derived from methods to the db fields (which will be picked by aaf). This option will be ignored when the fields option is given, in that case additional fields get specified there. if:: Can be set to a block that will be called with the record in question to determine if it should be indexed or not. index_dir:: declares the directory where to put the index for this class. The default is Rails.root/index/Rails.env/CLASSNAME. The index directory will be created if it doesn't exist. reindex_batch_size:: reindexing is done in batches of this size, default is 1000 mysql_fast_batches:: set this to false to disable the faster mysql batching algorithm if this model uses a non-integer primary key named 'id' on MySQL. ferret:: Hash of Options that directly influence the way the Ferret engine works. You can use most of the options the Ferret::I class accepts here, too. Among the more useful are: or_default:: whether query terms are required by default (the default, false), or not (true) analyzer:: the analyzer to use for query parsing (default: nil, which means the ferret StandardAnalyzer gets used) default_field:: use to set one or more fields that are searched for query terms that don't have an explicit field list. This list should *not* contain any untokenized fields. If it does, you're asking for trouble (i.e. not getting results for queries having stop words in them). Aaf by default initializes the default field list to contain all tokenized fields. If you use :single_index => true, you really should set this option specifying your default field list (which should be equal in all your classes sharing the index). Otherwise you might get incorrect search results and you won't get any lazy loading of stored field data. For downwards compatibility reasons you can also specify the Ferret options in the last Hash argument.
[ "declares", "a", "class", "as", "ferret", "-", "searchable", "." ]
1c3330c51a4d07298e6b89347077742636d9e3cf
https://github.com/jkraemer/acts_as_ferret/blob/1c3330c51a4d07298e6b89347077742636d9e3cf/lib/acts_as_ferret/act_methods.rb#L60-L106
train
jkraemer/acts_as_ferret
lib/acts_as_ferret/act_methods.rb
ActsAsFerret.ActMethods.define_to_field_method
def define_to_field_method(field, options = {}) method_name = "#{field}_to_ferret" return if instance_methods.include?(method_name) # already defined aaf_configuration[:defined_fields] ||= {} aaf_configuration[:defined_fields][field] = options dynamic_boost = options[:boost] if options[:boost].is_a?(Symbol) via = options[:via] || field define_method(method_name.to_sym) do val = begin content_for_field_name(field, via, dynamic_boost) rescue logger.warn("Error retrieving value for field #{field}: #{$!}") '' end logger.debug("Adding field #{field} with value '#{val}' to index") val end end
ruby
def define_to_field_method(field, options = {}) method_name = "#{field}_to_ferret" return if instance_methods.include?(method_name) # already defined aaf_configuration[:defined_fields] ||= {} aaf_configuration[:defined_fields][field] = options dynamic_boost = options[:boost] if options[:boost].is_a?(Symbol) via = options[:via] || field define_method(method_name.to_sym) do val = begin content_for_field_name(field, via, dynamic_boost) rescue logger.warn("Error retrieving value for field #{field}: #{$!}") '' end logger.debug("Adding field #{field} with value '#{val}' to index") val end end
[ "def", "define_to_field_method", "(", "field", ",", "options", "=", "{", "}", ")", "method_name", "=", "\"#{field}_to_ferret\"", "return", "if", "instance_methods", ".", "include?", "(", "method_name", ")", "aaf_configuration", "[", ":defined_fields", "]", "||=", "{", "}", "aaf_configuration", "[", ":defined_fields", "]", "[", "field", "]", "=", "options", "dynamic_boost", "=", "options", "[", ":boost", "]", "if", "options", "[", ":boost", "]", ".", "is_a?", "(", "Symbol", ")", "via", "=", "options", "[", ":via", "]", "||", "field", "define_method", "(", "method_name", ".", "to_sym", ")", "do", "val", "=", "begin", "content_for_field_name", "(", "field", ",", "via", ",", "dynamic_boost", ")", "rescue", "logger", ".", "warn", "(", "\"Error retrieving value for field #{field}: #{$!}\"", ")", "''", "end", "logger", ".", "debug", "(", "\"Adding field #{field} with value '#{val}' to index\"", ")", "val", "end", "end" ]
helper to defines a method which adds the given field to a ferret document instance
[ "helper", "to", "defines", "a", "method", "which", "adds", "the", "given", "field", "to", "a", "ferret", "document", "instance" ]
1c3330c51a4d07298e6b89347077742636d9e3cf
https://github.com/jkraemer/acts_as_ferret/blob/1c3330c51a4d07298e6b89347077742636d9e3cf/lib/acts_as_ferret/act_methods.rb#L114-L131
train
nicholasjackson/minke
lib/minke/command.rb
Minke.Command.create_dependencies
def create_dependencies task project_name = "minke#{SecureRandom.urlsafe_base64(12)}".downcase.gsub(/[^0-9a-z ]/i, '') network_name = ENV['DOCKER_NETWORK'] ||= "#{project_name}_default" ENV['DOCKER_PROJECT'] = project_name ENV['DOCKER_NETWORK'] = network_name logger = Minke::Logging.create_logger(STDOUT, self.verbose) shell = Minke::Helpers::Shell.new(logger) task_runner = Minke::Tasks::TaskRunner.new ({ :ruby_helper => Minke::Helpers::Ruby.new, :copy_helper => Minke::Helpers::Copy.new, :service_discovery => Minke::Docker::ServiceDiscovery.new(project_name, Minke::Docker::DockerRunner.new(logger), network_name), :logger_helper => logger }) consul = Minke::Docker::Consul.new( { :health_check => Minke::Docker::HealthCheck.new(logger), :service_discovery => Minke::Docker::ServiceDiscovery.new( project_name, Minke::Docker::DockerRunner.new(logger, network_name), network_name), :consul_loader => ConsulLoader::Loader.new(ConsulLoader::ConfigParser.new), :docker_runner => Minke::Docker::DockerRunner.new(logger, network_name), :network => network_name, :project_name => project_name, :logger_helper => logger } ) network = Minke::Docker::Network.new( network_name, shell ) return { :config => @config, :task_name => task, :docker_runner => Minke::Docker::DockerRunner.new(logger, network_name, project_name), :task_runner => task_runner, :shell_helper => shell, :logger_helper => logger, :generator_config => generator_config, :docker_compose_factory => Minke::Docker::DockerComposeFactory.new(shell, project_name, network_name), :consul => consul, :docker_network => network, :health_check => Minke::Docker::HealthCheck.new(logger), :service_discovery => Minke::Docker::ServiceDiscovery.new(project_name, Minke::Docker::DockerRunner.new(logger), network_name) } end
ruby
def create_dependencies task project_name = "minke#{SecureRandom.urlsafe_base64(12)}".downcase.gsub(/[^0-9a-z ]/i, '') network_name = ENV['DOCKER_NETWORK'] ||= "#{project_name}_default" ENV['DOCKER_PROJECT'] = project_name ENV['DOCKER_NETWORK'] = network_name logger = Minke::Logging.create_logger(STDOUT, self.verbose) shell = Minke::Helpers::Shell.new(logger) task_runner = Minke::Tasks::TaskRunner.new ({ :ruby_helper => Minke::Helpers::Ruby.new, :copy_helper => Minke::Helpers::Copy.new, :service_discovery => Minke::Docker::ServiceDiscovery.new(project_name, Minke::Docker::DockerRunner.new(logger), network_name), :logger_helper => logger }) consul = Minke::Docker::Consul.new( { :health_check => Minke::Docker::HealthCheck.new(logger), :service_discovery => Minke::Docker::ServiceDiscovery.new( project_name, Minke::Docker::DockerRunner.new(logger, network_name), network_name), :consul_loader => ConsulLoader::Loader.new(ConsulLoader::ConfigParser.new), :docker_runner => Minke::Docker::DockerRunner.new(logger, network_name), :network => network_name, :project_name => project_name, :logger_helper => logger } ) network = Minke::Docker::Network.new( network_name, shell ) return { :config => @config, :task_name => task, :docker_runner => Minke::Docker::DockerRunner.new(logger, network_name, project_name), :task_runner => task_runner, :shell_helper => shell, :logger_helper => logger, :generator_config => generator_config, :docker_compose_factory => Minke::Docker::DockerComposeFactory.new(shell, project_name, network_name), :consul => consul, :docker_network => network, :health_check => Minke::Docker::HealthCheck.new(logger), :service_discovery => Minke::Docker::ServiceDiscovery.new(project_name, Minke::Docker::DockerRunner.new(logger), network_name) } end
[ "def", "create_dependencies", "task", "project_name", "=", "\"minke#{SecureRandom.urlsafe_base64(12)}\"", ".", "downcase", ".", "gsub", "(", "/", "/i", ",", "''", ")", "network_name", "=", "ENV", "[", "'DOCKER_NETWORK'", "]", "||=", "\"#{project_name}_default\"", "ENV", "[", "'DOCKER_PROJECT'", "]", "=", "project_name", "ENV", "[", "'DOCKER_NETWORK'", "]", "=", "network_name", "logger", "=", "Minke", "::", "Logging", ".", "create_logger", "(", "STDOUT", ",", "self", ".", "verbose", ")", "shell", "=", "Minke", "::", "Helpers", "::", "Shell", ".", "new", "(", "logger", ")", "task_runner", "=", "Minke", "::", "Tasks", "::", "TaskRunner", ".", "new", "(", "{", ":ruby_helper", "=>", "Minke", "::", "Helpers", "::", "Ruby", ".", "new", ",", ":copy_helper", "=>", "Minke", "::", "Helpers", "::", "Copy", ".", "new", ",", ":service_discovery", "=>", "Minke", "::", "Docker", "::", "ServiceDiscovery", ".", "new", "(", "project_name", ",", "Minke", "::", "Docker", "::", "DockerRunner", ".", "new", "(", "logger", ")", ",", "network_name", ")", ",", ":logger_helper", "=>", "logger", "}", ")", "consul", "=", "Minke", "::", "Docker", "::", "Consul", ".", "new", "(", "{", ":health_check", "=>", "Minke", "::", "Docker", "::", "HealthCheck", ".", "new", "(", "logger", ")", ",", ":service_discovery", "=>", "Minke", "::", "Docker", "::", "ServiceDiscovery", ".", "new", "(", "project_name", ",", "Minke", "::", "Docker", "::", "DockerRunner", ".", "new", "(", "logger", ",", "network_name", ")", ",", "network_name", ")", ",", ":consul_loader", "=>", "ConsulLoader", "::", "Loader", ".", "new", "(", "ConsulLoader", "::", "ConfigParser", ".", "new", ")", ",", ":docker_runner", "=>", "Minke", "::", "Docker", "::", "DockerRunner", ".", "new", "(", "logger", ",", "network_name", ")", ",", ":network", "=>", "network_name", ",", ":project_name", "=>", "project_name", ",", ":logger_helper", "=>", "logger", "}", ")", "network", "=", "Minke", "::", "Docker", "::", "Network", ".", "new", "(", "network_name", ",", "shell", ")", "return", "{", ":config", "=>", "@config", ",", ":task_name", "=>", "task", ",", ":docker_runner", "=>", "Minke", "::", "Docker", "::", "DockerRunner", ".", "new", "(", "logger", ",", "network_name", ",", "project_name", ")", ",", ":task_runner", "=>", "task_runner", ",", ":shell_helper", "=>", "shell", ",", ":logger_helper", "=>", "logger", ",", ":generator_config", "=>", "generator_config", ",", ":docker_compose_factory", "=>", "Minke", "::", "Docker", "::", "DockerComposeFactory", ".", "new", "(", "shell", ",", "project_name", ",", "network_name", ")", ",", ":consul", "=>", "consul", ",", ":docker_network", "=>", "network", ",", ":health_check", "=>", "Minke", "::", "Docker", "::", "HealthCheck", ".", "new", "(", "logger", ")", ",", ":service_discovery", "=>", "Minke", "::", "Docker", "::", "ServiceDiscovery", ".", "new", "(", "project_name", ",", "Minke", "::", "Docker", "::", "DockerRunner", ".", "new", "(", "logger", ")", ",", "network_name", ")", "}", "end" ]
Creates dependencies for minke
[ "Creates", "dependencies", "for", "minke" ]
56de4de0bcc2eebc72583fedf4fe812b6f519ffb
https://github.com/nicholasjackson/minke/blob/56de4de0bcc2eebc72583fedf4fe812b6f519ffb/lib/minke/command.rb#L13-L60
train
holman/rapinoe
lib/rapinoe/slide.rb
Rapinoe.Slide.write_preview_to_file
def write_preview_to_file(path) FileUtils.mkdir_p(File.dirname(path)) File.open(path, 'wb') do |out| out.write(preview_data) end end
ruby
def write_preview_to_file(path) FileUtils.mkdir_p(File.dirname(path)) File.open(path, 'wb') do |out| out.write(preview_data) end end
[ "def", "write_preview_to_file", "(", "path", ")", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "path", ")", ")", "File", ".", "open", "(", "path", ",", "'wb'", ")", "do", "|", "out", "|", "out", ".", "write", "(", "preview_data", ")", "end", "end" ]
Writes the preview for this slide to disk.
[ "Writes", "the", "preview", "for", "this", "slide", "to", "disk", "." ]
6e76d8e2f16f5e7af859c4b16417c442166f19e6
https://github.com/holman/rapinoe/blob/6e76d8e2f16f5e7af859c4b16417c442166f19e6/lib/rapinoe/slide.rb#L35-L40
train
gemnasium/gemnasium-gem
lib/gemnasium/configuration.rb
Gemnasium.Configuration.is_valid?
def is_valid? site_option_valid = !site.nil? && !site.empty? api_key_option_valid = !api_key.nil? && !api_key.empty? use_ssl_option_valid = !use_ssl.nil? && !!use_ssl == use_ssl # Check this is a boolean api_version_option_valid = !api_version.nil? && !api_version.empty? project_name_option_valid = !project_name.nil? && !project_name.empty? ignored_paths_option_valid = ignored_paths.kind_of?(Array) site_option_valid && api_key_option_valid && use_ssl_option_valid && api_version_option_valid && project_name_option_valid && ignored_paths_option_valid end
ruby
def is_valid? site_option_valid = !site.nil? && !site.empty? api_key_option_valid = !api_key.nil? && !api_key.empty? use_ssl_option_valid = !use_ssl.nil? && !!use_ssl == use_ssl # Check this is a boolean api_version_option_valid = !api_version.nil? && !api_version.empty? project_name_option_valid = !project_name.nil? && !project_name.empty? ignored_paths_option_valid = ignored_paths.kind_of?(Array) site_option_valid && api_key_option_valid && use_ssl_option_valid && api_version_option_valid && project_name_option_valid && ignored_paths_option_valid end
[ "def", "is_valid?", "site_option_valid", "=", "!", "site", ".", "nil?", "&&", "!", "site", ".", "empty?", "api_key_option_valid", "=", "!", "api_key", ".", "nil?", "&&", "!", "api_key", ".", "empty?", "use_ssl_option_valid", "=", "!", "use_ssl", ".", "nil?", "&&", "!", "!", "use_ssl", "==", "use_ssl", "api_version_option_valid", "=", "!", "api_version", ".", "nil?", "&&", "!", "api_version", ".", "empty?", "project_name_option_valid", "=", "!", "project_name", ".", "nil?", "&&", "!", "project_name", ".", "empty?", "ignored_paths_option_valid", "=", "ignored_paths", ".", "kind_of?", "(", "Array", ")", "site_option_valid", "&&", "api_key_option_valid", "&&", "use_ssl_option_valid", "&&", "api_version_option_valid", "&&", "project_name_option_valid", "&&", "ignored_paths_option_valid", "end" ]
Check that mandatory parameters are not nil and contain valid values @return [Boolean] if configuration is valid
[ "Check", "that", "mandatory", "parameters", "are", "not", "nil", "and", "contain", "valid", "values" ]
882b43337b4f483cdd0f93fff2e3db96d94998e0
https://github.com/gemnasium/gemnasium-gem/blob/882b43337b4f483cdd0f93fff2e3db96d94998e0/lib/gemnasium/configuration.rb#L87-L97
train
postmodern/gscraper
lib/gscraper/sponsored_links.rb
GScraper.SponsoredLinks.ads_with_title
def ads_with_title(title) return enum_for(:ads_with_title,title) unless block_given? comparitor = if title.kind_of?(Regexp) lambda { |ad| ad.title =~ title } else lambda { |ad| ad.title == title } end return ads_with do |ad| if comparitor.call(ad) yield ad true end end end
ruby
def ads_with_title(title) return enum_for(:ads_with_title,title) unless block_given? comparitor = if title.kind_of?(Regexp) lambda { |ad| ad.title =~ title } else lambda { |ad| ad.title == title } end return ads_with do |ad| if comparitor.call(ad) yield ad true end end end
[ "def", "ads_with_title", "(", "title", ")", "return", "enum_for", "(", ":ads_with_title", ",", "title", ")", "unless", "block_given?", "comparitor", "=", "if", "title", ".", "kind_of?", "(", "Regexp", ")", "lambda", "{", "|", "ad", "|", "ad", ".", "title", "=~", "title", "}", "else", "lambda", "{", "|", "ad", "|", "ad", ".", "title", "==", "title", "}", "end", "return", "ads_with", "do", "|", "ad", "|", "if", "comparitor", ".", "call", "(", "ad", ")", "yield", "ad", "true", "end", "end", "end" ]
Selects the ads with the matching title. @param [String, Regexp] title The title to search for. @yield [ad] Each matching ad will be passed to the given block. @yieldparam [SponsoredAd] ad A sponsored ad with the matching title. @return [Array, Enumerator] The sponsored ads with the matching title. If no block is given, an Enumerator object will be returned. @example sponsored.ads_with_title('be attractive') # => SponsoredLinks @example sponsored.ads_with_title(/buy me/) do |ad| puts ad.url end
[ "Selects", "the", "ads", "with", "the", "matching", "title", "." ]
8370880a7b0c03b3c12a5ba3dfc19a6230187d6a
https://github.com/postmodern/gscraper/blob/8370880a7b0c03b3c12a5ba3dfc19a6230187d6a/lib/gscraper/sponsored_links.rb#L126-L142
train
postmodern/gscraper
lib/gscraper/sponsored_links.rb
GScraper.SponsoredLinks.ads_with_url
def ads_with_url(url) return enum_for(:ads_with_url,url) unless block_given? comparitor = if url.kind_of?(Regexp) lambda { |ad| ad.url =~ url } else lambda { |ad| ad.url == url } end return ads_with do |ad| if comparitor.call(ad) yield ad true end end end
ruby
def ads_with_url(url) return enum_for(:ads_with_url,url) unless block_given? comparitor = if url.kind_of?(Regexp) lambda { |ad| ad.url =~ url } else lambda { |ad| ad.url == url } end return ads_with do |ad| if comparitor.call(ad) yield ad true end end end
[ "def", "ads_with_url", "(", "url", ")", "return", "enum_for", "(", ":ads_with_url", ",", "url", ")", "unless", "block_given?", "comparitor", "=", "if", "url", ".", "kind_of?", "(", "Regexp", ")", "lambda", "{", "|", "ad", "|", "ad", ".", "url", "=~", "url", "}", "else", "lambda", "{", "|", "ad", "|", "ad", ".", "url", "==", "url", "}", "end", "return", "ads_with", "do", "|", "ad", "|", "if", "comparitor", ".", "call", "(", "ad", ")", "yield", "ad", "true", "end", "end", "end" ]
Selects the ads with the matching URL. @param [String, Regexp] url The URL to search for. @yield [ad] Each matching ad will be passed to the given block. @yieldparam [SponsoredAd] ad A sponsored ad with the matching URL. @return [Array, Enumerator] The sponsored ads with the matching URL. If no block is given, an Enumerator object will be returned. @example sponsored.ads_with_url(/\.com/) # => SponsoredLinks
[ "Selects", "the", "ads", "with", "the", "matching", "URL", "." ]
8370880a7b0c03b3c12a5ba3dfc19a6230187d6a
https://github.com/postmodern/gscraper/blob/8370880a7b0c03b3c12a5ba3dfc19a6230187d6a/lib/gscraper/sponsored_links.rb#L164-L180
train
postmodern/gscraper
lib/gscraper/sponsored_links.rb
GScraper.SponsoredLinks.ads_with_direct_url
def ads_with_direct_url(direct_url) return enum_for(:ads_with_direct_url,direct_url) unless block_given? comparitor = if direct_url.kind_of?(Regexp) lambda { |ad| ad.direct_url =~ direct_url } else lambda { |ad| ad.direct_url == direct_url } end return ads_with do |ad| if comparitor.call(ad) yield ad true end end end
ruby
def ads_with_direct_url(direct_url) return enum_for(:ads_with_direct_url,direct_url) unless block_given? comparitor = if direct_url.kind_of?(Regexp) lambda { |ad| ad.direct_url =~ direct_url } else lambda { |ad| ad.direct_url == direct_url } end return ads_with do |ad| if comparitor.call(ad) yield ad true end end end
[ "def", "ads_with_direct_url", "(", "direct_url", ")", "return", "enum_for", "(", ":ads_with_direct_url", ",", "direct_url", ")", "unless", "block_given?", "comparitor", "=", "if", "direct_url", ".", "kind_of?", "(", "Regexp", ")", "lambda", "{", "|", "ad", "|", "ad", ".", "direct_url", "=~", "direct_url", "}", "else", "lambda", "{", "|", "ad", "|", "ad", ".", "direct_url", "==", "direct_url", "}", "end", "return", "ads_with", "do", "|", "ad", "|", "if", "comparitor", ".", "call", "(", "ad", ")", "yield", "ad", "true", "end", "end", "end" ]
Selects the ads with the matching direct URL. @param [String, Regexp] direct_url The direct URL to search for. @yield [ad] Each matching ad will be passed to the given block. @yieldparam [SponsoredAd] ad A sponsored ad with the matching direct URL. @return [Array, Enumerator] The sponsored ads with the matching URL. If no block is given, an Enumerator object will be returned. @example sponsored.ads_with_direct_url(/\.com/) # => SponsoredLinks
[ "Selects", "the", "ads", "with", "the", "matching", "direct", "URL", "." ]
8370880a7b0c03b3c12a5ba3dfc19a6230187d6a
https://github.com/postmodern/gscraper/blob/8370880a7b0c03b3c12a5ba3dfc19a6230187d6a/lib/gscraper/sponsored_links.rb#L202-L218
train
holman/rapinoe
lib/rapinoe/keynote.rb
Rapinoe.Keynote.aspect_ratio
def aspect_ratio path = "/tmp/rapinoe-aspect" write_preview_to_file(path) dimensions = FastImage.size(path) widescreen = (16/9.0) if widescreen == (dimensions[0] / dimensions[1].to_f) :widescreen else :standard end end
ruby
def aspect_ratio path = "/tmp/rapinoe-aspect" write_preview_to_file(path) dimensions = FastImage.size(path) widescreen = (16/9.0) if widescreen == (dimensions[0] / dimensions[1].to_f) :widescreen else :standard end end
[ "def", "aspect_ratio", "path", "=", "\"/tmp/rapinoe-aspect\"", "write_preview_to_file", "(", "path", ")", "dimensions", "=", "FastImage", ".", "size", "(", "path", ")", "widescreen", "=", "(", "16", "/", "9.0", ")", "if", "widescreen", "==", "(", "dimensions", "[", "0", "]", "/", "dimensions", "[", "1", "]", ".", "to_f", ")", ":widescreen", "else", ":standard", "end", "end" ]
The aspect ratio of the deck. Returns a Symbol, either :widescreen or :standard (4:3).
[ "The", "aspect", "ratio", "of", "the", "deck", "." ]
6e76d8e2f16f5e7af859c4b16417c442166f19e6
https://github.com/holman/rapinoe/blob/6e76d8e2f16f5e7af859c4b16417c442166f19e6/lib/rapinoe/keynote.rb#L31-L43
train
holman/rapinoe
lib/rapinoe/keynote.rb
Rapinoe.Keynote.colors
def colors return @colors if @colors path = "/tmp/rapinoe-aspect" write_preview_to_file(path) colors = Miro::DominantColors.new(path) by_percentage = colors.by_percentage hash = {} colors.to_rgb.each_with_index do |hex, i| hash[hex] = by_percentage[i] end @colors = hash end
ruby
def colors return @colors if @colors path = "/tmp/rapinoe-aspect" write_preview_to_file(path) colors = Miro::DominantColors.new(path) by_percentage = colors.by_percentage hash = {} colors.to_rgb.each_with_index do |hex, i| hash[hex] = by_percentage[i] end @colors = hash end
[ "def", "colors", "return", "@colors", "if", "@colors", "path", "=", "\"/tmp/rapinoe-aspect\"", "write_preview_to_file", "(", "path", ")", "colors", "=", "Miro", "::", "DominantColors", ".", "new", "(", "path", ")", "by_percentage", "=", "colors", ".", "by_percentage", "hash", "=", "{", "}", "colors", ".", "to_rgb", ".", "each_with_index", "do", "|", "hex", ",", "i", "|", "hash", "[", "hex", "]", "=", "by_percentage", "[", "i", "]", "end", "@colors", "=", "hash", "end" ]
The top colors present in the title slide. This returns a Hash of the color (in RGB) and its percentage in the frame. For example: { [1, 1, 1] => 0.7296031746031746, [8, 12, 15] => 0.13706349206349205, [ … ] }
[ "The", "top", "colors", "present", "in", "the", "title", "slide", "." ]
6e76d8e2f16f5e7af859c4b16417c442166f19e6
https://github.com/holman/rapinoe/blob/6e76d8e2f16f5e7af859c4b16417c442166f19e6/lib/rapinoe/keynote.rb#L60-L75
train
xcres/xcres
lib/xcres/model/xcassets/resource_image.rb
XCRes::XCAssets.ResourceImage.read
def read(hash) self.scale = hash.delete('scale').sub(/x$/, '').to_i unless hash['scale'].nil? KNOWN_KEYS.each do |key| value = hash.delete(key.to_s.dasherize) next if value.nil? self.send "#{key}=".to_sym, value end self.attributes = hash return self end
ruby
def read(hash) self.scale = hash.delete('scale').sub(/x$/, '').to_i unless hash['scale'].nil? KNOWN_KEYS.each do |key| value = hash.delete(key.to_s.dasherize) next if value.nil? self.send "#{key}=".to_sym, value end self.attributes = hash return self end
[ "def", "read", "(", "hash", ")", "self", ".", "scale", "=", "hash", ".", "delete", "(", "'scale'", ")", ".", "sub", "(", "/", "/", ",", "''", ")", ".", "to_i", "unless", "hash", "[", "'scale'", "]", ".", "nil?", "KNOWN_KEYS", ".", "each", "do", "|", "key", "|", "value", "=", "hash", ".", "delete", "(", "key", ".", "to_s", ".", "dasherize", ")", "next", "if", "value", ".", "nil?", "self", ".", "send", "\"#{key}=\"", ".", "to_sym", ",", "value", "end", "self", ".", "attributes", "=", "hash", "return", "self", "end" ]
Initialize a new ResourceImage @param [Hash] the initial attribute values Read from hash @param [Hash] the hash to deserialize @return [ResourceImage]
[ "Initialize", "a", "new", "ResourceImage" ]
4747b072ab316e7c6f389db9a3cad584e814fe43
https://github.com/xcres/xcres/blob/4747b072ab316e7c6f389db9a3cad584e814fe43/lib/xcres/model/xcassets/resource_image.rb#L90-L102
train
xcres/xcres
lib/xcres/model/xcassets/resource_image.rb
XCRes::XCAssets.ResourceImage.to_hash
def to_hash hash = {} hash['scale'] = "#{scale}x" unless scale.nil? (KNOWN_KEYS - [:scale]).each do |key| value = self.send(key) hash[key.to_s.dasherize] = value.to_s unless value.nil? end attributes.each do |key, value| hash[key.to_s] = value end hash end
ruby
def to_hash hash = {} hash['scale'] = "#{scale}x" unless scale.nil? (KNOWN_KEYS - [:scale]).each do |key| value = self.send(key) hash[key.to_s.dasherize] = value.to_s unless value.nil? end attributes.each do |key, value| hash[key.to_s] = value end hash end
[ "def", "to_hash", "hash", "=", "{", "}", "hash", "[", "'scale'", "]", "=", "\"#{scale}x\"", "unless", "scale", ".", "nil?", "(", "KNOWN_KEYS", "-", "[", ":scale", "]", ")", ".", "each", "do", "|", "key", "|", "value", "=", "self", ".", "send", "(", "key", ")", "hash", "[", "key", ".", "to_s", ".", "dasherize", "]", "=", "value", ".", "to_s", "unless", "value", ".", "nil?", "end", "attributes", ".", "each", "do", "|", "key", ",", "value", "|", "hash", "[", "key", ".", "to_s", "]", "=", "value", "end", "hash", "end" ]
Serialize to hash @return [Hash{String => String}]
[ "Serialize", "to", "hash" ]
4747b072ab316e7c6f389db9a3cad584e814fe43
https://github.com/xcres/xcres/blob/4747b072ab316e7c6f389db9a3cad584e814fe43/lib/xcres/model/xcassets/resource_image.rb#L108-L123
train
xcres/xcres
lib/xcres/analyzer/aggregate_analyzer.rb
XCRes.AggregateAnalyzer.add_with_class
def add_with_class(analyzer_class, options={}) analyzer = analyzer_class.new(target, self.options.merge(options)) analyzer.exclude_file_patterns = exclude_file_patterns analyzer.logger = logger self.analyzers << analyzer analyzer end
ruby
def add_with_class(analyzer_class, options={}) analyzer = analyzer_class.new(target, self.options.merge(options)) analyzer.exclude_file_patterns = exclude_file_patterns analyzer.logger = logger self.analyzers << analyzer analyzer end
[ "def", "add_with_class", "(", "analyzer_class", ",", "options", "=", "{", "}", ")", "analyzer", "=", "analyzer_class", ".", "new", "(", "target", ",", "self", ".", "options", ".", "merge", "(", "options", ")", ")", "analyzer", ".", "exclude_file_patterns", "=", "exclude_file_patterns", "analyzer", ".", "logger", "=", "logger", "self", ".", "analyzers", "<<", "analyzer", "analyzer", "end" ]
Instantiate and add an analyzer by its class. All properties will be copied to the child analyzer. @param [Class] analyzer_class the class of the analyzer to instantiate and add @param [Hash] options options which will be passed on initialization @return [Analyzer]
[ "Instantiate", "and", "add", "an", "analyzer", "by", "its", "class", ".", "All", "properties", "will", "be", "copied", "to", "the", "child", "analyzer", "." ]
4747b072ab316e7c6f389db9a3cad584e814fe43
https://github.com/xcres/xcres/blob/4747b072ab316e7c6f389db9a3cad584e814fe43/lib/xcres/analyzer/aggregate_analyzer.rb#L38-L44
train
sush/lieu
lib/lieu/request.rb
Lieu.Request.post
def post(path, options={}) response = request(:post, path, options) response.delete(:status) if response.respond_to?(:status) response end
ruby
def post(path, options={}) response = request(:post, path, options) response.delete(:status) if response.respond_to?(:status) response end
[ "def", "post", "(", "path", ",", "options", "=", "{", "}", ")", "response", "=", "request", "(", ":post", ",", "path", ",", "options", ")", "response", ".", "delete", "(", ":status", ")", "if", "response", ".", "respond_to?", "(", ":status", ")", "response", "end" ]
Make a HTTP POST request. @param path [String] The path, relative to api_endpoint @param options [Hash] body params for request @return [Hashie::Mash]
[ "Make", "a", "HTTP", "POST", "request", "." ]
b6bb5e82931308c80ed52bd7969df48fbafe8668
https://github.com/sush/lieu/blob/b6bb5e82931308c80ed52bd7969df48fbafe8668/lib/lieu/request.rb#L18-L24
train
siong1987/mongoid_shortener
app/helpers/mongoid_shortener/shortened_urls_helper.rb
MongoidShortener.ShortenedUrlsHelper.shortened_url
def shortened_url(url) raise "Only String accepted: #{url}" unless url.class == String short_url = MongoidShortener::ShortenedUrl.generate(url) short_url end
ruby
def shortened_url(url) raise "Only String accepted: #{url}" unless url.class == String short_url = MongoidShortener::ShortenedUrl.generate(url) short_url end
[ "def", "shortened_url", "(", "url", ")", "raise", "\"Only String accepted: #{url}\"", "unless", "url", ".", "class", "==", "String", "short_url", "=", "MongoidShortener", "::", "ShortenedUrl", ".", "generate", "(", "url", ")", "short_url", "end" ]
generate a url from either a url string, or a shortened url object
[ "generate", "a", "url", "from", "either", "a", "url", "string", "or", "a", "shortened", "url", "object" ]
32888cef58d9980d01d04d2ef42ad49ae5d06d04
https://github.com/siong1987/mongoid_shortener/blob/32888cef58d9980d01d04d2ef42ad49ae5d06d04/app/helpers/mongoid_shortener/shortened_urls_helper.rb#L4-L8
train
jkraemer/acts_as_ferret
lib/acts_as_ferret/local_index.rb
ActsAsFerret.LocalIndex.ferret_index
def ferret_index ensure_index_exists (@ferret_index ||= Ferret::Index::Index.new(index_definition[:ferret])).tap do |idx| idx.batch_size = index_definition[:reindex_batch_size] idx.logger = logger end end
ruby
def ferret_index ensure_index_exists (@ferret_index ||= Ferret::Index::Index.new(index_definition[:ferret])).tap do |idx| idx.batch_size = index_definition[:reindex_batch_size] idx.logger = logger end end
[ "def", "ferret_index", "ensure_index_exists", "(", "@ferret_index", "||=", "Ferret", "::", "Index", "::", "Index", ".", "new", "(", "index_definition", "[", ":ferret", "]", ")", ")", ".", "tap", "do", "|", "idx", "|", "idx", ".", "batch_size", "=", "index_definition", "[", ":reindex_batch_size", "]", "idx", ".", "logger", "=", "logger", "end", "end" ]
The 'real' Ferret Index instance
[ "The", "real", "Ferret", "Index", "instance" ]
1c3330c51a4d07298e6b89347077742636d9e3cf
https://github.com/jkraemer/acts_as_ferret/blob/1c3330c51a4d07298e6b89347077742636d9e3cf/lib/acts_as_ferret/local_index.rb#L17-L23
train
jkraemer/acts_as_ferret
lib/acts_as_ferret/local_index.rb
ActsAsFerret.LocalIndex.rebuild_index
def rebuild_index models = index_definition[:registered_models] logger.debug "rebuild index with models: #{models.inspect}" close index = Ferret::Index::Index.new(index_definition[:ferret].dup.update(:auto_flush => false, :field_infos => ActsAsFerret::field_infos(index_definition), :create => true)) index.batch_size = index_definition[:reindex_batch_size] index.logger = logger index.index_models models reopen! end
ruby
def rebuild_index models = index_definition[:registered_models] logger.debug "rebuild index with models: #{models.inspect}" close index = Ferret::Index::Index.new(index_definition[:ferret].dup.update(:auto_flush => false, :field_infos => ActsAsFerret::field_infos(index_definition), :create => true)) index.batch_size = index_definition[:reindex_batch_size] index.logger = logger index.index_models models reopen! end
[ "def", "rebuild_index", "models", "=", "index_definition", "[", ":registered_models", "]", "logger", ".", "debug", "\"rebuild index with models: #{models.inspect}\"", "close", "index", "=", "Ferret", "::", "Index", "::", "Index", ".", "new", "(", "index_definition", "[", ":ferret", "]", ".", "dup", ".", "update", "(", ":auto_flush", "=>", "false", ",", ":field_infos", "=>", "ActsAsFerret", "::", "field_infos", "(", "index_definition", ")", ",", ":create", "=>", "true", ")", ")", "index", ".", "batch_size", "=", "index_definition", "[", ":reindex_batch_size", "]", "index", ".", "logger", "=", "logger", "index", ".", "index_models", "models", "reopen!", "end" ]
rebuilds the index from all records of the model classes associated with this index
[ "rebuilds", "the", "index", "from", "all", "records", "of", "the", "model", "classes", "associated", "with", "this", "index" ]
1c3330c51a4d07298e6b89347077742636d9e3cf
https://github.com/jkraemer/acts_as_ferret/blob/1c3330c51a4d07298e6b89347077742636d9e3cf/lib/acts_as_ferret/local_index.rb#L45-L56
train
jkraemer/acts_as_ferret
lib/acts_as_ferret/local_index.rb
ActsAsFerret.LocalIndex.process_query
def process_query(query, options = {}) return query unless String === query ferret_index.synchronize do if options[:analyzer] # use per-query analyzer if present qp = Ferret::QueryParser.new ferret_index.instance_variable_get('@options').merge(options) reader = ferret_index.reader qp.fields = reader.fields unless options[:all_fields] || options[:fields] qp.tokenized_fields = reader.tokenized_fields unless options[:tokenized_fields] return qp.parse query else return ferret_index.process_query(query) end end end
ruby
def process_query(query, options = {}) return query unless String === query ferret_index.synchronize do if options[:analyzer] # use per-query analyzer if present qp = Ferret::QueryParser.new ferret_index.instance_variable_get('@options').merge(options) reader = ferret_index.reader qp.fields = reader.fields unless options[:all_fields] || options[:fields] qp.tokenized_fields = reader.tokenized_fields unless options[:tokenized_fields] return qp.parse query else return ferret_index.process_query(query) end end end
[ "def", "process_query", "(", "query", ",", "options", "=", "{", "}", ")", "return", "query", "unless", "String", "===", "query", "ferret_index", ".", "synchronize", "do", "if", "options", "[", ":analyzer", "]", "qp", "=", "Ferret", "::", "QueryParser", ".", "new", "ferret_index", ".", "instance_variable_get", "(", "'@options'", ")", ".", "merge", "(", "options", ")", "reader", "=", "ferret_index", ".", "reader", "qp", ".", "fields", "=", "reader", ".", "fields", "unless", "options", "[", ":all_fields", "]", "||", "options", "[", ":fields", "]", "qp", ".", "tokenized_fields", "=", "reader", ".", "tokenized_fields", "unless", "options", "[", ":tokenized_fields", "]", "return", "qp", ".", "parse", "query", "else", "return", "ferret_index", ".", "process_query", "(", "query", ")", "end", "end", "end" ]
Parses the given query string into a Ferret Query object.
[ "Parses", "the", "given", "query", "string", "into", "a", "Ferret", "Query", "object", "." ]
1c3330c51a4d07298e6b89347077742636d9e3cf
https://github.com/jkraemer/acts_as_ferret/blob/1c3330c51a4d07298e6b89347077742636d9e3cf/lib/acts_as_ferret/local_index.rb#L63-L79
train
jkraemer/acts_as_ferret
lib/acts_as_ferret/local_index.rb
ActsAsFerret.LocalIndex.total_hits
def total_hits(query, options = {}) ferret_index.search(process_query(query, options), options).total_hits end
ruby
def total_hits(query, options = {}) ferret_index.search(process_query(query, options), options).total_hits end
[ "def", "total_hits", "(", "query", ",", "options", "=", "{", "}", ")", "ferret_index", ".", "search", "(", "process_query", "(", "query", ",", "options", ")", ",", "options", ")", ".", "total_hits", "end" ]
Total number of hits for the given query.
[ "Total", "number", "of", "hits", "for", "the", "given", "query", "." ]
1c3330c51a4d07298e6b89347077742636d9e3cf
https://github.com/jkraemer/acts_as_ferret/blob/1c3330c51a4d07298e6b89347077742636d9e3cf/lib/acts_as_ferret/local_index.rb#L82-L84
train
jkraemer/acts_as_ferret
lib/acts_as_ferret/local_index.rb
ActsAsFerret.LocalIndex.highlight
def highlight(key, query, options = {}) logger.debug("highlight: #{key} query: #{query}") options.reverse_merge! :num_excerpts => 2, :pre_tag => '<em>', :post_tag => '</em>' highlights = [] ferret_index.synchronize do doc_num = document_number(key) if options[:field] highlights << ferret_index.highlight(query, doc_num, options) else query = process_query(query) # process only once index_definition[:ferret_fields].each_pair do |field, config| next if config[:store] == :no || config[:highlight] == :no options[:field] = field highlights << ferret_index.highlight(query, doc_num, options) end end end return highlights.compact.flatten[0..options[:num_excerpts]-1] end
ruby
def highlight(key, query, options = {}) logger.debug("highlight: #{key} query: #{query}") options.reverse_merge! :num_excerpts => 2, :pre_tag => '<em>', :post_tag => '</em>' highlights = [] ferret_index.synchronize do doc_num = document_number(key) if options[:field] highlights << ferret_index.highlight(query, doc_num, options) else query = process_query(query) # process only once index_definition[:ferret_fields].each_pair do |field, config| next if config[:store] == :no || config[:highlight] == :no options[:field] = field highlights << ferret_index.highlight(query, doc_num, options) end end end return highlights.compact.flatten[0..options[:num_excerpts]-1] end
[ "def", "highlight", "(", "key", ",", "query", ",", "options", "=", "{", "}", ")", "logger", ".", "debug", "(", "\"highlight: #{key} query: #{query}\"", ")", "options", ".", "reverse_merge!", ":num_excerpts", "=>", "2", ",", ":pre_tag", "=>", "'<em>'", ",", ":post_tag", "=>", "'</em>'", "highlights", "=", "[", "]", "ferret_index", ".", "synchronize", "do", "doc_num", "=", "document_number", "(", "key", ")", "if", "options", "[", ":field", "]", "highlights", "<<", "ferret_index", ".", "highlight", "(", "query", ",", "doc_num", ",", "options", ")", "else", "query", "=", "process_query", "(", "query", ")", "index_definition", "[", ":ferret_fields", "]", ".", "each_pair", "do", "|", "field", ",", "config", "|", "next", "if", "config", "[", ":store", "]", "==", ":no", "||", "config", "[", ":highlight", "]", "==", ":no", "options", "[", ":field", "]", "=", "field", "highlights", "<<", "ferret_index", ".", "highlight", "(", "query", ",", "doc_num", ",", "options", ")", "end", "end", "end", "return", "highlights", ".", "compact", ".", "flatten", "[", "0", "..", "options", "[", ":num_excerpts", "]", "-", "1", "]", "end" ]
highlight search terms for the record with the given id.
[ "highlight", "search", "terms", "for", "the", "record", "with", "the", "given", "id", "." ]
1c3330c51a4d07298e6b89347077742636d9e3cf
https://github.com/jkraemer/acts_as_ferret/blob/1c3330c51a4d07298e6b89347077742636d9e3cf/lib/acts_as_ferret/local_index.rb#L115-L134
train
jkraemer/acts_as_ferret
lib/acts_as_ferret/local_index.rb
ActsAsFerret.LocalIndex.document_number
def document_number(key) docnum = ferret_index.doc_number(key) # hits = ferret_index.search query_for_record(key) # return hits.hits.first.doc if hits.total_hits == 1 raise "cannot determine document number for record #{key}" if docnum.nil? docnum end
ruby
def document_number(key) docnum = ferret_index.doc_number(key) # hits = ferret_index.search query_for_record(key) # return hits.hits.first.doc if hits.total_hits == 1 raise "cannot determine document number for record #{key}" if docnum.nil? docnum end
[ "def", "document_number", "(", "key", ")", "docnum", "=", "ferret_index", ".", "doc_number", "(", "key", ")", "raise", "\"cannot determine document number for record #{key}\"", "if", "docnum", ".", "nil?", "docnum", "end" ]
retrieves the ferret document number of the record with the given key.
[ "retrieves", "the", "ferret", "document", "number", "of", "the", "record", "with", "the", "given", "key", "." ]
1c3330c51a4d07298e6b89347077742636d9e3cf
https://github.com/jkraemer/acts_as_ferret/blob/1c3330c51a4d07298e6b89347077742636d9e3cf/lib/acts_as_ferret/local_index.rb#L137-L143
train
mwlang/social_media
lib/social_media/service/facebook.rb
SocialMedia::Service.Facebook.get_app_access_token
def get_app_access_token return connection_params[:app_access_token] if connection_params.has_key? :app_access_token @oauth = Koala::Facebook::OAuth.new(connection_params[:app_id], connection_params[:app_secret], callback_url) connection_params[:app_access_token] = @oauth.get_app_access_token end
ruby
def get_app_access_token return connection_params[:app_access_token] if connection_params.has_key? :app_access_token @oauth = Koala::Facebook::OAuth.new(connection_params[:app_id], connection_params[:app_secret], callback_url) connection_params[:app_access_token] = @oauth.get_app_access_token end
[ "def", "get_app_access_token", "return", "connection_params", "[", ":app_access_token", "]", "if", "connection_params", ".", "has_key?", ":app_access_token", "@oauth", "=", "Koala", "::", "Facebook", "::", "OAuth", ".", "new", "(", "connection_params", "[", ":app_id", "]", ",", "connection_params", "[", ":app_secret", "]", ",", "callback_url", ")", "connection_params", "[", ":app_access_token", "]", "=", "@oauth", ".", "get_app_access_token", "end" ]
A long-term app_access_token might be supplied on connection parameters If not, we fetch a short-term one here.
[ "A", "long", "-", "term", "app_access_token", "might", "be", "supplied", "on", "connection", "parameters", "If", "not", "we", "fetch", "a", "short", "-", "term", "one", "here", "." ]
44c431701fb6ff9c1618e3194a1a1d89c6494f92
https://github.com/mwlang/social_media/blob/44c431701fb6ff9c1618e3194a1a1d89c6494f92/lib/social_media/service/facebook.rb#L98-L103
train
EvidentSecurity/esp_sdk
lib/esp/resources/suppression.rb
ESP.Suppression.regions
def regions # When regions come back in an include, the method still gets called, to return the object from the attributes. return attributes['regions'] if attributes['regions'].present? return [] unless respond_to? :region_ids ESP::Region.where(id_in: region_ids) end
ruby
def regions # When regions come back in an include, the method still gets called, to return the object from the attributes. return attributes['regions'] if attributes['regions'].present? return [] unless respond_to? :region_ids ESP::Region.where(id_in: region_ids) end
[ "def", "regions", "return", "attributes", "[", "'regions'", "]", "if", "attributes", "[", "'regions'", "]", ".", "present?", "return", "[", "]", "unless", "respond_to?", ":region_ids", "ESP", "::", "Region", ".", "where", "(", "id_in", ":", "region_ids", ")", "end" ]
The regions affected by this suppression. @return [ActiveResource::PaginatedCollection<ESP::Region>]
[ "The", "regions", "affected", "by", "this", "suppression", "." ]
feb1740a8e8849bdeb967a22358f9bcfaa99d215
https://github.com/EvidentSecurity/esp_sdk/blob/feb1740a8e8849bdeb967a22358f9bcfaa99d215/lib/esp/resources/suppression.rb#L20-L25
train
EvidentSecurity/esp_sdk
lib/esp/resources/suppression.rb
ESP.Suppression.external_accounts
def external_accounts # When external_accounts come back in an include, the method still gets called, to return the object from the attributes. return attributes['external_accounts'] if attributes['external_accounts'].present? return [] unless respond_to? :external_account_ids ESP::ExternalAccount.where(id_in: external_account_ids) end
ruby
def external_accounts # When external_accounts come back in an include, the method still gets called, to return the object from the attributes. return attributes['external_accounts'] if attributes['external_accounts'].present? return [] unless respond_to? :external_account_ids ESP::ExternalAccount.where(id_in: external_account_ids) end
[ "def", "external_accounts", "return", "attributes", "[", "'external_accounts'", "]", "if", "attributes", "[", "'external_accounts'", "]", ".", "present?", "return", "[", "]", "unless", "respond_to?", ":external_account_ids", "ESP", "::", "ExternalAccount", ".", "where", "(", "id_in", ":", "external_account_ids", ")", "end" ]
The external accounts affected by this suppression. @return [ActiveResource::PaginatedCollection<ESP::ExternalAccount>]
[ "The", "external", "accounts", "affected", "by", "this", "suppression", "." ]
feb1740a8e8849bdeb967a22358f9bcfaa99d215
https://github.com/EvidentSecurity/esp_sdk/blob/feb1740a8e8849bdeb967a22358f9bcfaa99d215/lib/esp/resources/suppression.rb#L30-L35
train
EvidentSecurity/esp_sdk
lib/esp/resources/suppression.rb
ESP.Suppression.signatures
def signatures # When signatures come back in an include, the method still gets called, to return the object from the attributes. return attributes['signatures'] if attributes['signatures'].present? return [] unless respond_to? :signature_ids ESP::Signature.where(id_in: signature_ids) end
ruby
def signatures # When signatures come back in an include, the method still gets called, to return the object from the attributes. return attributes['signatures'] if attributes['signatures'].present? return [] unless respond_to? :signature_ids ESP::Signature.where(id_in: signature_ids) end
[ "def", "signatures", "return", "attributes", "[", "'signatures'", "]", "if", "attributes", "[", "'signatures'", "]", ".", "present?", "return", "[", "]", "unless", "respond_to?", ":signature_ids", "ESP", "::", "Signature", ".", "where", "(", "id_in", ":", "signature_ids", ")", "end" ]
The signatures being suppressed. @return [ActiveResource::PaginatedCollection<ESP::Signature>]
[ "The", "signatures", "being", "suppressed", "." ]
feb1740a8e8849bdeb967a22358f9bcfaa99d215
https://github.com/EvidentSecurity/esp_sdk/blob/feb1740a8e8849bdeb967a22358f9bcfaa99d215/lib/esp/resources/suppression.rb#L40-L45
train
EvidentSecurity/esp_sdk
lib/esp/resources/suppression.rb
ESP.Suppression.custom_signatures
def custom_signatures # When custom_signatures come back in an include, the method still gets called, to return the object from the attributes. return attributes['custom_signatures'] if attributes['custom_signatures'].present? return [] unless respond_to? :custom_signature_ids ESP::CustomSignature.where(id_in: custom_signature_ids) end
ruby
def custom_signatures # When custom_signatures come back in an include, the method still gets called, to return the object from the attributes. return attributes['custom_signatures'] if attributes['custom_signatures'].present? return [] unless respond_to? :custom_signature_ids ESP::CustomSignature.where(id_in: custom_signature_ids) end
[ "def", "custom_signatures", "return", "attributes", "[", "'custom_signatures'", "]", "if", "attributes", "[", "'custom_signatures'", "]", ".", "present?", "return", "[", "]", "unless", "respond_to?", ":custom_signature_ids", "ESP", "::", "CustomSignature", ".", "where", "(", "id_in", ":", "custom_signature_ids", ")", "end" ]
The custom signatures being suppressed. @return [ActiveResource::PaginatedCollection<ESP::CustomSignature>]
[ "The", "custom", "signatures", "being", "suppressed", "." ]
feb1740a8e8849bdeb967a22358f9bcfaa99d215
https://github.com/EvidentSecurity/esp_sdk/blob/feb1740a8e8849bdeb967a22358f9bcfaa99d215/lib/esp/resources/suppression.rb#L50-L55
train
EvidentSecurity/esp_sdk
lib/esp/resources/region.rb
ESP.Region.suppress
def suppress(arguments = {}) arguments = arguments.with_indifferent_access ESP::Suppression::Region.create(regions: [code], external_account_ids: Array(arguments[:external_account_ids]), reason: arguments[:reason]) end
ruby
def suppress(arguments = {}) arguments = arguments.with_indifferent_access ESP::Suppression::Region.create(regions: [code], external_account_ids: Array(arguments[:external_account_ids]), reason: arguments[:reason]) end
[ "def", "suppress", "(", "arguments", "=", "{", "}", ")", "arguments", "=", "arguments", ".", "with_indifferent_access", "ESP", "::", "Suppression", "::", "Region", ".", "create", "(", "regions", ":", "[", "code", "]", ",", "external_account_ids", ":", "Array", "(", "arguments", "[", ":external_account_ids", "]", ")", ",", "reason", ":", "arguments", "[", ":reason", "]", ")", "end" ]
Create a suppression for this region. @param arguments [Hash] Required hash of region suppression attributes. ===== Valid Arguments See {API documentation}[http://api-docs.evident.io?ruby#suppression-create] for valid arguments @return [ESP::Suppression::Region] @example suppress(external_account_ids: [5], reason: 'My very good reason for creating this suppression')
[ "Create", "a", "suppression", "for", "this", "region", "." ]
feb1740a8e8849bdeb967a22358f9bcfaa99d215
https://github.com/EvidentSecurity/esp_sdk/blob/feb1740a8e8849bdeb967a22358f9bcfaa99d215/lib/esp/resources/region.rb#L26-L29
train
Threespot/tolaria
lib/tolaria/help_links.rb
Tolaria.HelpLink.validate!
def validate! if title.blank? raise RuntimeError, "HelpLinks must provide a string title" end file_configured = (slug.present? && markdown_file.present?) link_configured = link_to.present? unless file_configured || link_configured raise RuntimeError, "Incomplete HelpLink config. You must provide link_to, or both slug and markdown_file." end if file_configured && link_configured raise RuntimeError, "Ambiguous HelpLink config. You must provide link_to, or both slug and markdown_file, but not all three." end end
ruby
def validate! if title.blank? raise RuntimeError, "HelpLinks must provide a string title" end file_configured = (slug.present? && markdown_file.present?) link_configured = link_to.present? unless file_configured || link_configured raise RuntimeError, "Incomplete HelpLink config. You must provide link_to, or both slug and markdown_file." end if file_configured && link_configured raise RuntimeError, "Ambiguous HelpLink config. You must provide link_to, or both slug and markdown_file, but not all three." end end
[ "def", "validate!", "if", "title", ".", "blank?", "raise", "RuntimeError", ",", "\"HelpLinks must provide a string title\"", "end", "file_configured", "=", "(", "slug", ".", "present?", "&&", "markdown_file", ".", "present?", ")", "link_configured", "=", "link_to", ".", "present?", "unless", "file_configured", "||", "link_configured", "raise", "RuntimeError", ",", "\"Incomplete HelpLink config. You must provide link_to, or both slug and markdown_file.\"", "end", "if", "file_configured", "&&", "link_configured", "raise", "RuntimeError", ",", "\"Ambiguous HelpLink config. You must provide link_to, or both slug and markdown_file, but not all three.\"", "end", "end" ]
Raises RuntimeError if this HelpLink is incorrectly configured.
[ "Raises", "RuntimeError", "if", "this", "HelpLink", "is", "incorrectly", "configured", "." ]
e60c5e330f7b423879433e35ec01ee2263e41c2c
https://github.com/Threespot/tolaria/blob/e60c5e330f7b423879433e35ec01ee2263e41c2c/lib/tolaria/help_links.rb#L62-L79
train
brettstimmerman/jabber-bot
lib/jabber/bot.rb
Jabber.Bot.presence
def presence(presence=nil, status=nil, priority=nil) @config[:presence] = presence @config[:status] = status @config[:priority] = priority status_message = Presence.new(presence, status, priority) @jabber.send!(status_message) if @jabber.connected? end
ruby
def presence(presence=nil, status=nil, priority=nil) @config[:presence] = presence @config[:status] = status @config[:priority] = priority status_message = Presence.new(presence, status, priority) @jabber.send!(status_message) if @jabber.connected? end
[ "def", "presence", "(", "presence", "=", "nil", ",", "status", "=", "nil", ",", "priority", "=", "nil", ")", "@config", "[", ":presence", "]", "=", "presence", "@config", "[", ":status", "]", "=", "status", "@config", "[", ":priority", "]", "=", "priority", "status_message", "=", "Presence", ".", "new", "(", "presence", ",", "status", ",", "priority", ")", "@jabber", ".", "send!", "(", "status_message", ")", "if", "@jabber", ".", "connected?", "end" ]
Sets the bot presence, status message and priority.
[ "Sets", "the", "bot", "presence", "status", "message", "and", "priority", "." ]
d3501dcca043b5ade71b99664d5664e2b03f1539
https://github.com/brettstimmerman/jabber-bot/blob/d3501dcca043b5ade71b99664d5664e2b03f1539/lib/jabber/bot.rb#L237-L244
train
brettstimmerman/jabber-bot
lib/jabber/bot.rb
Jabber.Bot.add_command_alias
def add_command_alias(command_name, alias_command, callback) #:nodoc: original_command = @commands[:meta][command_name] original_command[:syntax] << alias_command[:syntax] alias_name = command_name(alias_command[:syntax]) alias_command[:is_public] = original_command[:is_public] add_command_meta(alias_name, original_command, true) add_command_spec(alias_command, callback) end
ruby
def add_command_alias(command_name, alias_command, callback) #:nodoc: original_command = @commands[:meta][command_name] original_command[:syntax] << alias_command[:syntax] alias_name = command_name(alias_command[:syntax]) alias_command[:is_public] = original_command[:is_public] add_command_meta(alias_name, original_command, true) add_command_spec(alias_command, callback) end
[ "def", "add_command_alias", "(", "command_name", ",", "alias_command", ",", "callback", ")", "original_command", "=", "@commands", "[", ":meta", "]", "[", "command_name", "]", "original_command", "[", ":syntax", "]", "<<", "alias_command", "[", ":syntax", "]", "alias_name", "=", "command_name", "(", "alias_command", "[", ":syntax", "]", ")", "alias_command", "[", ":is_public", "]", "=", "original_command", "[", ":is_public", "]", "add_command_meta", "(", "alias_name", ",", "original_command", ",", "true", ")", "add_command_spec", "(", "alias_command", ",", "callback", ")", "end" ]
Add a command alias for the given original +command_name+
[ "Add", "a", "command", "alias", "for", "the", "given", "original", "+", "command_name", "+" ]
d3501dcca043b5ade71b99664d5664e2b03f1539
https://github.com/brettstimmerman/jabber-bot/blob/d3501dcca043b5ade71b99664d5664e2b03f1539/lib/jabber/bot.rb#L277-L287
train
brettstimmerman/jabber-bot
lib/jabber/bot.rb
Jabber.Bot.add_command_meta
def add_command_meta(name, command, is_alias=false) #:nodoc: syntax = command[:syntax] @commands[:meta][name] = { :syntax => syntax.is_a?(Array) ? syntax : [syntax], :description => command[:description], :is_public => command[:is_public] || false, :is_alias => is_alias } end
ruby
def add_command_meta(name, command, is_alias=false) #:nodoc: syntax = command[:syntax] @commands[:meta][name] = { :syntax => syntax.is_a?(Array) ? syntax : [syntax], :description => command[:description], :is_public => command[:is_public] || false, :is_alias => is_alias } end
[ "def", "add_command_meta", "(", "name", ",", "command", ",", "is_alias", "=", "false", ")", "syntax", "=", "command", "[", ":syntax", "]", "@commands", "[", ":meta", "]", "[", "name", "]", "=", "{", ":syntax", "=>", "syntax", ".", "is_a?", "(", "Array", ")", "?", "syntax", ":", "[", "syntax", "]", ",", ":description", "=>", "command", "[", ":description", "]", ",", ":is_public", "=>", "command", "[", ":is_public", "]", "||", "false", ",", ":is_alias", "=>", "is_alias", "}", "end" ]
Add a command meta
[ "Add", "a", "command", "meta" ]
d3501dcca043b5ade71b99664d5664e2b03f1539
https://github.com/brettstimmerman/jabber-bot/blob/d3501dcca043b5ade71b99664d5664e2b03f1539/lib/jabber/bot.rb#L290-L299
train
brettstimmerman/jabber-bot
lib/jabber/bot.rb
Jabber.Bot.help_message
def help_message(sender, command_name) #:nodoc: if command_name.nil? || command_name.length == 0 # Display help for all commands help_message = "I understand the following commands:\n\n" @commands[:meta].sort.each do |command| # Thank you, Hash.sort command = command[1] if !command[:is_alias] && (command[:is_public] || master?(sender)) command[:syntax].each { |syntax| help_message += "#{syntax}\n" } help_message += " #{command[:description]}\n\n" end end else # Display help for the given command command = @commands[:meta][command_name] if command.nil? help_message = "I don't understand '#{command_name}' Try saying" + " 'help' to see what commands I understand." else help_message = '' command[:syntax].each { |syntax| help_message += "#{syntax}\n" } help_message += " #{command[:description]} " end end help_message end
ruby
def help_message(sender, command_name) #:nodoc: if command_name.nil? || command_name.length == 0 # Display help for all commands help_message = "I understand the following commands:\n\n" @commands[:meta].sort.each do |command| # Thank you, Hash.sort command = command[1] if !command[:is_alias] && (command[:is_public] || master?(sender)) command[:syntax].each { |syntax| help_message += "#{syntax}\n" } help_message += " #{command[:description]}\n\n" end end else # Display help for the given command command = @commands[:meta][command_name] if command.nil? help_message = "I don't understand '#{command_name}' Try saying" + " 'help' to see what commands I understand." else help_message = '' command[:syntax].each { |syntax| help_message += "#{syntax}\n" } help_message += " #{command[:description]} " end end help_message end
[ "def", "help_message", "(", "sender", ",", "command_name", ")", "if", "command_name", ".", "nil?", "||", "command_name", ".", "length", "==", "0", "help_message", "=", "\"I understand the following commands:\\n\\n\"", "@commands", "[", ":meta", "]", ".", "sort", ".", "each", "do", "|", "command", "|", "command", "=", "command", "[", "1", "]", "if", "!", "command", "[", ":is_alias", "]", "&&", "(", "command", "[", ":is_public", "]", "||", "master?", "(", "sender", ")", ")", "command", "[", ":syntax", "]", ".", "each", "{", "|", "syntax", "|", "help_message", "+=", "\"#{syntax}\\n\"", "}", "help_message", "+=", "\" #{command[:description]}\\n\\n\"", "end", "end", "else", "command", "=", "@commands", "[", ":meta", "]", "[", "command_name", "]", "if", "command", ".", "nil?", "help_message", "=", "\"I don't understand '#{command_name}' Try saying\"", "+", "\" 'help' to see what commands I understand.\"", "else", "help_message", "=", "''", "command", "[", ":syntax", "]", ".", "each", "{", "|", "syntax", "|", "help_message", "+=", "\"#{syntax}\\n\"", "}", "help_message", "+=", "\" #{command[:description]} \"", "end", "end", "help_message", "end" ]
Returns the default help message describing the bot's command repertoire. Commands are sorted alphabetically by name, and are displayed according to the bot's and the commands's _public_ attribute.
[ "Returns", "the", "default", "help", "message", "describing", "the", "bot", "s", "command", "repertoire", ".", "Commands", "are", "sorted", "alphabetically", "by", "name", "and", "are", "displayed", "according", "to", "the", "bot", "s", "and", "the", "commands", "s", "_public_", "attribute", "." ]
d3501dcca043b5ade71b99664d5664e2b03f1539
https://github.com/brettstimmerman/jabber-bot/blob/d3501dcca043b5ade71b99664d5664e2b03f1539/lib/jabber/bot.rb#L322-L351
train
brettstimmerman/jabber-bot
lib/jabber/bot.rb
Jabber.Bot.start_listener_thread
def start_listener_thread #:nodoc: listener_thread = Thread.new do loop do if @jabber.received_messages? @jabber.received_messages do |message| # Remove the Jabber resourse, if any sender = message.from.to_s.sub(/\/.+$/, '') if message.type == :chat parse_thread = Thread.new do parse_command(sender, message.body) end parse_thread.join end end end sleep 1 end end listener_thread.join end
ruby
def start_listener_thread #:nodoc: listener_thread = Thread.new do loop do if @jabber.received_messages? @jabber.received_messages do |message| # Remove the Jabber resourse, if any sender = message.from.to_s.sub(/\/.+$/, '') if message.type == :chat parse_thread = Thread.new do parse_command(sender, message.body) end parse_thread.join end end end sleep 1 end end listener_thread.join end
[ "def", "start_listener_thread", "listener_thread", "=", "Thread", ".", "new", "do", "loop", "do", "if", "@jabber", ".", "received_messages?", "@jabber", ".", "received_messages", "do", "|", "message", "|", "sender", "=", "message", ".", "from", ".", "to_s", ".", "sub", "(", "/", "\\/", "/", ",", "''", ")", "if", "message", ".", "type", "==", ":chat", "parse_thread", "=", "Thread", ".", "new", "do", "parse_command", "(", "sender", ",", "message", ".", "body", ")", "end", "parse_thread", ".", "join", "end", "end", "end", "sleep", "1", "end", "end", "listener_thread", ".", "join", "end" ]
Creates a new Thread dedicated to listening for incoming chat messages. When a chat message is received, the bot checks if the sender is its master. If so, it is tested for the presence commands, and processed accordingly. If the bot itself or the command issued is not made public, a message sent by anyone other than the bot's master is silently ignored. Only the chat message type is supported. Other message types such as error and groupchat are not supported.
[ "Creates", "a", "new", "Thread", "dedicated", "to", "listening", "for", "incoming", "chat", "messages", ".", "When", "a", "chat", "message", "is", "received", "the", "bot", "checks", "if", "the", "sender", "is", "its", "master", ".", "If", "so", "it", "is", "tested", "for", "the", "presence", "commands", "and", "processed", "accordingly", ".", "If", "the", "bot", "itself", "or", "the", "command", "issued", "is", "not", "made", "public", "a", "message", "sent", "by", "anyone", "other", "than", "the", "bot", "s", "master", "is", "silently", "ignored", "." ]
d3501dcca043b5ade71b99664d5664e2b03f1539
https://github.com/brettstimmerman/jabber-bot/blob/d3501dcca043b5ade71b99664d5664e2b03f1539/lib/jabber/bot.rb#L405-L428
train
m247/epp-client
lib/epp-client/server.rb
EPP.Server.prepare_request
def prepare_request(command, extension = nil) cmd = EPP::Requests::Command.new(req_tid, command, extension) EPP::Request.new(cmd) end
ruby
def prepare_request(command, extension = nil) cmd = EPP::Requests::Command.new(req_tid, command, extension) EPP::Request.new(cmd) end
[ "def", "prepare_request", "(", "command", ",", "extension", "=", "nil", ")", "cmd", "=", "EPP", "::", "Requests", "::", "Command", ".", "new", "(", "req_tid", ",", "command", ",", "extension", ")", "EPP", "::", "Request", ".", "new", "(", "cmd", ")", "end" ]
Send request to server @overload request(command, payload) @param [String, #to_s] command EPP Command to call @param [XML::Node, XML::Document, String] payload EPP XML Payload @overload request(command) @param [String, #to_s] command EPP Command to call @yield [xml] block to construct payload @yieldparam [XML::Node] xml XML Node of the command for the payload to be added into @return [Response] EPP Response object def request(command, payload = nil, extension = nil, &block) @req = if payload.nil? && block_given? Request.new(command, req_tid, &block) else Request.new(command, payload, extension, req_tid) end @resp = send_recv_frame(@req) end @note Primarily an internal method, exposed to enable testing @param [] command @param [] extension @return [EPP::Request] @see request
[ "Send", "request", "to", "server" ]
72227e57d248f215d842e3dd37e72432d2a79270
https://github.com/m247/epp-client/blob/72227e57d248f215d842e3dd37e72432d2a79270/lib/epp-client/server.rb#L106-L109
train
m247/epp-client
lib/epp-client/server.rb
EPP.Server.connection
def connection @connection_errors = [] addrinfo.each do |_,port,_,addr,_,_,_| retried = false begin @conn = TCPSocket.new(addr, port) rescue Errno::EINVAL => e if retried message = e.message.split(" - ")[1] @connection_errors << Errno::EINVAL.new( "#{message}: TCPSocket.new(#{addr.inspect}, #{port.inspect})") next end retried = true retry end args = [@conn] args << options[:ssl_context] if options[:ssl_context] @sock = OpenSSL::SSL::SSLSocket.new(*args) @sock.sync_close = true begin @sock.connect @greeting = recv_frame # Perform initial recv return yield rescue Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::EHOSTUNREACH => e @connection_errors << e next # try the next address in the list rescue OpenSSL::SSL::SSLError => e # Connection error, most likely the IP isn't in the allow list if e.message =~ /returned=5 errno=0/ @connection_errors << ConnectionError.new("SSL Connection error, IP may not be permitted to connect to #{@host}", @conn.addr, @conn.peeraddr, e) next else raise e end ensure @sock.close # closes @conn @conn = @sock = nil end end # Should only get here if we didn't return from the block above addrinfo(true) # Update our addrinfo in case the DNS has changed raise @connection_errors.last unless @connection_errors.empty? raise Errno::EHOSTUNREACH, "Failed to connect to host #{@host}" end
ruby
def connection @connection_errors = [] addrinfo.each do |_,port,_,addr,_,_,_| retried = false begin @conn = TCPSocket.new(addr, port) rescue Errno::EINVAL => e if retried message = e.message.split(" - ")[1] @connection_errors << Errno::EINVAL.new( "#{message}: TCPSocket.new(#{addr.inspect}, #{port.inspect})") next end retried = true retry end args = [@conn] args << options[:ssl_context] if options[:ssl_context] @sock = OpenSSL::SSL::SSLSocket.new(*args) @sock.sync_close = true begin @sock.connect @greeting = recv_frame # Perform initial recv return yield rescue Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::EHOSTUNREACH => e @connection_errors << e next # try the next address in the list rescue OpenSSL::SSL::SSLError => e # Connection error, most likely the IP isn't in the allow list if e.message =~ /returned=5 errno=0/ @connection_errors << ConnectionError.new("SSL Connection error, IP may not be permitted to connect to #{@host}", @conn.addr, @conn.peeraddr, e) next else raise e end ensure @sock.close # closes @conn @conn = @sock = nil end end # Should only get here if we didn't return from the block above addrinfo(true) # Update our addrinfo in case the DNS has changed raise @connection_errors.last unless @connection_errors.empty? raise Errno::EHOSTUNREACH, "Failed to connect to host #{@host}" end
[ "def", "connection", "@connection_errors", "=", "[", "]", "addrinfo", ".", "each", "do", "|", "_", ",", "port", ",", "_", ",", "addr", ",", "_", ",", "_", ",", "_", "|", "retried", "=", "false", "begin", "@conn", "=", "TCPSocket", ".", "new", "(", "addr", ",", "port", ")", "rescue", "Errno", "::", "EINVAL", "=>", "e", "if", "retried", "message", "=", "e", ".", "message", ".", "split", "(", "\" - \"", ")", "[", "1", "]", "@connection_errors", "<<", "Errno", "::", "EINVAL", ".", "new", "(", "\"#{message}: TCPSocket.new(#{addr.inspect}, #{port.inspect})\"", ")", "next", "end", "retried", "=", "true", "retry", "end", "args", "=", "[", "@conn", "]", "args", "<<", "options", "[", ":ssl_context", "]", "if", "options", "[", ":ssl_context", "]", "@sock", "=", "OpenSSL", "::", "SSL", "::", "SSLSocket", ".", "new", "(", "*", "args", ")", "@sock", ".", "sync_close", "=", "true", "begin", "@sock", ".", "connect", "@greeting", "=", "recv_frame", "return", "yield", "rescue", "Errno", "::", "ECONNREFUSED", ",", "Errno", "::", "ECONNRESET", ",", "Errno", "::", "EHOSTUNREACH", "=>", "e", "@connection_errors", "<<", "e", "next", "rescue", "OpenSSL", "::", "SSL", "::", "SSLError", "=>", "e", "if", "e", ".", "message", "=~", "/", "/", "@connection_errors", "<<", "ConnectionError", ".", "new", "(", "\"SSL Connection error, IP may not be permitted to connect to #{@host}\"", ",", "@conn", ".", "addr", ",", "@conn", ".", "peeraddr", ",", "e", ")", "next", "else", "raise", "e", "end", "ensure", "@sock", ".", "close", "@conn", "=", "@sock", "=", "nil", "end", "end", "addrinfo", "(", "true", ")", "raise", "@connection_errors", ".", "last", "unless", "@connection_errors", ".", "empty?", "raise", "Errno", "::", "EHOSTUNREACH", ",", "\"Failed to connect to host #{@host}\"", "end" ]
EPP Server Connection @yield connected session @example typical usage connection do # .. do stuff with logged in session .. end @example usage with with_login connection do with_login do # .. do stuff with logged in session .. end end
[ "EPP", "Server", "Connection" ]
72227e57d248f215d842e3dd37e72432d2a79270
https://github.com/m247/epp-client/blob/72227e57d248f215d842e3dd37e72432d2a79270/lib/epp-client/server.rb#L181-L232
train
m247/epp-client
lib/epp-client/server.rb
EPP.Server.send_frame
def send_frame(xml) xml = xml.to_s if xml.kind_of?(Request) @sock.write([xml.size + HEADER_LEN].pack("N") + xml) end
ruby
def send_frame(xml) xml = xml.to_s if xml.kind_of?(Request) @sock.write([xml.size + HEADER_LEN].pack("N") + xml) end
[ "def", "send_frame", "(", "xml", ")", "xml", "=", "xml", ".", "to_s", "if", "xml", ".", "kind_of?", "(", "Request", ")", "@sock", ".", "write", "(", "[", "xml", ".", "size", "+", "HEADER_LEN", "]", ".", "pack", "(", "\"N\"", ")", "+", "xml", ")", "end" ]
Send XML frame @param [String,Request] xml Payload to send @return [Integer] number of bytes written
[ "Send", "XML", "frame" ]
72227e57d248f215d842e3dd37e72432d2a79270
https://github.com/m247/epp-client/blob/72227e57d248f215d842e3dd37e72432d2a79270/lib/epp-client/server.rb#L308-L311
train
m247/epp-client
lib/epp-client/server.rb
EPP.Server.recv_frame
def recv_frame header = @sock.read(HEADER_LEN) if header.nil? && @sock.eof? raise ServerError, "Connection terminated by remote host" elsif header.nil? raise ServerError, "Failed to read header from remote host" else len = header.unpack('N')[0] raise ServerError, "Bad frame header from server, should be greater than #{HEADER_LEN}" unless len > HEADER_LEN @sock.read(len - HEADER_LEN) end end
ruby
def recv_frame header = @sock.read(HEADER_LEN) if header.nil? && @sock.eof? raise ServerError, "Connection terminated by remote host" elsif header.nil? raise ServerError, "Failed to read header from remote host" else len = header.unpack('N')[0] raise ServerError, "Bad frame header from server, should be greater than #{HEADER_LEN}" unless len > HEADER_LEN @sock.read(len - HEADER_LEN) end end
[ "def", "recv_frame", "header", "=", "@sock", ".", "read", "(", "HEADER_LEN", ")", "if", "header", ".", "nil?", "&&", "@sock", ".", "eof?", "raise", "ServerError", ",", "\"Connection terminated by remote host\"", "elsif", "header", ".", "nil?", "raise", "ServerError", ",", "\"Failed to read header from remote host\"", "else", "len", "=", "header", ".", "unpack", "(", "'N'", ")", "[", "0", "]", "raise", "ServerError", ",", "\"Bad frame header from server, should be greater than #{HEADER_LEN}\"", "unless", "len", ">", "HEADER_LEN", "@sock", ".", "read", "(", "len", "-", "HEADER_LEN", ")", "end", "end" ]
Receive XML frame @return [String] XML response
[ "Receive", "XML", "frame" ]
72227e57d248f215d842e3dd37e72432d2a79270
https://github.com/m247/epp-client/blob/72227e57d248f215d842e3dd37e72432d2a79270/lib/epp-client/server.rb#L315-L328
train
Threespot/tolaria
lib/tolaria/markdown.rb
Tolaria.MarkdownRendererProxy.render
def render(document) if Tolaria.config.markdown_renderer.nil? return simple_format(document) else @markdown_renderer ||= Tolaria.config.markdown_renderer.constantize return @markdown_renderer.render(document) end end
ruby
def render(document) if Tolaria.config.markdown_renderer.nil? return simple_format(document) else @markdown_renderer ||= Tolaria.config.markdown_renderer.constantize return @markdown_renderer.render(document) end end
[ "def", "render", "(", "document", ")", "if", "Tolaria", ".", "config", ".", "markdown_renderer", ".", "nil?", "return", "simple_format", "(", "document", ")", "else", "@markdown_renderer", "||=", "Tolaria", ".", "config", ".", "markdown_renderer", ".", "constantize", "return", "@markdown_renderer", ".", "render", "(", "document", ")", "end", "end" ]
Calls the configured Markdown renderer, if none exists then uses `simple_format` to return more than nothing.
[ "Calls", "the", "configured", "Markdown", "renderer", "if", "none", "exists", "then", "uses", "simple_format", "to", "return", "more", "than", "nothing", "." ]
e60c5e330f7b423879433e35ec01ee2263e41c2c
https://github.com/Threespot/tolaria/blob/e60c5e330f7b423879433e35ec01ee2263e41c2c/lib/tolaria/markdown.rb#L11-L18
train
benbalter/problem_child
lib/problem_child/helpers.rb
ProblemChild.Helpers.base_sha
def base_sha default_branch = client.repo(repo)[:default_branch] branches.find { |branch| branch[:name] == default_branch }[:commit][:sha] end
ruby
def base_sha default_branch = client.repo(repo)[:default_branch] branches.find { |branch| branch[:name] == default_branch }[:commit][:sha] end
[ "def", "base_sha", "default_branch", "=", "client", ".", "repo", "(", "repo", ")", "[", ":default_branch", "]", "branches", ".", "find", "{", "|", "branch", "|", "branch", "[", ":name", "]", "==", "default_branch", "}", "[", ":commit", "]", "[", ":sha", "]", "end" ]
Head SHA of default branch, used for creating new branches
[ "Head", "SHA", "of", "default", "branch", "used", "for", "creating", "new", "branches" ]
cd06f0f174c37a5a5ee3cc655a0f0e824b362ce6
https://github.com/benbalter/problem_child/blob/cd06f0f174c37a5a5ee3cc655a0f0e824b362ce6/lib/problem_child/helpers.rb#L61-L64
train
benbalter/problem_child
lib/problem_child/helpers.rb
ProblemChild.Helpers.patch_branch
def patch_branch num = 1 branch_name = form_data['title'].parameterize return branch_name unless branch_exists?(branch_name) branch = "#{branch_name}-#{num}" while branch_exists?(branch) num += 1 branch = "#{branch_name}-#{num}" end branch end
ruby
def patch_branch num = 1 branch_name = form_data['title'].parameterize return branch_name unless branch_exists?(branch_name) branch = "#{branch_name}-#{num}" while branch_exists?(branch) num += 1 branch = "#{branch_name}-#{num}" end branch end
[ "def", "patch_branch", "num", "=", "1", "branch_name", "=", "form_data", "[", "'title'", "]", ".", "parameterize", "return", "branch_name", "unless", "branch_exists?", "(", "branch_name", ")", "branch", "=", "\"#{branch_name}-#{num}\"", "while", "branch_exists?", "(", "branch", ")", "num", "+=", "1", "branch", "=", "\"#{branch_name}-#{num}\"", "end", "branch", "end" ]
Name of branch to submit pull request from Starts with patch-1 and keeps going until it finds one not taken
[ "Name", "of", "branch", "to", "submit", "pull", "request", "from", "Starts", "with", "patch", "-", "1", "and", "keeps", "going", "until", "it", "finds", "one", "not", "taken" ]
cd06f0f174c37a5a5ee3cc655a0f0e824b362ce6
https://github.com/benbalter/problem_child/blob/cd06f0f174c37a5a5ee3cc655a0f0e824b362ce6/lib/problem_child/helpers.rb#L72-L82
train
benbalter/problem_child
lib/problem_child/helpers.rb
ProblemChild.Helpers.create_pull_request
def create_pull_request unless uploads.empty? branch = patch_branch create_branch(branch) uploads.each do |key, upload| client.create_contents( repo, upload[:filename], "Create #{upload[:filename]}", branch: branch, file: upload[:tempfile] ) session["file_#{key}"] = nil end end pr = client.create_pull_request(repo, 'master', branch, form_data['title'], issue_body, labels: labels) pr['number'] if pr end
ruby
def create_pull_request unless uploads.empty? branch = patch_branch create_branch(branch) uploads.each do |key, upload| client.create_contents( repo, upload[:filename], "Create #{upload[:filename]}", branch: branch, file: upload[:tempfile] ) session["file_#{key}"] = nil end end pr = client.create_pull_request(repo, 'master', branch, form_data['title'], issue_body, labels: labels) pr['number'] if pr end
[ "def", "create_pull_request", "unless", "uploads", ".", "empty?", "branch", "=", "patch_branch", "create_branch", "(", "branch", ")", "uploads", ".", "each", "do", "|", "key", ",", "upload", "|", "client", ".", "create_contents", "(", "repo", ",", "upload", "[", ":filename", "]", ",", "\"Create #{upload[:filename]}\"", ",", "branch", ":", "branch", ",", "file", ":", "upload", "[", ":tempfile", "]", ")", "session", "[", "\"file_#{key}\"", "]", "=", "nil", "end", "end", "pr", "=", "client", ".", "create_pull_request", "(", "repo", ",", "'master'", ",", "branch", ",", "form_data", "[", "'title'", "]", ",", "issue_body", ",", "labels", ":", "labels", ")", "pr", "[", "'number'", "]", "if", "pr", "end" ]
Create a pull request with the form contents
[ "Create", "a", "pull", "request", "with", "the", "form", "contents" ]
cd06f0f174c37a5a5ee3cc655a0f0e824b362ce6
https://github.com/benbalter/problem_child/blob/cd06f0f174c37a5a5ee3cc655a0f0e824b362ce6/lib/problem_child/helpers.rb#L90-L107
train
DannyBen/runfile
lib/runfile/exec.rb
Runfile.ExecHandler.run
def run(cmd) cmd = @before_run_block.call(cmd) if @before_run_block return false unless cmd say "!txtgrn!> #{cmd}" unless Runfile.quiet system cmd @after_run_block.call(cmd) if @after_run_block end
ruby
def run(cmd) cmd = @before_run_block.call(cmd) if @before_run_block return false unless cmd say "!txtgrn!> #{cmd}" unless Runfile.quiet system cmd @after_run_block.call(cmd) if @after_run_block end
[ "def", "run", "(", "cmd", ")", "cmd", "=", "@before_run_block", ".", "call", "(", "cmd", ")", "if", "@before_run_block", "return", "false", "unless", "cmd", "say", "\"!txtgrn!> #{cmd}\"", "unless", "Runfile", ".", "quiet", "system", "cmd", "@after_run_block", ".", "call", "(", "cmd", ")", "if", "@after_run_block", "end" ]
Run a command, wait until it is done and continue
[ "Run", "a", "command", "wait", "until", "it", "is", "done", "and", "continue" ]
2e9da12766c88f27981f0b7b044a26ee724cfda5
https://github.com/DannyBen/runfile/blob/2e9da12766c88f27981f0b7b044a26ee724cfda5/lib/runfile/exec.rb#L13-L19
train
DannyBen/runfile
lib/runfile/exec.rb
Runfile.ExecHandler.run!
def run!(cmd) cmd = @before_run_block.call(cmd) if @before_run_block return false unless cmd say "!txtgrn!> #{cmd}" unless Runfile.quiet exec cmd end
ruby
def run!(cmd) cmd = @before_run_block.call(cmd) if @before_run_block return false unless cmd say "!txtgrn!> #{cmd}" unless Runfile.quiet exec cmd end
[ "def", "run!", "(", "cmd", ")", "cmd", "=", "@before_run_block", ".", "call", "(", "cmd", ")", "if", "@before_run_block", "return", "false", "unless", "cmd", "say", "\"!txtgrn!> #{cmd}\"", "unless", "Runfile", ".", "quiet", "exec", "cmd", "end" ]
Run a command, wait until it is done, then exit
[ "Run", "a", "command", "wait", "until", "it", "is", "done", "then", "exit" ]
2e9da12766c88f27981f0b7b044a26ee724cfda5
https://github.com/DannyBen/runfile/blob/2e9da12766c88f27981f0b7b044a26ee724cfda5/lib/runfile/exec.rb#L22-L27
train
DannyBen/runfile
lib/runfile/exec.rb
Runfile.ExecHandler.run_bg
def run_bg(cmd, pid: nil, log: '/dev/null') cmd = @before_run_block.call(cmd) if @before_run_block return false unless cmd full_cmd = "exec #{cmd} >#{log} 2>&1" say "!txtgrn!> #{full_cmd}" unless Runfile.quiet process = IO.popen "exec #{cmd} >#{log} 2>&1" File.write pidfile(pid), process.pid if pid @after_run_block.call(cmd) if @after_run_block return process.pid end
ruby
def run_bg(cmd, pid: nil, log: '/dev/null') cmd = @before_run_block.call(cmd) if @before_run_block return false unless cmd full_cmd = "exec #{cmd} >#{log} 2>&1" say "!txtgrn!> #{full_cmd}" unless Runfile.quiet process = IO.popen "exec #{cmd} >#{log} 2>&1" File.write pidfile(pid), process.pid if pid @after_run_block.call(cmd) if @after_run_block return process.pid end
[ "def", "run_bg", "(", "cmd", ",", "pid", ":", "nil", ",", "log", ":", "'/dev/null'", ")", "cmd", "=", "@before_run_block", ".", "call", "(", "cmd", ")", "if", "@before_run_block", "return", "false", "unless", "cmd", "full_cmd", "=", "\"exec #{cmd} >#{log} 2>&1\"", "say", "\"!txtgrn!> #{full_cmd}\"", "unless", "Runfile", ".", "quiet", "process", "=", "IO", ".", "popen", "\"exec #{cmd} >#{log} 2>&1\"", "File", ".", "write", "pidfile", "(", "pid", ")", ",", "process", ".", "pid", "if", "pid", "@after_run_block", ".", "call", "(", "cmd", ")", "if", "@after_run_block", "return", "process", ".", "pid", "end" ]
Run a command in the background, optionally log to a log file and save the process ID in a pid file
[ "Run", "a", "command", "in", "the", "background", "optionally", "log", "to", "a", "log", "file", "and", "save", "the", "process", "ID", "in", "a", "pid", "file" ]
2e9da12766c88f27981f0b7b044a26ee724cfda5
https://github.com/DannyBen/runfile/blob/2e9da12766c88f27981f0b7b044a26ee724cfda5/lib/runfile/exec.rb#L31-L40
train
DannyBen/runfile
lib/runfile/exec.rb
Runfile.ExecHandler.stop_bg
def stop_bg(pid) file = pidfile(pid) if File.exist? file pid = File.read file File.delete file run "kill -s TERM #{pid}" else say "!txtred!PID file not found." unless Runfile.quiet end end
ruby
def stop_bg(pid) file = pidfile(pid) if File.exist? file pid = File.read file File.delete file run "kill -s TERM #{pid}" else say "!txtred!PID file not found." unless Runfile.quiet end end
[ "def", "stop_bg", "(", "pid", ")", "file", "=", "pidfile", "(", "pid", ")", "if", "File", ".", "exist?", "file", "pid", "=", "File", ".", "read", "file", "File", ".", "delete", "file", "run", "\"kill -s TERM #{pid}\"", "else", "say", "\"!txtred!PID file not found.\"", "unless", "Runfile", ".", "quiet", "end", "end" ]
Stop a command started with 'run_bg'. Provide the name of he pid file you used in 'run_bg'
[ "Stop", "a", "command", "started", "with", "run_bg", ".", "Provide", "the", "name", "of", "he", "pid", "file", "you", "used", "in", "run_bg" ]
2e9da12766c88f27981f0b7b044a26ee724cfda5
https://github.com/DannyBen/runfile/blob/2e9da12766c88f27981f0b7b044a26ee724cfda5/lib/runfile/exec.rb#L44-L53
train
EvidentSecurity/esp_sdk
lib/esp/commands/console.rb
ESP.Console.start
def start # rubocop:disable Metrics/MethodLength ARGV.clear IRB.setup nil IRB.conf[:PROMPT] = {} IRB.conf[:IRB_NAME] = 'espsdk' IRB.conf[:PROMPT][:ESPSDK] = { PROMPT_I: '%N:%03n:%i> ', PROMPT_N: '%N:%03n:%i> ', PROMPT_S: '%N:%03n:%i%l ', PROMPT_C: '%N:%03n:%i* ', RETURN: "# => %s\n" } IRB.conf[:PROMPT_MODE] = :ESPSDK IRB.conf[:RC] = false require 'irb/completion' require 'irb/ext/save-history' IRB.conf[:READLINE] = true IRB.conf[:SAVE_HISTORY] = 1000 IRB.conf[:HISTORY_FILE] = '~/.esp_sdk_history' context = Class.new do include ESP end irb = IRB::Irb.new(IRB::WorkSpace.new(context.new)) IRB.conf[:MAIN_CONTEXT] = irb.context trap("SIGINT") do irb.signal_handle end begin catch(:IRB_EXIT) do irb.eval_input end ensure IRB.irb_at_exit end end
ruby
def start # rubocop:disable Metrics/MethodLength ARGV.clear IRB.setup nil IRB.conf[:PROMPT] = {} IRB.conf[:IRB_NAME] = 'espsdk' IRB.conf[:PROMPT][:ESPSDK] = { PROMPT_I: '%N:%03n:%i> ', PROMPT_N: '%N:%03n:%i> ', PROMPT_S: '%N:%03n:%i%l ', PROMPT_C: '%N:%03n:%i* ', RETURN: "# => %s\n" } IRB.conf[:PROMPT_MODE] = :ESPSDK IRB.conf[:RC] = false require 'irb/completion' require 'irb/ext/save-history' IRB.conf[:READLINE] = true IRB.conf[:SAVE_HISTORY] = 1000 IRB.conf[:HISTORY_FILE] = '~/.esp_sdk_history' context = Class.new do include ESP end irb = IRB::Irb.new(IRB::WorkSpace.new(context.new)) IRB.conf[:MAIN_CONTEXT] = irb.context trap("SIGINT") do irb.signal_handle end begin catch(:IRB_EXIT) do irb.eval_input end ensure IRB.irb_at_exit end end
[ "def", "start", "ARGV", ".", "clear", "IRB", ".", "setup", "nil", "IRB", ".", "conf", "[", ":PROMPT", "]", "=", "{", "}", "IRB", ".", "conf", "[", ":IRB_NAME", "]", "=", "'espsdk'", "IRB", ".", "conf", "[", ":PROMPT", "]", "[", ":ESPSDK", "]", "=", "{", "PROMPT_I", ":", "'%N:%03n:%i> '", ",", "PROMPT_N", ":", "'%N:%03n:%i> '", ",", "PROMPT_S", ":", "'%N:%03n:%i%l '", ",", "PROMPT_C", ":", "'%N:%03n:%i* '", ",", "RETURN", ":", "\"# => %s\\n\"", "}", "IRB", ".", "conf", "[", ":PROMPT_MODE", "]", "=", ":ESPSDK", "IRB", ".", "conf", "[", ":RC", "]", "=", "false", "require", "'irb/completion'", "require", "'irb/ext/save-history'", "IRB", ".", "conf", "[", ":READLINE", "]", "=", "true", "IRB", ".", "conf", "[", ":SAVE_HISTORY", "]", "=", "1000", "IRB", ".", "conf", "[", ":HISTORY_FILE", "]", "=", "'~/.esp_sdk_history'", "context", "=", "Class", ".", "new", "do", "include", "ESP", "end", "irb", "=", "IRB", "::", "Irb", ".", "new", "(", "IRB", "::", "WorkSpace", ".", "new", "(", "context", ".", "new", ")", ")", "IRB", ".", "conf", "[", ":MAIN_CONTEXT", "]", "=", "irb", ".", "context", "trap", "(", "\"SIGINT\"", ")", "do", "irb", ".", "signal_handle", "end", "begin", "catch", "(", ":IRB_EXIT", ")", "do", "irb", ".", "eval_input", "end", "ensure", "IRB", ".", "irb_at_exit", "end", "end" ]
Start a console @return [void]
[ "Start", "a", "console" ]
feb1740a8e8849bdeb967a22358f9bcfaa99d215
https://github.com/EvidentSecurity/esp_sdk/blob/feb1740a8e8849bdeb967a22358f9bcfaa99d215/lib/esp/commands/console.rb#L29-L70
train