repo stringlengths 5 58 | path stringlengths 9 168 | func_name stringlengths 9 130 | original_string stringlengths 66 10.5k | language stringclasses 1
value | code stringlengths 66 10.5k | code_tokens list | docstring stringlengths 8 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 94 266 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
mayoral/telegrammer | lib/telegrammer/bot.rb | Telegrammer.Bot.send_document | def send_document(params)
extra_params_validation = {
document: { required: true, class: [File, String] }
}
send_something(:document, params, extra_params_validation)
end | ruby | def send_document(params)
extra_params_validation = {
document: { required: true, class: [File, String] }
}
send_something(:document, params, extra_params_validation)
end | [
"def",
"send_document",
"(",
"params",
")",
"extra_params_validation",
"=",
"{",
"document",
":",
"{",
"required",
":",
"true",
",",
"class",
":",
"[",
"File",
",",
"String",
"]",
"}",
"}",
"send_something",
"(",
":document",
",",
"params",
",",
"extra_par... | Sends a document to a user or group chat.
@param [Hash] params hash of paramers to send to the sendDocument API operation.
@option params [Integer,String] :chat_id Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername).
@option params [File,String] :docume... | [
"Sends",
"a",
"document",
"to",
"a",
"user",
"or",
"group",
"chat",
"."
] | be85007a647fcebec7e0b5ed1ff86f4dd924a62a | https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L288-L294 | train |
mayoral/telegrammer | lib/telegrammer/bot.rb | Telegrammer.Bot.send_sticker | def send_sticker(params)
extra_params_validation = {
sticker: { required: true, class: [File, String] }
}
send_something(:sticker, params, extra_params_validation)
end | ruby | def send_sticker(params)
extra_params_validation = {
sticker: { required: true, class: [File, String] }
}
send_something(:sticker, params, extra_params_validation)
end | [
"def",
"send_sticker",
"(",
"params",
")",
"extra_params_validation",
"=",
"{",
"sticker",
":",
"{",
"required",
":",
"true",
",",
"class",
":",
"[",
"File",
",",
"String",
"]",
"}",
"}",
"send_something",
"(",
":sticker",
",",
"params",
",",
"extra_params... | Send WebP images as stickers.
@param [Hash] params hash of paramers to send to the sendSticker API operation.
@option params [Integer,String] :chat_id Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername).
@option params [File,String] :sticker Required. S... | [
"Send",
"WebP",
"images",
"as",
"stickers",
"."
] | be85007a647fcebec7e0b5ed1ff86f4dd924a62a | https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L314-L320 | train |
mayoral/telegrammer | lib/telegrammer/bot.rb | Telegrammer.Bot.send_video | def send_video(params)
extra_params_validation = {
video: { required: true, class: [File, String] },
duration: { required: false, class: [Integer] },
caption: { required: false, class: [String] }
}
send_something(:video, params, extra_params_validation)
end | ruby | def send_video(params)
extra_params_validation = {
video: { required: true, class: [File, String] },
duration: { required: false, class: [Integer] },
caption: { required: false, class: [String] }
}
send_something(:video, params, extra_params_validation)
end | [
"def",
"send_video",
"(",
"params",
")",
"extra_params_validation",
"=",
"{",
"video",
":",
"{",
"required",
":",
"true",
",",
"class",
":",
"[",
"File",
",",
"String",
"]",
"}",
",",
"duration",
":",
"{",
"required",
":",
"false",
",",
"class",
":",
... | Sends a video file to a user or group chat.
At this moment, Telegram only support mp4 videos. If you need to send other formats you must use #send_document.
@param [Hash] params hash of paramers to send to the sendVideo API operation.
@option params [Integer,String] :chat_id Required. Unique identifier for the tar... | [
"Sends",
"a",
"video",
"file",
"to",
"a",
"user",
"or",
"group",
"chat",
"."
] | be85007a647fcebec7e0b5ed1ff86f4dd924a62a | https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L344-L352 | train |
mayoral/telegrammer | lib/telegrammer/bot.rb | Telegrammer.Bot.send_location | def send_location(params)
extra_params_validation = {
latitude: { required: true, class: [Float] },
longitude: { required: true, class: [Float] }
}
send_something(:location, params, extra_params_validation)
end | ruby | def send_location(params)
extra_params_validation = {
latitude: { required: true, class: [Float] },
longitude: { required: true, class: [Float] }
}
send_something(:location, params, extra_params_validation)
end | [
"def",
"send_location",
"(",
"params",
")",
"extra_params_validation",
"=",
"{",
"latitude",
":",
"{",
"required",
":",
"true",
",",
"class",
":",
"[",
"Float",
"]",
"}",
",",
"longitude",
":",
"{",
"required",
":",
"true",
",",
"class",
":",
"[",
"Flo... | Sends point on the map to a user or group chat.
@param [Hash] params hash of paramers to send to the sendAudio API operation.
@option params [Integer,String] :chat_id Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername).
@option params [Float] :latitude ... | [
"Sends",
"point",
"on",
"the",
"map",
"to",
"a",
"user",
"or",
"group",
"chat",
"."
] | be85007a647fcebec7e0b5ed1ff86f4dd924a62a | https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L371-L378 | train |
mayoral/telegrammer | lib/telegrammer/bot.rb | Telegrammer.Bot.send_chat_action | def send_chat_action(params)
params_validation = {
chat_id: { required: true, class: [Fixnum, String] },
action: { required: true, class: [String] }
}
api_request('sendChatAction', params, params_validation)
end | ruby | def send_chat_action(params)
params_validation = {
chat_id: { required: true, class: [Fixnum, String] },
action: { required: true, class: [String] }
}
api_request('sendChatAction', params, params_validation)
end | [
"def",
"send_chat_action",
"(",
"params",
")",
"params_validation",
"=",
"{",
"chat_id",
":",
"{",
"required",
":",
"true",
",",
"class",
":",
"[",
"Fixnum",
",",
"String",
"]",
"}",
",",
"action",
":",
"{",
"required",
":",
"true",
",",
"class",
":",
... | Sends a status action to a user or group chat.
Used when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status).
@param [Hash] params hash of paramers to send to the sendChatAct... | [
"Sends",
"a",
"status",
"action",
"to",
"a",
"user",
"or",
"group",
"chat",
"."
] | be85007a647fcebec7e0b5ed1ff86f4dd924a62a | https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L396-L403 | train |
mayoral/telegrammer | lib/telegrammer/bot.rb | Telegrammer.Bot.get_user_profile_photos | def get_user_profile_photos(params)
params_validation = {
user_id: { required: true, class: [Fixnum] },
offset: { required: false, class: [Fixnum] },
limit: { required: false, class: [Fixnum] }
}
response = api_request('getUserProfilePhotos', params, params_validation)
... | ruby | def get_user_profile_photos(params)
params_validation = {
user_id: { required: true, class: [Fixnum] },
offset: { required: false, class: [Fixnum] },
limit: { required: false, class: [Fixnum] }
}
response = api_request('getUserProfilePhotos', params, params_validation)
... | [
"def",
"get_user_profile_photos",
"(",
"params",
")",
"params_validation",
"=",
"{",
"user_id",
":",
"{",
"required",
":",
"true",
",",
"class",
":",
"[",
"Fixnum",
"]",
"}",
",",
"offset",
":",
"{",
"required",
":",
"false",
",",
"class",
":",
"[",
"F... | Get a list of profile pictures for a user.
@param [Hash] params hash of paramers to send to the getUserProfilePhotos API operation.
@option params [Integer] :user_id Required. Unique identifier of the target user.
@option params [Integer] :offset Optional. Sequential number of the first photo to be returned. By def... | [
"Get",
"a",
"list",
"of",
"profile",
"pictures",
"for",
"a",
"user",
"."
] | be85007a647fcebec7e0b5ed1ff86f4dd924a62a | https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L420-L430 | train |
mayoral/telegrammer | lib/telegrammer/bot.rb | Telegrammer.Bot.get_file | def get_file(params)
params_validation = {
file_id: { required: true, class: [String] }
}
response = api_request("getFile", params, params_validation)
file_object = Telegrammer::DataTypes::File.new(response.result)
"#{API_ENDPOINT}/file/bot#{@api_token}/#{file_object.file_path}"
... | ruby | def get_file(params)
params_validation = {
file_id: { required: true, class: [String] }
}
response = api_request("getFile", params, params_validation)
file_object = Telegrammer::DataTypes::File.new(response.result)
"#{API_ENDPOINT}/file/bot#{@api_token}/#{file_object.file_path}"
... | [
"def",
"get_file",
"(",
"params",
")",
"params_validation",
"=",
"{",
"file_id",
":",
"{",
"required",
":",
"true",
",",
"class",
":",
"[",
"String",
"]",
"}",
"}",
"response",
"=",
"api_request",
"(",
"\"getFile\"",
",",
"params",
",",
"params_validation"... | Get basic info about a file and prepare it for downloading.
@param [Hash] params hash of paramers to send to the getFile API operation.
@option params [String] :file_id Required. File identifier to get info about.
@example
bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')
bot.get_file(file_id: 12345678... | [
"Get",
"basic",
"info",
"about",
"a",
"file",
"and",
"prepare",
"it",
"for",
"downloading",
"."
] | be85007a647fcebec7e0b5ed1ff86f4dd924a62a | https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L445-L454 | train |
mayoral/telegrammer | lib/telegrammer/bot.rb | Telegrammer.Bot.answer_inline_query | def answer_inline_query(params)
params_validation = {
inline_query_id: { required: true, class: [String] },
results: { required: true, class: [Array] },
cache_time: { required: false, class: [Fixnum] },
is_personal: { required: false, class: [TrueClass, FalseClass] },
next_... | ruby | def answer_inline_query(params)
params_validation = {
inline_query_id: { required: true, class: [String] },
results: { required: true, class: [Array] },
cache_time: { required: false, class: [Fixnum] },
is_personal: { required: false, class: [TrueClass, FalseClass] },
next_... | [
"def",
"answer_inline_query",
"(",
"params",
")",
"params_validation",
"=",
"{",
"inline_query_id",
":",
"{",
"required",
":",
"true",
",",
"class",
":",
"[",
"String",
"]",
"}",
",",
"results",
":",
"{",
"required",
":",
"true",
",",
"class",
":",
"[",
... | Answer an inline query. On success, True is returned. No more than 50 results per query are allowed.
@param [Hash] params hash of paramers to send to the answerInlineQuery API operation.
@option params [String] :inline_query_id Required. Unique identifier for the answered query
@option params [Array] :results Requi... | [
"Answer",
"an",
"inline",
"query",
".",
"On",
"success",
"True",
"is",
"returned",
".",
"No",
"more",
"than",
"50",
"results",
"per",
"query",
"are",
"allowed",
"."
] | be85007a647fcebec7e0b5ed1ff86f4dd924a62a | https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L489-L499 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/apis/distance_matrix.rb | GoogleMapsService::Apis.DistanceMatrix.distance_matrix | def distance_matrix(origins, destinations,
mode: nil, language: nil, avoid: nil, units: nil,
departure_time: nil, arrival_time: nil, transit_mode: nil,
transit_routing_preference: nil)
params = {
origins: GoogleMapsService::Convert.waypoints(origins),
destinations: GoogleMa... | ruby | def distance_matrix(origins, destinations,
mode: nil, language: nil, avoid: nil, units: nil,
departure_time: nil, arrival_time: nil, transit_mode: nil,
transit_routing_preference: nil)
params = {
origins: GoogleMapsService::Convert.waypoints(origins),
destinations: GoogleMa... | [
"def",
"distance_matrix",
"(",
"origins",
",",
"destinations",
",",
"mode",
":",
"nil",
",",
"language",
":",
"nil",
",",
"avoid",
":",
"nil",
",",
"units",
":",
"nil",
",",
"departure_time",
":",
"nil",
",",
"arrival_time",
":",
"nil",
",",
"transit_mod... | Gets travel distance and time for a matrix of origins and destinations.
@example Simple distance matrix
origins = ["Perth, Australia", "Sydney, Australia",
"Melbourne, Australia", "Adelaide, Australia",
"Brisbane, Australia", "Darwin, Australia",
"Hobart, Australia", "Canb... | [
"Gets",
"travel",
"distance",
"and",
"time",
"for",
"a",
"matrix",
"of",
"origins",
"and",
"destinations",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/distance_matrix.rb#L58-L83 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/convert.rb | GoogleMapsService.Convert.components | def components(arg)
if arg.kind_of?(Hash)
arg = arg.sort.map { |k, v| "#{k}:#{v}" }
return arg.join("|")
end
raise ArgumentError, "Expected a Hash for components, but got #{arg.class}"
end | ruby | def components(arg)
if arg.kind_of?(Hash)
arg = arg.sort.map { |k, v| "#{k}:#{v}" }
return arg.join("|")
end
raise ArgumentError, "Expected a Hash for components, but got #{arg.class}"
end | [
"def",
"components",
"(",
"arg",
")",
"if",
"arg",
".",
"kind_of?",
"(",
"Hash",
")",
"arg",
"=",
"arg",
".",
"sort",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"\"#{k}:#{v}\"",
"}",
"return",
"arg",
".",
"join",
"(",
"\"|\"",
")",
"end",
"raise",... | Converts a dict of components to the format expected by the Google Maps
server.
@example
>> GoogleMapsService::Convert.components({"country": "US", "postal_code": "94043"})
=> "country:US|postal_code:94043"
@param [Hash] arg The component filter.
@return [String] | [
"Converts",
"a",
"dict",
"of",
"components",
"to",
"the",
"format",
"expected",
"by",
"the",
"Google",
"Maps",
"server",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/convert.rb#L94-L101 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/convert.rb | GoogleMapsService.Convert.waypoint | def waypoint(waypoint)
if waypoint.kind_of?(String)
return waypoint
end
return GoogleMapsService::Convert.latlng(waypoint)
end | ruby | def waypoint(waypoint)
if waypoint.kind_of?(String)
return waypoint
end
return GoogleMapsService::Convert.latlng(waypoint)
end | [
"def",
"waypoint",
"(",
"waypoint",
")",
"if",
"waypoint",
".",
"kind_of?",
"(",
"String",
")",
"return",
"waypoint",
"end",
"return",
"GoogleMapsService",
"::",
"Convert",
".",
"latlng",
"(",
"waypoint",
")",
"end"
] | Converts a waypoints to the format expected by the Google Maps server.
Accept two representation of waypoint:
1. String: Name of place or comma-separated lat/lon pair.
2. Hash/Array: Lat/lon pair.
@param [Array, String, Hash] waypoint Path.
@return [String] | [
"Converts",
"a",
"waypoints",
"to",
"the",
"format",
"expected",
"by",
"the",
"Google",
"Maps",
"server",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/convert.rb#L149-L154 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/apis/geocoding.rb | GoogleMapsService::Apis.Geocoding.reverse_geocode | def reverse_geocode(latlng, location_type: nil, result_type: nil, language: nil)
params = {
latlng: GoogleMapsService::Convert.latlng(latlng)
}
params[:result_type] = GoogleMapsService::Convert.join_list('|', result_type) if result_type
params[:location_type] = GoogleMapsService::Conver... | ruby | def reverse_geocode(latlng, location_type: nil, result_type: nil, language: nil)
params = {
latlng: GoogleMapsService::Convert.latlng(latlng)
}
params[:result_type] = GoogleMapsService::Convert.join_list('|', result_type) if result_type
params[:location_type] = GoogleMapsService::Conver... | [
"def",
"reverse_geocode",
"(",
"latlng",
",",
"location_type",
":",
"nil",
",",
"result_type",
":",
"nil",
",",
"language",
":",
"nil",
")",
"params",
"=",
"{",
"latlng",
":",
"GoogleMapsService",
"::",
"Convert",
".",
"latlng",
"(",
"latlng",
")",
"}",
... | Reverse geocoding is the process of converting geographic coordinates into a
human-readable address.
@example Simple lat/lon pair
client.reverse_geocode({lat: 40.714224, lng: -73.961452})
@example Multiple parameters
client.reverse_geocode([40.714224, -73.961452],
location_type: ['ROOFTOP', 'RANGE_INT... | [
"Reverse",
"geocoding",
"is",
"the",
"process",
"of",
"converting",
"geographic",
"coordinates",
"into",
"a",
"human",
"-",
"readable",
"address",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/geocoding.rb#L72-L82 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/apis/time_zone.rb | GoogleMapsService::Apis.TimeZone.timezone | def timezone(location, timestamp: Time.now, language: nil)
location = GoogleMapsService::Convert.latlng(location)
timestamp = GoogleMapsService::Convert.time(timestamp)
params = {
location: location,
timestamp: timestamp
}
params[:language] = language if language
r... | ruby | def timezone(location, timestamp: Time.now, language: nil)
location = GoogleMapsService::Convert.latlng(location)
timestamp = GoogleMapsService::Convert.time(timestamp)
params = {
location: location,
timestamp: timestamp
}
params[:language] = language if language
r... | [
"def",
"timezone",
"(",
"location",
",",
"timestamp",
":",
"Time",
".",
"now",
",",
"language",
":",
"nil",
")",
"location",
"=",
"GoogleMapsService",
"::",
"Convert",
".",
"latlng",
"(",
"location",
")",
"timestamp",
"=",
"GoogleMapsService",
"::",
"Convert... | Get time zone for a location on the earth, as well as that location's
time offset from UTC.
@example Current time zone
timezone = client.timezone([39.603481, -119.682251])
@example Time zone at certain time
timezone = client.timezone([39.603481, -119.682251], timestamp: Time.at(1608))
@param [Hash, Array] ... | [
"Get",
"time",
"zone",
"for",
"a",
"location",
"on",
"the",
"earth",
"as",
"well",
"as",
"that",
"location",
"s",
"time",
"offset",
"from",
"UTC",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/time_zone.rb#L27-L39 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/url.rb | GoogleMapsService.Url.sign_hmac | def sign_hmac(secret, payload)
secret = secret.encode('ASCII')
payload = payload.encode('ASCII')
# Decode the private key
raw_key = Base64.urlsafe_decode64(secret)
# Create a signature using the private key and the URL
digest = OpenSSL::Digest.new('sha1')
raw_signature = Open... | ruby | def sign_hmac(secret, payload)
secret = secret.encode('ASCII')
payload = payload.encode('ASCII')
# Decode the private key
raw_key = Base64.urlsafe_decode64(secret)
# Create a signature using the private key and the URL
digest = OpenSSL::Digest.new('sha1')
raw_signature = Open... | [
"def",
"sign_hmac",
"(",
"secret",
",",
"payload",
")",
"secret",
"=",
"secret",
".",
"encode",
"(",
"'ASCII'",
")",
"payload",
"=",
"payload",
".",
"encode",
"(",
"'ASCII'",
")",
"raw_key",
"=",
"Base64",
".",
"urlsafe_decode64",
"(",
"secret",
")",
"di... | Returns a base64-encoded HMAC-SHA1 signature of a given string.
@param [String] secret The key used for the signature, base64 encoded.
@param [String] payload The payload to sign.
@return [String] Base64-encoded HMAC-SHA1 signature | [
"Returns",
"a",
"base64",
"-",
"encoded",
"HMAC",
"-",
"SHA1",
"signature",
"of",
"a",
"given",
"string",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/url.rb#L16-L30 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/url.rb | GoogleMapsService.Url.unquote_unreserved | def unquote_unreserved(uri)
parts = uri.split('%')
(1..parts.length-1).each do |i|
h = parts[i][0..1]
if h =~ /^([\h]{2})(.*)/ and c = $1.to_i(16).chr and UNRESERVED_SET.include?(c)
parts[i] = c + $2
else
parts[i] = '%' + parts[i]
end
end
pa... | ruby | def unquote_unreserved(uri)
parts = uri.split('%')
(1..parts.length-1).each do |i|
h = parts[i][0..1]
if h =~ /^([\h]{2})(.*)/ and c = $1.to_i(16).chr and UNRESERVED_SET.include?(c)
parts[i] = c + $2
else
parts[i] = '%' + parts[i]
end
end
pa... | [
"def",
"unquote_unreserved",
"(",
"uri",
")",
"parts",
"=",
"uri",
".",
"split",
"(",
"'%'",
")",
"(",
"1",
"..",
"parts",
".",
"length",
"-",
"1",
")",
".",
"each",
"do",
"|",
"i",
"|",
"h",
"=",
"parts",
"[",
"i",
"]",
"[",
"0",
"..",
"1",
... | Un-escape any percent-escape sequences in a URI that are unreserved
characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
@param [String] uri
@return [String] | [
"Un",
"-",
"escape",
"any",
"percent",
"-",
"escape",
"sequences",
"in",
"a",
"URI",
"that",
"are",
"unreserved",
"characters",
".",
"This",
"leaves",
"all",
"reserved",
"illegal",
"and",
"non",
"-",
"ASCII",
"bytes",
"encoded",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/url.rb#L45-L59 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/client.rb | GoogleMapsService.Client.new_client | def new_client
client = Hurley::Client.new
client.request_options.query_class = Hurley::Query::Flat
client.request_options.redirection_limit = 0
client.header[:user_agent] = user_agent
client.connection = @connection if @connection
@request_options.each_pair {|key, value| client.req... | ruby | def new_client
client = Hurley::Client.new
client.request_options.query_class = Hurley::Query::Flat
client.request_options.redirection_limit = 0
client.header[:user_agent] = user_agent
client.connection = @connection if @connection
@request_options.each_pair {|key, value| client.req... | [
"def",
"new_client",
"client",
"=",
"Hurley",
"::",
"Client",
".",
"new",
"client",
".",
"request_options",
".",
"query_class",
"=",
"Hurley",
"::",
"Query",
"::",
"Flat",
"client",
".",
"request_options",
".",
"redirection_limit",
"=",
"0",
"client",
".",
"... | Create a new HTTP client.
@return [Hurley::Client] | [
"Create",
"a",
"new",
"HTTP",
"client",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/client.rb#L141-L152 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/client.rb | GoogleMapsService.Client.get | def get(path, params, base_url: DEFAULT_BASE_URL, accepts_client_id: true, custom_response_decoder: nil)
url = base_url + generate_auth_url(path, params, accepts_client_id)
Retriable.retriable timeout: @retry_timeout, on: RETRIABLE_ERRORS do |try|
begin
request_query_ticket
resp... | ruby | def get(path, params, base_url: DEFAULT_BASE_URL, accepts_client_id: true, custom_response_decoder: nil)
url = base_url + generate_auth_url(path, params, accepts_client_id)
Retriable.retriable timeout: @retry_timeout, on: RETRIABLE_ERRORS do |try|
begin
request_query_ticket
resp... | [
"def",
"get",
"(",
"path",
",",
"params",
",",
"base_url",
":",
"DEFAULT_BASE_URL",
",",
"accepts_client_id",
":",
"true",
",",
"custom_response_decoder",
":",
"nil",
")",
"url",
"=",
"base_url",
"+",
"generate_auth_url",
"(",
"path",
",",
"params",
",",
"ac... | Make API call.
@param [String] path Url path.
@param [String] params Request parameters.
@param [String] base_url Base Google Maps Web Service API endpoint url.
@param [Boolean] accepts_client_id Sign the request using API {#keys} instead of {#client_id}.
@param [Method] custom_response_decoder Custom method to d... | [
"Make",
"API",
"call",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/client.rb#L171-L185 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/client.rb | GoogleMapsService.Client.generate_auth_url | def generate_auth_url(path, params, accepts_client_id)
# Deterministic ordering through sorting by key.
# Useful for tests, and in the future, any caching.
if params.kind_of?(Hash)
params = params.sort
else
params = params.dup
end
if accepts_client_id and @client_id ... | ruby | def generate_auth_url(path, params, accepts_client_id)
# Deterministic ordering through sorting by key.
# Useful for tests, and in the future, any caching.
if params.kind_of?(Hash)
params = params.sort
else
params = params.dup
end
if accepts_client_id and @client_id ... | [
"def",
"generate_auth_url",
"(",
"path",
",",
"params",
",",
"accepts_client_id",
")",
"if",
"params",
".",
"kind_of?",
"(",
"Hash",
")",
"params",
"=",
"params",
".",
"sort",
"else",
"params",
"=",
"params",
".",
"dup",
"end",
"if",
"accepts_client_id",
"... | Returns the path and query string portion of the request URL,
first adding any necessary parameters.
@param [String] path The path portion of the URL.
@param [Hash] params URL parameters.
@param [Boolean] accepts_client_id Sign the request using API {#keys} instead of {#client_id}.
@return [String] | [
"Returns",
"the",
"path",
"and",
"query",
"string",
"portion",
"of",
"the",
"request",
"URL",
"first",
"adding",
"any",
"necessary",
"parameters",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/client.rb#L213-L236 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/client.rb | GoogleMapsService.Client.decode_response_body | def decode_response_body(response)
check_response_status_code(response)
body = MultiJson.load(response.body, :symbolize_keys => true)
check_body_error(response, body)
body
end | ruby | def decode_response_body(response)
check_response_status_code(response)
body = MultiJson.load(response.body, :symbolize_keys => true)
check_body_error(response, body)
body
end | [
"def",
"decode_response_body",
"(",
"response",
")",
"check_response_status_code",
"(",
"response",
")",
"body",
"=",
"MultiJson",
".",
"load",
"(",
"response",
".",
"body",
",",
":symbolize_keys",
"=>",
"true",
")",
"check_body_error",
"(",
"response",
",",
"bo... | Extract and parse body response as hash. Throw an error if there is something wrong with the response.
@param [Hurley::Response] response Web API response.
@return [Hash] Response body as hash. The hash key will be symbolized. | [
"Extract",
"and",
"parse",
"body",
"response",
"as",
"hash",
".",
"Throw",
"an",
"error",
"if",
"there",
"is",
"something",
"wrong",
"with",
"the",
"response",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/client.rb#L243-L248 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/client.rb | GoogleMapsService.Client.check_response_status_code | def check_response_status_code(response)
case response.status_code
when 200..300
# Do-nothing
when 301, 302, 303, 307
raise GoogleMapsService::Error::RedirectError.new(response), sprintf('Redirect to %s', response.header[:location])
when 401
raise GoogleMapsService::Error... | ruby | def check_response_status_code(response)
case response.status_code
when 200..300
# Do-nothing
when 301, 302, 303, 307
raise GoogleMapsService::Error::RedirectError.new(response), sprintf('Redirect to %s', response.header[:location])
when 401
raise GoogleMapsService::Error... | [
"def",
"check_response_status_code",
"(",
"response",
")",
"case",
"response",
".",
"status_code",
"when",
"200",
"..",
"300",
"when",
"301",
",",
"302",
",",
"303",
",",
"307",
"raise",
"GoogleMapsService",
"::",
"Error",
"::",
"RedirectError",
".",
"new",
... | Check HTTP response status code. Raise error if the status is not 2xx.
@param [Hurley::Response] response Web API response. | [
"Check",
"HTTP",
"response",
"status",
"code",
".",
"Raise",
"error",
"if",
"the",
"status",
"is",
"not",
"2xx",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/client.rb#L253-L266 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/apis/directions.rb | GoogleMapsService::Apis.Directions.directions | def directions(origin, destination,
mode: nil, waypoints: nil, alternatives: false, avoid: nil,
language: nil, units: nil, region: nil, departure_time: nil,
arrival_time: nil, optimize_waypoints: false, transit_mode: nil,
transit_routing_preference: nil)
params = {
origin:... | ruby | def directions(origin, destination,
mode: nil, waypoints: nil, alternatives: false, avoid: nil,
language: nil, units: nil, region: nil, departure_time: nil,
arrival_time: nil, optimize_waypoints: false, transit_mode: nil,
transit_routing_preference: nil)
params = {
origin:... | [
"def",
"directions",
"(",
"origin",
",",
"destination",
",",
"mode",
":",
"nil",
",",
"waypoints",
":",
"nil",
",",
"alternatives",
":",
"false",
",",
"avoid",
":",
"nil",
",",
"language",
":",
"nil",
",",
"units",
":",
"nil",
",",
"region",
":",
"ni... | Get directions between an origin point and a destination point.
@example Simple directions
routes = client.directions('Sydney', 'Melbourne')
@example Complex bicycling directions
routes = client.directions('Sydney', 'Melbourne',
mode: 'bicycling',
avoid: ['highways', 'tolls', 'ferries'],
... | [
"Get",
"directions",
"between",
"an",
"origin",
"point",
"and",
"a",
"destination",
"point",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/directions.rb#L62-L99 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/apis/elevation.rb | GoogleMapsService::Apis.Elevation.elevation_along_path | def elevation_along_path(path, samples)
if path.kind_of?(String)
path = "enc:%s" % path
else
path = GoogleMapsService::Convert.waypoints(path)
end
params = {
path: path,
samples: samples
}
return get('/maps/api/elevation/json', params)[:results]
... | ruby | def elevation_along_path(path, samples)
if path.kind_of?(String)
path = "enc:%s" % path
else
path = GoogleMapsService::Convert.waypoints(path)
end
params = {
path: path,
samples: samples
}
return get('/maps/api/elevation/json', params)[:results]
... | [
"def",
"elevation_along_path",
"(",
"path",
",",
"samples",
")",
"if",
"path",
".",
"kind_of?",
"(",
"String",
")",
"path",
"=",
"\"enc:%s\"",
"%",
"path",
"else",
"path",
"=",
"GoogleMapsService",
"::",
"Convert",
".",
"waypoints",
"(",
"path",
")",
"end"... | Provides elevation data sampled along a path on the surface of the earth.
@example Elevation along path
locations = [[40.714728, -73.998672], [-34.397, 150.644]]
results = client.elevation_along_path(locations, 5)
@param [String, Array] path A encoded polyline string, or a list of
latitude/longitude ... | [
"Provides",
"elevation",
"data",
"sampled",
"along",
"a",
"path",
"on",
"the",
"surface",
"of",
"the",
"earth",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/elevation.rb#L43-L56 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/apis/roads.rb | GoogleMapsService::Apis.Roads.snap_to_roads | def snap_to_roads(path, interpolate: false)
path = GoogleMapsService::Convert.waypoints(path)
params = {
path: path
}
params[:interpolate] = 'true' if interpolate
return get('/v1/snapToRoads', params,
base_url: ROADS_BASE_URL,
accepts_client_id:... | ruby | def snap_to_roads(path, interpolate: false)
path = GoogleMapsService::Convert.waypoints(path)
params = {
path: path
}
params[:interpolate] = 'true' if interpolate
return get('/v1/snapToRoads', params,
base_url: ROADS_BASE_URL,
accepts_client_id:... | [
"def",
"snap_to_roads",
"(",
"path",
",",
"interpolate",
":",
"false",
")",
"path",
"=",
"GoogleMapsService",
"::",
"Convert",
".",
"waypoints",
"(",
"path",
")",
"params",
"=",
"{",
"path",
":",
"path",
"}",
"params",
"[",
":interpolate",
"]",
"=",
"'tr... | Snaps a path to the most likely roads travelled.
Takes up to 100 GPS points collected along a route, and returns a similar
set of data with the points snapped to the most likely roads the vehicle
was traveling along.
@example Single point snap
results = client.snap_to_roads([40.714728, -73.998672])
@example ... | [
"Snaps",
"a",
"path",
"to",
"the",
"most",
"likely",
"roads",
"travelled",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/roads.rb#L38-L51 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/apis/roads.rb | GoogleMapsService::Apis.Roads.nearest_roads | def nearest_roads(points)
points = GoogleMapsService::Convert.waypoints(points)
params = {
points: points
}
return get('/v1/nearestRoads', params,
base_url: ROADS_BASE_URL,
accepts_client_id: false,
custom_response_decoder: method(:ext... | ruby | def nearest_roads(points)
points = GoogleMapsService::Convert.waypoints(points)
params = {
points: points
}
return get('/v1/nearestRoads', params,
base_url: ROADS_BASE_URL,
accepts_client_id: false,
custom_response_decoder: method(:ext... | [
"def",
"nearest_roads",
"(",
"points",
")",
"points",
"=",
"GoogleMapsService",
"::",
"Convert",
".",
"waypoints",
"(",
"points",
")",
"params",
"=",
"{",
"points",
":",
"points",
"}",
"return",
"get",
"(",
"'/v1/nearestRoads'",
",",
"params",
",",
"base_url... | Returns the nearest road segments for provided points.
The points passed do not need to be part of a continuous path.
@example Single point snap
results = client.nearest_roads([40.714728, -73.998672])
@example Multi points snap
points = [
[-33.8671, 151.20714],
[-33.86708, 151.20683000000002],
... | [
"Returns",
"the",
"nearest",
"road",
"segments",
"for",
"provided",
"points",
".",
"The",
"points",
"passed",
"do",
"not",
"need",
"to",
"be",
"part",
"of",
"a",
"continuous",
"path",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/roads.rb#L128-L139 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/apis/roads.rb | GoogleMapsService::Apis.Roads.extract_roads_body | def extract_roads_body(response)
begin
body = MultiJson.load(response.body, :symbolize_keys => true)
rescue
unless response.status_code == 200
check_response_status_code(response)
end
raise GoogleMapsService::Error::ApiError.new(response), 'Received a ... | ruby | def extract_roads_body(response)
begin
body = MultiJson.load(response.body, :symbolize_keys => true)
rescue
unless response.status_code == 200
check_response_status_code(response)
end
raise GoogleMapsService::Error::ApiError.new(response), 'Received a ... | [
"def",
"extract_roads_body",
"(",
"response",
")",
"begin",
"body",
"=",
"MultiJson",
".",
"load",
"(",
"response",
".",
"body",
",",
":symbolize_keys",
"=>",
"true",
")",
"rescue",
"unless",
"response",
".",
"status_code",
"==",
"200",
"check_response_status_co... | Extracts a result from a Roads API HTTP response. | [
"Extracts",
"a",
"result",
"from",
"a",
"Roads",
"API",
"HTTP",
"response",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/roads.rb#L145-L161 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/polyline.rb | GoogleMapsService.Polyline.encode | def encode(points)
last_lat = last_lng = 0
result = ""
points.each do |point|
ll = GoogleMapsService::Convert.normalize_latlng(point)
lat = (ll[0] * 1e5).round.to_i
lng = (ll[1] * 1e5).round.to_i
d_lat = lat - last_lat
d_lng = lng - last_lng
[d_lat, d_... | ruby | def encode(points)
last_lat = last_lng = 0
result = ""
points.each do |point|
ll = GoogleMapsService::Convert.normalize_latlng(point)
lat = (ll[0] * 1e5).round.to_i
lng = (ll[1] * 1e5).round.to_i
d_lat = lat - last_lat
d_lng = lng - last_lng
[d_lat, d_... | [
"def",
"encode",
"(",
"points",
")",
"last_lat",
"=",
"last_lng",
"=",
"0",
"result",
"=",
"\"\"",
"points",
".",
"each",
"do",
"|",
"point",
"|",
"ll",
"=",
"GoogleMapsService",
"::",
"Convert",
".",
"normalize_latlng",
"(",
"point",
")",
"lat",
"=",
... | Encodes a list of points into a polyline string.
See the developer docs for a detailed description of this encoding:
https://developers.google.com/maps/documentation/utilities/polylinealgorithm
@param [Array<Hash>, Array<Array>] points A list of lat/lng pairs.
@return [String] | [
"Encodes",
"a",
"list",
"of",
"points",
"into",
"a",
"polyline",
"string",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/polyline.rb#L63-L88 | train |
mongoid/mongoid_fulltext | lib/mongoid/full_text_search.rb | Mongoid::FullTextSearch.ClassMethods.map_query_filters | def map_query_filters(filters)
Hash[filters.map do |key, value|
case value
when Hash then
if value.key? :any then format_query_filter('$in', key, value[:any])
elsif value.key? :all then format_query_filter('$all', key, value[:all])
else raise UnknownFilterQueryOperato... | ruby | def map_query_filters(filters)
Hash[filters.map do |key, value|
case value
when Hash then
if value.key? :any then format_query_filter('$in', key, value[:any])
elsif value.key? :all then format_query_filter('$all', key, value[:all])
else raise UnknownFilterQueryOperato... | [
"def",
"map_query_filters",
"(",
"filters",
")",
"Hash",
"[",
"filters",
".",
"map",
"do",
"|",
"key",
",",
"value",
"|",
"case",
"value",
"when",
"Hash",
"then",
"if",
"value",
".",
"key?",
":any",
"then",
"format_query_filter",
"(",
"'$in'",
",",
"key"... | Take a list of filters to be mapped so they can update the query
used upon the fulltext search of the ngrams | [
"Take",
"a",
"list",
"of",
"filters",
"to",
"be",
"mapped",
"so",
"they",
"can",
"update",
"the",
"query",
"used",
"upon",
"the",
"fulltext",
"search",
"of",
"the",
"ngrams"
] | 3d212b0eaec2b93b54d9514603bc24b3b2594104 | https://github.com/mongoid/mongoid_fulltext/blob/3d212b0eaec2b93b54d9514603bc24b3b2594104/lib/mongoid/full_text_search.rb#L300-L310 | train |
copiousfreetime/stickler | lib/stickler/spec_lite.rb | Stickler.SpecLite.=~ | def =~(other)
other = coerce( other )
return (other and
self.name == other.name and
self.version.to_s == other.version.to_s and
self.platform_string == other.platform_string )
end | ruby | def =~(other)
other = coerce( other )
return (other and
self.name == other.name and
self.version.to_s == other.version.to_s and
self.platform_string == other.platform_string )
end | [
"def",
"=~",
"(",
"other",
")",
"other",
"=",
"coerce",
"(",
"other",
")",
"return",
"(",
"other",
"and",
"self",
".",
"name",
"==",
"other",
".",
"name",
"and",
"self",
".",
"version",
".",
"to_s",
"==",
"other",
".",
"version",
".",
"to_s",
"and"... | Lets be comparable!
See if another Spec is the same as this spec | [
"Lets",
"be",
"comparable!"
] | 9c9ef5b2287c0be071da0a233e2b262e98c878e5 | https://github.com/copiousfreetime/stickler/blob/9c9ef5b2287c0be071da0a233e2b262e98c878e5/lib/stickler/spec_lite.rb#L85-L91 | train |
copiousfreetime/stickler | lib/stickler/repository/remote_mirror.rb | ::Stickler::Repository.RemoteMirror.mirror | def mirror( spec, upstream_host )
raise Stickler::Repository::Error, "gem #{spec.full_name} already exists in remote repository" if remote_gem_file_exist?( spec )
resource_request( mirror_resource( spec, upstream_host ) )
end | ruby | def mirror( spec, upstream_host )
raise Stickler::Repository::Error, "gem #{spec.full_name} already exists in remote repository" if remote_gem_file_exist?( spec )
resource_request( mirror_resource( spec, upstream_host ) )
end | [
"def",
"mirror",
"(",
"spec",
",",
"upstream_host",
")",
"raise",
"Stickler",
"::",
"Repository",
"::",
"Error",
",",
"\"gem #{spec.full_name} already exists in remote repository\"",
"if",
"remote_gem_file_exist?",
"(",
"spec",
")",
"resource_request",
"(",
"mirror_resour... | Tell the remote repoistory to mirror the given gem from an upstream
repository | [
"Tell",
"the",
"remote",
"repoistory",
"to",
"mirror",
"the",
"given",
"gem",
"from",
"an",
"upstream",
"repository"
] | 9c9ef5b2287c0be071da0a233e2b262e98c878e5 | https://github.com/copiousfreetime/stickler/blob/9c9ef5b2287c0be071da0a233e2b262e98c878e5/lib/stickler/repository/remote_mirror.rb#L14-L17 | train |
copiousfreetime/stickler | lib/stickler/middleware/index.rb | Stickler::Middleware.Index.marshalled_specs | def marshalled_specs( spec_a )
a = spec_a.collect { |s| s.to_rubygems_a }
marshal( optimize_specs( a ) )
end | ruby | def marshalled_specs( spec_a )
a = spec_a.collect { |s| s.to_rubygems_a }
marshal( optimize_specs( a ) )
end | [
"def",
"marshalled_specs",
"(",
"spec_a",
")",
"a",
"=",
"spec_a",
".",
"collect",
"{",
"|",
"s",
"|",
"s",
".",
"to_rubygems_a",
"}",
"marshal",
"(",
"optimize_specs",
"(",
"a",
")",
")",
"end"
] | Convert to the array format used by gem servers
everywhere | [
"Convert",
"to",
"the",
"array",
"format",
"used",
"by",
"gem",
"servers",
"everywhere"
] | 9c9ef5b2287c0be071da0a233e2b262e98c878e5 | https://github.com/copiousfreetime/stickler/blob/9c9ef5b2287c0be071da0a233e2b262e98c878e5/lib/stickler/middleware/index.rb#L153-L156 | train |
copiousfreetime/stickler | lib/stickler/client.rb | Stickler.Client.parser | def parser
me = self # scoping forces this
@parser ||= Trollop::Parser.new do
banner me.class.banner
opt :server, "The gem or stickler server URL", :type => :string, :default => Client.config.server
opt :debug, "Output debug information for the server interaction", :default => false
... | ruby | def parser
me = self # scoping forces this
@parser ||= Trollop::Parser.new do
banner me.class.banner
opt :server, "The gem or stickler server URL", :type => :string, :default => Client.config.server
opt :debug, "Output debug information for the server interaction", :default => false
... | [
"def",
"parser",
"me",
"=",
"self",
"@parser",
"||=",
"Trollop",
"::",
"Parser",
".",
"new",
"do",
"banner",
"me",
".",
"class",
".",
"banner",
"opt",
":server",
",",
"\"The gem or stickler server URL\"",
",",
":type",
"=>",
":string",
",",
":default",
"=>",... | Create a new client
Takes an argv like array as a parameter. | [
"Create",
"a",
"new",
"client"
] | 9c9ef5b2287c0be071da0a233e2b262e98c878e5 | https://github.com/copiousfreetime/stickler/blob/9c9ef5b2287c0be071da0a233e2b262e98c878e5/lib/stickler/client.rb#L21-L28 | train |
janko/flickr-objects | lib/flickr/attributes.rb | Flickr.Attribute.find_value | def find_value(context)
locations.each do |location|
begin
value = context.instance_exec(&location)
next if value.nil?
return value
rescue
end
end
nil
end | ruby | def find_value(context)
locations.each do |location|
begin
value = context.instance_exec(&location)
next if value.nil?
return value
rescue
end
end
nil
end | [
"def",
"find_value",
"(",
"context",
")",
"locations",
".",
"each",
"do",
"|",
"location",
"|",
"begin",
"value",
"=",
"context",
".",
"instance_exec",
"(",
"&",
"location",
")",
"next",
"if",
"value",
".",
"nil?",
"return",
"value",
"rescue",
"end",
"en... | Finds attribute value in the JSON response by looking at the given locations. | [
"Finds",
"attribute",
"value",
"in",
"the",
"JSON",
"response",
"by",
"looking",
"at",
"the",
"given",
"locations",
"."
] | dd25554e0002e76f4045542a9abdcdb754a94df6 | https://github.com/janko/flickr-objects/blob/dd25554e0002e76f4045542a9abdcdb754a94df6/lib/flickr/attributes.rb#L79-L90 | train |
janko/flickr-objects | lib/flickr/attributes.rb | Flickr.AttributeSet.add_locations | def add_locations(hash)
hash.each do |attribute_name, locations|
find(attribute_name).add_locations(locations)
end
end | ruby | def add_locations(hash)
hash.each do |attribute_name, locations|
find(attribute_name).add_locations(locations)
end
end | [
"def",
"add_locations",
"(",
"hash",
")",
"hash",
".",
"each",
"do",
"|",
"attribute_name",
",",
"locations",
"|",
"find",
"(",
"attribute_name",
")",
".",
"add_locations",
"(",
"locations",
")",
"end",
"end"
] | Shorthand for adding locations to multiple attributes at once. | [
"Shorthand",
"for",
"adding",
"locations",
"to",
"multiple",
"attributes",
"at",
"once",
"."
] | dd25554e0002e76f4045542a9abdcdb754a94df6 | https://github.com/janko/flickr-objects/blob/dd25554e0002e76f4045542a9abdcdb754a94df6/lib/flickr/attributes.rb#L187-L191 | train |
janko/flickr-objects | spec/support/helpers.rb | Helpers.ClassMethods.record_api_methods | def record_api_methods
before do
stub_const("Flickr::Client::Data", Class.new(Flickr::Client::Data) do
def do_request(http_method, flickr_method, params = {})
VCR.use_cassette(flickr_method) { super }
end
end)
stub_const("Flickr::Client::Upload", Class.new(... | ruby | def record_api_methods
before do
stub_const("Flickr::Client::Data", Class.new(Flickr::Client::Data) do
def do_request(http_method, flickr_method, params = {})
VCR.use_cassette(flickr_method) { super }
end
end)
stub_const("Flickr::Client::Upload", Class.new(... | [
"def",
"record_api_methods",
"before",
"do",
"stub_const",
"(",
"\"Flickr::Client::Data\"",
",",
"Class",
".",
"new",
"(",
"Flickr",
"::",
"Client",
"::",
"Data",
")",
"do",
"def",
"do_request",
"(",
"http_method",
",",
"flickr_method",
",",
"params",
"=",
"{"... | Wraps a VCR cassette around API calls with the same name as the Flickr
method called. For example, the cassette for `Flickr.sets.create` will
be called "flickr.photosets.create". Because we repeat the same API calls
in different examples, we can just reuse those VCR cassettes rather than
recording new ones. | [
"Wraps",
"a",
"VCR",
"cassette",
"around",
"API",
"calls",
"with",
"the",
"same",
"name",
"as",
"the",
"Flickr",
"method",
"called",
".",
"For",
"example",
"the",
"cassette",
"for",
"Flickr",
".",
"sets",
".",
"create",
"will",
"be",
"called",
"flickr",
... | dd25554e0002e76f4045542a9abdcdb754a94df6 | https://github.com/janko/flickr-objects/blob/dd25554e0002e76f4045542a9abdcdb754a94df6/spec/support/helpers.rb#L30-L48 | train |
janko/flickr-objects | lib/flickr/object.rb | Flickr.Object.inspect | def inspect
attribute_values = self.class.attributes
.inject({}) { |hash, attribute| hash.update(attribute.name => send(attribute.name)) }
.reject { |name, value| value.nil? or (value.respond_to?(:empty?) and value.empty?) }
attributes = attribute_values
.map { |name, value| "#{name}... | ruby | def inspect
attribute_values = self.class.attributes
.inject({}) { |hash, attribute| hash.update(attribute.name => send(attribute.name)) }
.reject { |name, value| value.nil? or (value.respond_to?(:empty?) and value.empty?) }
attributes = attribute_values
.map { |name, value| "#{name}... | [
"def",
"inspect",
"attribute_values",
"=",
"self",
".",
"class",
".",
"attributes",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"hash",
",",
"attribute",
"|",
"hash",
".",
"update",
"(",
"attribute",
".",
"name",
"=>",
"send",
"(",
"attribute",
".",
... | Displays all the attributes and their values. | [
"Displays",
"all",
"the",
"attributes",
"and",
"their",
"values",
"."
] | dd25554e0002e76f4045542a9abdcdb754a94df6 | https://github.com/janko/flickr-objects/blob/dd25554e0002e76f4045542a9abdcdb754a94df6/lib/flickr/object.rb#L85-L97 | train |
janko/flickr-objects | lib/flickr/sanitized_file.rb | Flickr.SanitizedFile.sanitize! | def sanitize!
if rails_file?
@file = @original
@content_type = @original.content_type
@path = @original.tempfile
elsif sinatra_file?
@file = @original[:tempfile]
@content_type = @original[:type]
@path = @original[:tempfile].path
elsif io?
@file =... | ruby | def sanitize!
if rails_file?
@file = @original
@content_type = @original.content_type
@path = @original.tempfile
elsif sinatra_file?
@file = @original[:tempfile]
@content_type = @original[:type]
@path = @original[:tempfile].path
elsif io?
@file =... | [
"def",
"sanitize!",
"if",
"rails_file?",
"@file",
"=",
"@original",
"@content_type",
"=",
"@original",
".",
"content_type",
"@path",
"=",
"@original",
".",
"tempfile",
"elsif",
"sinatra_file?",
"@file",
"=",
"@original",
"[",
":tempfile",
"]",
"@content_type",
"="... | Extracts the tempfile, content type and path. | [
"Extracts",
"the",
"tempfile",
"content",
"type",
"and",
"path",
"."
] | dd25554e0002e76f4045542a9abdcdb754a94df6 | https://github.com/janko/flickr-objects/blob/dd25554e0002e76f4045542a9abdcdb754a94df6/lib/flickr/sanitized_file.rb#L30-L50 | train |
dei79/jquery-modal-rails | lib/jquery/modal/helpers/link_helpers.rb | Jquery.Helpers.link_to_modal | def link_to_modal(*args, &block)
if block_given?
options = args.first || {}
html_options = args.second
block_result = capture(&block)
link_to_modal(block_result, options, html_options)
else
name = args[0]
options = args[1] || {}
html_... | ruby | def link_to_modal(*args, &block)
if block_given?
options = args.first || {}
html_options = args.second
block_result = capture(&block)
link_to_modal(block_result, options, html_options)
else
name = args[0]
options = args[1] || {}
html_... | [
"def",
"link_to_modal",
"(",
"*",
"args",
",",
"&",
"block",
")",
"if",
"block_given?",
"options",
"=",
"args",
".",
"first",
"||",
"{",
"}",
"html_options",
"=",
"args",
".",
"second",
"block_result",
"=",
"capture",
"(",
"&",
"block",
")",
"link_to_mod... | Creates a link tag to a given url or path and ensures that the linke will be rendered
as jquery modal dialog
==== Signatures
link_to(body, url, html_options = {})
link_to(body, url) | [
"Creates",
"a",
"link",
"tag",
"to",
"a",
"given",
"url",
"or",
"path",
"and",
"ensures",
"that",
"the",
"linke",
"will",
"be",
"rendered",
"as",
"jquery",
"modal",
"dialog"
] | 9aa5e120131108577cfeb9600dde7343d95a034f | https://github.com/dei79/jquery-modal-rails/blob/9aa5e120131108577cfeb9600dde7343d95a034f/lib/jquery/modal/helpers/link_helpers.rb#L12-L43 | train |
ashmaroli/jekyll-data | lib/jekyll-data/reader.rb | JekyllData.Reader.read_theme_data | def read_theme_data
if @theme.data_path
#
# show contents of "<theme>/_data/" dir being read while degugging.
inspect_theme_data
theme_data = ThemeDataReader.new(site).read(site.config["data_dir"])
@site.data = Jekyll::Utils.deep_merge_hashes(theme_data, @site.data)
... | ruby | def read_theme_data
if @theme.data_path
#
# show contents of "<theme>/_data/" dir being read while degugging.
inspect_theme_data
theme_data = ThemeDataReader.new(site).read(site.config["data_dir"])
@site.data = Jekyll::Utils.deep_merge_hashes(theme_data, @site.data)
... | [
"def",
"read_theme_data",
"if",
"@theme",
".",
"data_path",
"inspect_theme_data",
"theme_data",
"=",
"ThemeDataReader",
".",
"new",
"(",
"site",
")",
".",
"read",
"(",
"site",
".",
"config",
"[",
"\"data_dir\"",
"]",
")",
"@site",
".",
"data",
"=",
"Jekyll",... | Read data files within a theme gem and add them to internal data
Returns a hash appended with new data | [
"Read",
"data",
"files",
"within",
"a",
"theme",
"gem",
"and",
"add",
"them",
"to",
"internal",
"data"
] | 7fb2b51db67c864c9e596a759c0df46efc78c86d | https://github.com/ashmaroli/jekyll-data/blob/7fb2b51db67c864c9e596a759c0df46efc78c86d/lib/jekyll-data/reader.rb#L25-L37 | train |
ashmaroli/jekyll-data | lib/jekyll-data/reader.rb | JekyllData.Reader.inspect_inner_hash | def inspect_inner_hash(hash)
hash.each do |key, value|
if value.is_a? Array
print_label key
extract_hashes_and_print value
elsif value.is_a? Hash
print_subkey_and_value key, value
else
print_hash key, value
end
end
end | ruby | def inspect_inner_hash(hash)
hash.each do |key, value|
if value.is_a? Array
print_label key
extract_hashes_and_print value
elsif value.is_a? Hash
print_subkey_and_value key, value
else
print_hash key, value
end
end
end | [
"def",
"inspect_inner_hash",
"(",
"hash",
")",
"hash",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"value",
".",
"is_a?",
"Array",
"print_label",
"key",
"extract_hashes_and_print",
"value",
"elsif",
"value",
".",
"is_a?",
"Hash",
"print_subkey_and_... | Analyse deeper hashes and extract contents to output | [
"Analyse",
"deeper",
"hashes",
"and",
"extract",
"contents",
"to",
"output"
] | 7fb2b51db67c864c9e596a759c0df46efc78c86d | https://github.com/ashmaroli/jekyll-data/blob/7fb2b51db67c864c9e596a759c0df46efc78c86d/lib/jekyll-data/reader.rb#L98-L109 | train |
ashmaroli/jekyll-data | lib/jekyll-data/reader.rb | JekyllData.Reader.print_subkey_and_value | def print_subkey_and_value(key, value)
print_label key
value.each do |subkey, val|
if val.is_a? Hash
print_inner_subkey subkey
inspect_inner_hash val
elsif val.is_a? Array
print_inner_subkey subkey
extract_hashes_and_print val
elsif val.is_a? S... | ruby | def print_subkey_and_value(key, value)
print_label key
value.each do |subkey, val|
if val.is_a? Hash
print_inner_subkey subkey
inspect_inner_hash val
elsif val.is_a? Array
print_inner_subkey subkey
extract_hashes_and_print val
elsif val.is_a? S... | [
"def",
"print_subkey_and_value",
"(",
"key",
",",
"value",
")",
"print_label",
"key",
"value",
".",
"each",
"do",
"|",
"subkey",
",",
"val",
"|",
"if",
"val",
".",
"is_a?",
"Hash",
"print_inner_subkey",
"subkey",
"inspect_inner_hash",
"val",
"elsif",
"val",
... | Prints label, keys and values of mappings | [
"Prints",
"label",
"keys",
"and",
"values",
"of",
"mappings"
] | 7fb2b51db67c864c9e596a759c0df46efc78c86d | https://github.com/ashmaroli/jekyll-data/blob/7fb2b51db67c864c9e596a759c0df46efc78c86d/lib/jekyll-data/reader.rb#L176-L189 | train |
RubyDevInc/paho.mqtt.ruby | lib/paho_mqtt/connection_helper.rb | PahoMqtt.ConnectionHelper.should_send_ping? | def should_send_ping?(now, keep_alive, last_packet_received_at)
last_pingreq_sent_at = @sender.last_pingreq_sent_at
last_pingresp_received_at = @handler.last_pingresp_received_at
if !last_pingreq_sent_at || (last_pingresp_received_at && (last_pingreq_sent_at <= last_pingresp_received_at))
next... | ruby | def should_send_ping?(now, keep_alive, last_packet_received_at)
last_pingreq_sent_at = @sender.last_pingreq_sent_at
last_pingresp_received_at = @handler.last_pingresp_received_at
if !last_pingreq_sent_at || (last_pingresp_received_at && (last_pingreq_sent_at <= last_pingresp_received_at))
next... | [
"def",
"should_send_ping?",
"(",
"now",
",",
"keep_alive",
",",
"last_packet_received_at",
")",
"last_pingreq_sent_at",
"=",
"@sender",
".",
"last_pingreq_sent_at",
"last_pingresp_received_at",
"=",
"@handler",
".",
"last_pingresp_received_at",
"if",
"!",
"last_pingreq_sent... | Would return 'true' if ping requset should be sent and 'nil' if not | [
"Would",
"return",
"true",
"if",
"ping",
"requset",
"should",
"be",
"sent",
"and",
"nil",
"if",
"not"
] | 1a3a14ac5b646132829fb0f38c794cae503989d2 | https://github.com/RubyDevInc/paho.mqtt.ruby/blob/1a3a14ac5b646132829fb0f38c794cae503989d2/lib/paho_mqtt/connection_helper.rb#L147-L154 | train |
morgoth/picasa | lib/picasa/utils.rb | Picasa.Utils.array_wrap | def array_wrap(object)
if object.nil?
[]
elsif object.respond_to?(:to_ary)
object.to_ary || [object]
else
[object]
end
end | ruby | def array_wrap(object)
if object.nil?
[]
elsif object.respond_to?(:to_ary)
object.to_ary || [object]
else
[object]
end
end | [
"def",
"array_wrap",
"(",
"object",
")",
"if",
"object",
".",
"nil?",
"[",
"]",
"elsif",
"object",
".",
"respond_to?",
"(",
":to_ary",
")",
"object",
".",
"to_ary",
"||",
"[",
"object",
"]",
"else",
"[",
"object",
"]",
"end",
"end"
] | Ported from activesupport gem | [
"Ported",
"from",
"activesupport",
"gem"
] | 94672fab0baa24eb2db9c6aba5b03920be9f98f2 | https://github.com/morgoth/picasa/blob/94672fab0baa24eb2db9c6aba5b03920be9f98f2/lib/picasa/utils.rb#L26-L34 | train |
coderanger/rspec-command | lib/rspec_command/match_fixture.rb | RSpecCommand.MatchFixture.failure_message | def failure_message
matching_files = @fixture.files & @local.files
fixture_only_files = @fixture.files - @local.files
local_only_files = @local.files - @fixture.files
buf = "expected fixture #{@fixture.path} to match files:\n"
(@fixture.files | @local.files).sort.each do |file|
if ... | ruby | def failure_message
matching_files = @fixture.files & @local.files
fixture_only_files = @fixture.files - @local.files
local_only_files = @local.files - @fixture.files
buf = "expected fixture #{@fixture.path} to match files:\n"
(@fixture.files | @local.files).sort.each do |file|
if ... | [
"def",
"failure_message",
"matching_files",
"=",
"@fixture",
".",
"files",
"&",
"@local",
".",
"files",
"fixture_only_files",
"=",
"@fixture",
".",
"files",
"-",
"@local",
".",
"files",
"local_only_files",
"=",
"@local",
".",
"files",
"-",
"@fixture",
".",
"fi... | Callback fro RSpec. Returns a human-readable failure message.
@return [String] | [
"Callback",
"fro",
"RSpec",
".",
"Returns",
"a",
"human",
"-",
"readable",
"failure",
"message",
"."
] | 3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9 | https://github.com/coderanger/rspec-command/blob/3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9/lib/rspec_command/match_fixture.rb#L51-L82 | train |
coderanger/rspec-command | lib/rspec_command/match_fixture.rb | RSpecCommand.MatchFixture.file_content_match? | def file_content_match?
@fixture.full_files.zip(@local.full_files).all? do |fixture_file, local_file|
if File.directory?(fixture_file)
File.directory?(local_file)
else
!File.directory?(local_file) && IO.read(fixture_file) == IO.read(local_file)
end
end
end | ruby | def file_content_match?
@fixture.full_files.zip(@local.full_files).all? do |fixture_file, local_file|
if File.directory?(fixture_file)
File.directory?(local_file)
else
!File.directory?(local_file) && IO.read(fixture_file) == IO.read(local_file)
end
end
end | [
"def",
"file_content_match?",
"@fixture",
".",
"full_files",
".",
"zip",
"(",
"@local",
".",
"full_files",
")",
".",
"all?",
"do",
"|",
"fixture_file",
",",
"local_file",
"|",
"if",
"File",
".",
"directory?",
"(",
"fixture_file",
")",
"File",
".",
"directory... | Do the file contents match?
@return [Boolean] | [
"Do",
"the",
"file",
"contents",
"match?"
] | 3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9 | https://github.com/coderanger/rspec-command/blob/3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9/lib/rspec_command/match_fixture.rb#L96-L104 | train |
coderanger/rspec-command | lib/rspec_command.rb | RSpecCommand.ClassMethods.file | def file(path, content=nil, &block)
raise "file path should be relative the the temporary directory." if path == File.expand_path(path)
before do
content = instance_eval(&block) if block
dest_path = File.join(temp_path, path)
FileUtils.mkdir_p(File.dirname(dest_path))
IO.writ... | ruby | def file(path, content=nil, &block)
raise "file path should be relative the the temporary directory." if path == File.expand_path(path)
before do
content = instance_eval(&block) if block
dest_path = File.join(temp_path, path)
FileUtils.mkdir_p(File.dirname(dest_path))
IO.writ... | [
"def",
"file",
"(",
"path",
",",
"content",
"=",
"nil",
",",
"&",
"block",
")",
"raise",
"\"file path should be relative the the temporary directory.\"",
"if",
"path",
"==",
"File",
".",
"expand_path",
"(",
"path",
")",
"before",
"do",
"content",
"=",
"instance_... | Create a file in the temporary directory for this example.
@param path [String] Path within the temporary directory to write to.
@param content [String] File data to write.
@param block [Proc] Optional block to return file data to write.
@example
describe 'myapp' do
command 'myapp read data.txt'
file ... | [
"Create",
"a",
"file",
"in",
"the",
"temporary",
"directory",
"for",
"this",
"example",
"."
] | 3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9 | https://github.com/coderanger/rspec-command/blob/3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9/lib/rspec_command.rb#L298-L306 | train |
coderanger/rspec-command | lib/rspec_command.rb | RSpecCommand.ClassMethods.fixture_file | def fixture_file(path, dest=nil)
raise "file path should be relative the the temporary directory." if path == File.expand_path(path)
before do |example|
fixture_path = find_fixture(example.file_path, path)
dest_path = dest ? File.join(temp_path, dest) : temp_path
FileUtils.mkdir_p(de... | ruby | def fixture_file(path, dest=nil)
raise "file path should be relative the the temporary directory." if path == File.expand_path(path)
before do |example|
fixture_path = find_fixture(example.file_path, path)
dest_path = dest ? File.join(temp_path, dest) : temp_path
FileUtils.mkdir_p(de... | [
"def",
"fixture_file",
"(",
"path",
",",
"dest",
"=",
"nil",
")",
"raise",
"\"file path should be relative the the temporary directory.\"",
"if",
"path",
"==",
"File",
".",
"expand_path",
"(",
"path",
")",
"before",
"do",
"|",
"example",
"|",
"fixture_path",
"=",
... | Copy fixture data from the spec folder to the temporary directory for this
example.
@param path [String] Path of the fixture to copy.
@param dest [String] Optional destination path. By default the destination
is the same as path.
@example
describe 'myapp' do
command 'myapp run test/'
fixture_file '... | [
"Copy",
"fixture",
"data",
"from",
"the",
"spec",
"folder",
"to",
"the",
"temporary",
"directory",
"for",
"this",
"example",
"."
] | 3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9 | https://github.com/coderanger/rspec-command/blob/3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9/lib/rspec_command.rb#L320-L336 | train |
coderanger/rspec-command | lib/rspec_command.rb | RSpecCommand.ClassMethods.environment | def environment(variables)
before do
variables.each do |key, value|
if value.nil?
_environment.delete(key.to_s)
else
_environment[key.to_s] = value.to_s
end
end
end
end | ruby | def environment(variables)
before do
variables.each do |key, value|
if value.nil?
_environment.delete(key.to_s)
else
_environment[key.to_s] = value.to_s
end
end
end
end | [
"def",
"environment",
"(",
"variables",
")",
"before",
"do",
"variables",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"value",
".",
"nil?",
"_environment",
".",
"delete",
"(",
"key",
".",
"to_s",
")",
"else",
"_environment",
"[",
"key",
"."... | Set an environment variable for this example.
@param variables [Hash] Key/value pairs to set.
@example
describe 'myapp' do
command 'myapp show'
environment DEBUG: true
its(:stderr) { is_expected.to include('[debug]') }
end | [
"Set",
"an",
"environment",
"variable",
"for",
"this",
"example",
"."
] | 3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9 | https://github.com/coderanger/rspec-command/blob/3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9/lib/rspec_command.rb#L347-L357 | train |
cheezy/data_magic | lib/data_magic/standard_translation.rb | DataMagic.StandardTranslation.randomize | def randomize(value)
case value
when Array then value[rand(value.size)]
when Range then rand((value.last+1) - value.first) + value.first
else value
end
end | ruby | def randomize(value)
case value
when Array then value[rand(value.size)]
when Range then rand((value.last+1) - value.first) + value.first
else value
end
end | [
"def",
"randomize",
"(",
"value",
")",
"case",
"value",
"when",
"Array",
"then",
"value",
"[",
"rand",
"(",
"value",
".",
"size",
")",
"]",
"when",
"Range",
"then",
"rand",
"(",
"(",
"value",
".",
"last",
"+",
"1",
")",
"-",
"value",
".",
"first",
... | return a random value from an array or range | [
"return",
"a",
"random",
"value",
"from",
"an",
"array",
"or",
"range"
] | ac0dc18b319bf3974f9a79704a7636dbf55059ae | https://github.com/cheezy/data_magic/blob/ac0dc18b319bf3974f9a79704a7636dbf55059ae/lib/data_magic/standard_translation.rb#L236-L242 | train |
cheezy/data_magic | lib/data_magic/standard_translation.rb | DataMagic.StandardTranslation.sequential | def sequential(value)
index = index_variable_for(value)
index = (index ? index + 1 : 0)
index = 0 if index == value.length
set_index_variable(value, index)
value[index]
end | ruby | def sequential(value)
index = index_variable_for(value)
index = (index ? index + 1 : 0)
index = 0 if index == value.length
set_index_variable(value, index)
value[index]
end | [
"def",
"sequential",
"(",
"value",
")",
"index",
"=",
"index_variable_for",
"(",
"value",
")",
"index",
"=",
"(",
"index",
"?",
"index",
"+",
"1",
":",
"0",
")",
"index",
"=",
"0",
"if",
"index",
"==",
"value",
".",
"length",
"set_index_variable",
"(",... | return an element from the array. The first request will return
the first element, the second request will return the second,
and so forth. | [
"return",
"an",
"element",
"from",
"the",
"array",
".",
"The",
"first",
"request",
"will",
"return",
"the",
"first",
"element",
"the",
"second",
"request",
"will",
"return",
"the",
"second",
"and",
"so",
"forth",
"."
] | ac0dc18b319bf3974f9a79704a7636dbf55059ae | https://github.com/cheezy/data_magic/blob/ac0dc18b319bf3974f9a79704a7636dbf55059ae/lib/data_magic/standard_translation.rb#L250-L256 | train |
matiasgagliano/action_access | lib/action_access/keeper.rb | ActionAccess.Keeper.let | def let(clearance_level, actions, resource, options = {})
clearance_level = clearance_level.to_s.singularize.to_sym
actions = Array(actions).map(&:to_sym)
controller = get_controller_name(resource, options)
@rules[controller] ||= {}
@rules[controller][clearance_level] ||= []
@rules[c... | ruby | def let(clearance_level, actions, resource, options = {})
clearance_level = clearance_level.to_s.singularize.to_sym
actions = Array(actions).map(&:to_sym)
controller = get_controller_name(resource, options)
@rules[controller] ||= {}
@rules[controller][clearance_level] ||= []
@rules[c... | [
"def",
"let",
"(",
"clearance_level",
",",
"actions",
",",
"resource",
",",
"options",
"=",
"{",
"}",
")",
"clearance_level",
"=",
"clearance_level",
".",
"to_s",
".",
"singularize",
".",
"to_sym",
"actions",
"=",
"Array",
"(",
"actions",
")",
".",
"map",
... | Set clearance to perform actions over a resource.
Clearance level and resource can be either plural or singular.
== Examples:
let :user, :show, :profile
let :user, :show, @profile
let :user, :show, ProfilesController
# Any user can can access 'profiles#show'.
let :admins, [:edit, :update], :articles... | [
"Set",
"clearance",
"to",
"perform",
"actions",
"over",
"a",
"resource",
".",
"Clearance",
"level",
"and",
"resource",
"can",
"be",
"either",
"plural",
"or",
"singular",
"."
] | aa1db07489943e2d5f281fd76257884f52de9766 | https://github.com/matiasgagliano/action_access/blob/aa1db07489943e2d5f281fd76257884f52de9766/lib/action_access/keeper.rb#L24-L33 | train |
matiasgagliano/action_access | lib/action_access/keeper.rb | ActionAccess.Keeper.lets? | def lets?(clearance_level, action, resource, options = {})
clearance_level = clearance_level.to_s.singularize.to_sym
action = action.to_sym
controller = get_controller_name(resource, options)
# Load the controller to ensure its rules are loaded (lazy loading rules).
controller.constantize... | ruby | def lets?(clearance_level, action, resource, options = {})
clearance_level = clearance_level.to_s.singularize.to_sym
action = action.to_sym
controller = get_controller_name(resource, options)
# Load the controller to ensure its rules are loaded (lazy loading rules).
controller.constantize... | [
"def",
"lets?",
"(",
"clearance_level",
",",
"action",
",",
"resource",
",",
"options",
"=",
"{",
"}",
")",
"clearance_level",
"=",
"clearance_level",
".",
"to_s",
".",
"singularize",
".",
"to_sym",
"action",
"=",
"action",
".",
"to_sym",
"controller",
"=",
... | Check if a given clearance level allows to perform an action on a resource.
Clearance level and resource can be either plural or singular.
== Examples:
lets? :users, :create, :profiles
lets? :users, :create, @profile
lets? :users, :create, ProfilesController
# True if users are allowed to access 'profil... | [
"Check",
"if",
"a",
"given",
"clearance",
"level",
"allows",
"to",
"perform",
"an",
"action",
"on",
"a",
"resource",
".",
"Clearance",
"level",
"and",
"resource",
"can",
"be",
"either",
"plural",
"or",
"singular",
"."
] | aa1db07489943e2d5f281fd76257884f52de9766 | https://github.com/matiasgagliano/action_access/blob/aa1db07489943e2d5f281fd76257884f52de9766/lib/action_access/keeper.rb#L50-L65 | train |
matiasgagliano/action_access | lib/action_access/controller_additions.rb | ActionAccess.ControllerAdditions.validate_access! | def validate_access!
action = self.action_name
clearance_levels = Array(current_clearance_levels)
authorized = clearance_levels.any? { |c| keeper.lets? c, action, self.class }
not_authorized! unless authorized
end | ruby | def validate_access!
action = self.action_name
clearance_levels = Array(current_clearance_levels)
authorized = clearance_levels.any? { |c| keeper.lets? c, action, self.class }
not_authorized! unless authorized
end | [
"def",
"validate_access!",
"action",
"=",
"self",
".",
"action_name",
"clearance_levels",
"=",
"Array",
"(",
"current_clearance_levels",
")",
"authorized",
"=",
"clearance_levels",
".",
"any?",
"{",
"|",
"c",
"|",
"keeper",
".",
"lets?",
"c",
",",
"action",
",... | Validate access to the current route. | [
"Validate",
"access",
"to",
"the",
"current",
"route",
"."
] | aa1db07489943e2d5f281fd76257884f52de9766 | https://github.com/matiasgagliano/action_access/blob/aa1db07489943e2d5f281fd76257884f52de9766/lib/action_access/controller_additions.rb#L86-L91 | train |
matiasgagliano/action_access | lib/action_access/controller_additions.rb | ActionAccess.ControllerAdditions.not_authorized! | def not_authorized!(*args)
options = args.extract_options!
message = options[:message] ||
I18n.t('action_access.redirection_message', default: 'Not authorized.')
path = options[:path] || unauthorized_access_redirection_path
redirect_to path, alert: message
end | ruby | def not_authorized!(*args)
options = args.extract_options!
message = options[:message] ||
I18n.t('action_access.redirection_message', default: 'Not authorized.')
path = options[:path] || unauthorized_access_redirection_path
redirect_to path, alert: message
end | [
"def",
"not_authorized!",
"(",
"*",
"args",
")",
"options",
"=",
"args",
".",
"extract_options!",
"message",
"=",
"options",
"[",
":message",
"]",
"||",
"I18n",
".",
"t",
"(",
"'action_access.redirection_message'",
",",
"default",
":",
"'Not authorized.'",
")",
... | Redirect if not authorized.
May be used inside action methods for finer control. | [
"Redirect",
"if",
"not",
"authorized",
".",
"May",
"be",
"used",
"inside",
"action",
"methods",
"for",
"finer",
"control",
"."
] | aa1db07489943e2d5f281fd76257884f52de9766 | https://github.com/matiasgagliano/action_access/blob/aa1db07489943e2d5f281fd76257884f52de9766/lib/action_access/controller_additions.rb#L95-L101 | train |
matiasgagliano/action_access | lib/action_access/user_utilities.rb | ActionAccess.UserUtilities.can? | def can?(action, resource, options = {})
keeper = ActionAccess::Keeper.instance
clearance_levels = Array(clearance_levels())
clearance_levels.any? { |c| keeper.lets? c, action, resource, options }
end | ruby | def can?(action, resource, options = {})
keeper = ActionAccess::Keeper.instance
clearance_levels = Array(clearance_levels())
clearance_levels.any? { |c| keeper.lets? c, action, resource, options }
end | [
"def",
"can?",
"(",
"action",
",",
"resource",
",",
"options",
"=",
"{",
"}",
")",
"keeper",
"=",
"ActionAccess",
"::",
"Keeper",
".",
"instance",
"clearance_levels",
"=",
"Array",
"(",
"clearance_levels",
"(",
")",
")",
"clearance_levels",
".",
"any?",
"{... | Check if the user is authorized to perform a given action.
Resource can be either plural or singular.
== Examples:
user.can? :show, :articles
user.can? :show, @article
user.can? :show, ArticlesController
# True if any of the user's clearance levels allows to access 'articles#show'
user.can? :edit, :... | [
"Check",
"if",
"the",
"user",
"is",
"authorized",
"to",
"perform",
"a",
"given",
"action",
".",
"Resource",
"can",
"be",
"either",
"plural",
"or",
"singular",
"."
] | aa1db07489943e2d5f281fd76257884f52de9766 | https://github.com/matiasgagliano/action_access/blob/aa1db07489943e2d5f281fd76257884f52de9766/lib/action_access/user_utilities.rb#L18-L22 | train |
ssut/telegram-rb | lib/telegram/models.rb | Telegram.TelegramBase.send_image | def send_image(path, refer, &callback)
if @type == 'encr_chat'
logger.warn("Currently telegram-cli has a bug with send_typing, then prevent this for safety")
return
end
fail_back(&callback) if not File.exist?(path)
@client.send_photo(targetize, path, &callback)
end | ruby | def send_image(path, refer, &callback)
if @type == 'encr_chat'
logger.warn("Currently telegram-cli has a bug with send_typing, then prevent this for safety")
return
end
fail_back(&callback) if not File.exist?(path)
@client.send_photo(targetize, path, &callback)
end | [
"def",
"send_image",
"(",
"path",
",",
"refer",
",",
"&",
"callback",
")",
"if",
"@type",
"==",
"'encr_chat'",
"logger",
".",
"warn",
"(",
"\"Currently telegram-cli has a bug with send_typing, then prevent this for safety\"",
")",
"return",
"end",
"fail_back",
"(",
"&... | Send an image
@param [String] path The absoulte path of the image you want to send
@param [TelegramMessage] refer referral of the method call
@param [Block] callback Callback block that will be called when finished
@since [0.1.1] | [
"Send",
"an",
"image"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/models.rb#L93-L100 | train |
ssut/telegram-rb | lib/telegram/models.rb | Telegram.TelegramBase.send_image_url | def send_image_url(url, opt, refer, &callback)
begin
opt = {} if opt.nil?
http = EM::HttpRequest.new(url, :connect_timeout => 2, :inactivity_timeout => 5).get opt
file = Tempfile.new(['image', 'jpg'])
http.stream { |chunk|
file.write(chunk)
}
http.callback... | ruby | def send_image_url(url, opt, refer, &callback)
begin
opt = {} if opt.nil?
http = EM::HttpRequest.new(url, :connect_timeout => 2, :inactivity_timeout => 5).get opt
file = Tempfile.new(['image', 'jpg'])
http.stream { |chunk|
file.write(chunk)
}
http.callback... | [
"def",
"send_image_url",
"(",
"url",
",",
"opt",
",",
"refer",
",",
"&",
"callback",
")",
"begin",
"opt",
"=",
"{",
"}",
"if",
"opt",
".",
"nil?",
"http",
"=",
"EM",
"::",
"HttpRequest",
".",
"new",
"(",
"url",
",",
":connect_timeout",
"=>",
"2",
"... | Send an image with given url, not implemen
@param [String] url The URL of the image you want to send
@param [TelegramMessage] refer referral of the method call
@param [Block] callback Callback block that will be called when finished
@since [0.1.1] | [
"Send",
"an",
"image",
"with",
"given",
"url",
"not",
"implemen"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/models.rb#L108-L129 | train |
ssut/telegram-rb | lib/telegram/models.rb | Telegram.TelegramBase.send_video | def send_video(path, refer, &callback)
fail_back(&callback) if not File.exist?(path)
@client.send_video(targetize, path, &callback)
end | ruby | def send_video(path, refer, &callback)
fail_back(&callback) if not File.exist?(path)
@client.send_video(targetize, path, &callback)
end | [
"def",
"send_video",
"(",
"path",
",",
"refer",
",",
"&",
"callback",
")",
"fail_back",
"(",
"&",
"callback",
")",
"if",
"not",
"File",
".",
"exist?",
"(",
"path",
")",
"@client",
".",
"send_video",
"(",
"targetize",
",",
"path",
",",
"&",
"callback",
... | Send a video
@param [String] path The absoulte path of the video you want to send
@param [TelegramMessage] refer referral of the method call
@param [Block] callback Callback block that will be called when finished
@since [0.1.1] | [
"Send",
"a",
"video"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/models.rb#L137-L140 | train |
ssut/telegram-rb | lib/telegram/models.rb | Telegram.TelegramMessage.reply | def reply(type, content, target=nil, &callback)
target = @target if target.nil?
case type
when :text
target.send_message(content, self, &callback)
when :image
option = nil
content, option = content if content.class == Array
if content.include?('http')
t... | ruby | def reply(type, content, target=nil, &callback)
target = @target if target.nil?
case type
when :text
target.send_message(content, self, &callback)
when :image
option = nil
content, option = content if content.class == Array
if content.include?('http')
t... | [
"def",
"reply",
"(",
"type",
",",
"content",
",",
"target",
"=",
"nil",
",",
"&",
"callback",
")",
"target",
"=",
"@target",
"if",
"target",
".",
"nil?",
"case",
"type",
"when",
":text",
"target",
".",
"send_message",
"(",
"content",
",",
"self",
",",
... | Reply a message to the chat
@param [Symbol] type Type of the message (either of :text, :sticker, :image)
@param [String] content Content to send a message
@param [TelegramChat] target Specify a TelegramChat to send
@param [TelegramContact] target Specify a TelegramContact to send
@param [Block] callback Callback ... | [
"Reply",
"a",
"message",
"to",
"the",
"chat"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/models.rb#L334-L351 | train |
ssut/telegram-rb | lib/telegram/api.rb | Telegram.API.update! | def update!(&cb)
done = false
EM.synchrony do
multi = EM::Synchrony::Multi.new
multi.add :profile, update_profile!
multi.add :contacts, update_contacts!
multi.add :chats, update_chats!
multi.perform
done = true
end
check_done = Proc.new {
... | ruby | def update!(&cb)
done = false
EM.synchrony do
multi = EM::Synchrony::Multi.new
multi.add :profile, update_profile!
multi.add :contacts, update_contacts!
multi.add :chats, update_chats!
multi.perform
done = true
end
check_done = Proc.new {
... | [
"def",
"update!",
"(",
"&",
"cb",
")",
"done",
"=",
"false",
"EM",
".",
"synchrony",
"do",
"multi",
"=",
"EM",
"::",
"Synchrony",
"::",
"Multi",
".",
"new",
"multi",
".",
"add",
":profile",
",",
"update_profile!",
"multi",
".",
"add",
":contacts",
",",... | Update user profile, contacts and chats
@api private | [
"Update",
"user",
"profile",
"contacts",
"and",
"chats"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/api.rb#L11-L32 | train |
ssut/telegram-rb | lib/telegram/api.rb | Telegram.API.update_profile! | def update_profile!
assert!
callback = Callback.new
@profile = nil
@connection.communicate('get_self') do |success, data|
if success
callback.trigger(:success)
contact = TelegramContact.pick_or_new(self, data)
@contacts << contact unless self.contacts.includ... | ruby | def update_profile!
assert!
callback = Callback.new
@profile = nil
@connection.communicate('get_self') do |success, data|
if success
callback.trigger(:success)
contact = TelegramContact.pick_or_new(self, data)
@contacts << contact unless self.contacts.includ... | [
"def",
"update_profile!",
"assert!",
"callback",
"=",
"Callback",
".",
"new",
"@profile",
"=",
"nil",
"@connection",
".",
"communicate",
"(",
"'get_self'",
")",
"do",
"|",
"success",
",",
"data",
"|",
"if",
"success",
"callback",
".",
"trigger",
"(",
":succe... | Update user profile
@api private | [
"Update",
"user",
"profile"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/api.rb#L37-L52 | train |
ssut/telegram-rb | lib/telegram/api.rb | Telegram.API.update_contacts! | def update_contacts!
assert!
callback = Callback.new
@contacts = []
@connection.communicate('contact_list') do |success, data|
if success and data.class == Array
callback.trigger(:success)
data.each { |contact|
contact = TelegramContact.pick_or_new(self, c... | ruby | def update_contacts!
assert!
callback = Callback.new
@contacts = []
@connection.communicate('contact_list') do |success, data|
if success and data.class == Array
callback.trigger(:success)
data.each { |contact|
contact = TelegramContact.pick_or_new(self, c... | [
"def",
"update_contacts!",
"assert!",
"callback",
"=",
"Callback",
".",
"new",
"@contacts",
"=",
"[",
"]",
"@connection",
".",
"communicate",
"(",
"'contact_list'",
")",
"do",
"|",
"success",
",",
"data",
"|",
"if",
"success",
"and",
"data",
".",
"class",
... | Update user contacts
@api private | [
"Update",
"user",
"contacts"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/api.rb#L57-L73 | train |
ssut/telegram-rb | lib/telegram/api.rb | Telegram.API.update_chats! | def update_chats!
assert!
callback = Callback.new
collected = 0
collect_done = Proc.new do |id, data, count|
collected += 1
@chats << TelegramChat.new(self, data)
callback.trigger(:success) if collected == count
end
collect = Proc.new do |id, count|
... | ruby | def update_chats!
assert!
callback = Callback.new
collected = 0
collect_done = Proc.new do |id, data, count|
collected += 1
@chats << TelegramChat.new(self, data)
callback.trigger(:success) if collected == count
end
collect = Proc.new do |id, count|
... | [
"def",
"update_chats!",
"assert!",
"callback",
"=",
"Callback",
".",
"new",
"collected",
"=",
"0",
"collect_done",
"=",
"Proc",
".",
"new",
"do",
"|",
"id",
",",
"data",
",",
"count",
"|",
"collected",
"+=",
"1",
"@chats",
"<<",
"TelegramChat",
".",
"new... | Update user chats
@api private | [
"Update",
"user",
"chats"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/api.rb#L78-L111 | train |
ssut/telegram-rb | lib/telegram/api.rb | Telegram.API.send_contact | def send_contact(peer, phone, first_name, last_name)
assert!
@connection.communicate(['send_contact', peer, phone, first_name, last_name])
end | ruby | def send_contact(peer, phone, first_name, last_name)
assert!
@connection.communicate(['send_contact', peer, phone, first_name, last_name])
end | [
"def",
"send_contact",
"(",
"peer",
",",
"phone",
",",
"first_name",
",",
"last_name",
")",
"assert!",
"@connection",
".",
"communicate",
"(",
"[",
"'send_contact'",
",",
"peer",
",",
"phone",
",",
"first_name",
",",
"last_name",
"]",
")",
"end"
] | Send contact to peer chat
@param [String] peer Target chat to which contact will be send
@param [String] contact phone number
@param [String] contact first name
@param [String] contact last name
@example
telegram.send_contact('chat#1234567', '9329232332', 'Foo', 'Bar') | [
"Send",
"contact",
"to",
"peer",
"chat"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/api.rb#L202-L205 | train |
ssut/telegram-rb | lib/telegram/api.rb | Telegram.API.download_attachment | def download_attachment(type, seq, &callback)
assert!
raise "Type mismatch" unless %w(photo video audio).include?(type)
@connection.communicate(["load_#{type.to_s}", seq], &callback)
end | ruby | def download_attachment(type, seq, &callback)
assert!
raise "Type mismatch" unless %w(photo video audio).include?(type)
@connection.communicate(["load_#{type.to_s}", seq], &callback)
end | [
"def",
"download_attachment",
"(",
"type",
",",
"seq",
",",
"&",
"callback",
")",
"assert!",
"raise",
"\"Type mismatch\"",
"unless",
"%w(",
"photo",
"video",
"audio",
")",
".",
"include?",
"(",
"type",
")",
"@connection",
".",
"communicate",
"(",
"[",
"\"loa... | Download an attachment from a message
@param [type] type The type of an attachment (:photo, :video, :audio)
@param [String] seq Message sequence number
@param [Block] callback Callback block that will be called when finished
@yieldparam [Bool] success The result of the request (true or false)
@yieldparam [Hash] d... | [
"Download",
"an",
"attachment",
"from",
"a",
"message"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/api.rb#L305-L309 | train |
ssut/telegram-rb | lib/telegram/events.rb | Telegram.Event.format_message | def format_message
message = Message.new
message.id = @id
message.text = @raw_data['text'] ||= ''
media = @raw_data['media']
message.type = media ? media['type'] : 'text'
message.raw_from = @raw_data['from']['peer_id']
message.from_type = @raw_data['from']['peer_type']
m... | ruby | def format_message
message = Message.new
message.id = @id
message.text = @raw_data['text'] ||= ''
media = @raw_data['media']
message.type = media ? media['type'] : 'text'
message.raw_from = @raw_data['from']['peer_id']
message.from_type = @raw_data['from']['peer_type']
m... | [
"def",
"format_message",
"message",
"=",
"Message",
".",
"new",
"message",
".",
"id",
"=",
"@id",
"message",
".",
"text",
"=",
"@raw_data",
"[",
"'text'",
"]",
"||=",
"''",
"media",
"=",
"@raw_data",
"[",
"'media'",
"]",
"message",
".",
"type",
"=",
"m... | Process raw data in which event type is message given.
@return [void]
@api private | [
"Process",
"raw",
"data",
"in",
"which",
"event",
"type",
"is",
"message",
"given",
"."
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/events.rb#L161-L206 | train |
ssut/telegram-rb | lib/telegram/connection.rb | Telegram.Connection.communicate | def communicate(*messages, &callback)
@available = false
@data = ''
@callback = callback
messages = messages.first if messages.size == 1 and messages.first.is_a?(Array)
messages = messages.join(' ') << "\n"
send_data(messages)
end | ruby | def communicate(*messages, &callback)
@available = false
@data = ''
@callback = callback
messages = messages.first if messages.size == 1 and messages.first.is_a?(Array)
messages = messages.join(' ') << "\n"
send_data(messages)
end | [
"def",
"communicate",
"(",
"*",
"messages",
",",
"&",
"callback",
")",
"@available",
"=",
"false",
"@data",
"=",
"''",
"@callback",
"=",
"callback",
"messages",
"=",
"messages",
".",
"first",
"if",
"messages",
".",
"size",
"==",
"1",
"and",
"messages",
"... | Communicate telegram-rb with telegram-cli connection
@param [Array<String>] messages Messages that will be sent
@yieldparam [Block] callback Callback block that will be called when finished | [
"Communicate",
"telegram",
"-",
"rb",
"with",
"telegram",
"-",
"cli",
"connection"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/connection.rb#L31-L38 | train |
ssut/telegram-rb | lib/telegram/connection.rb | Telegram.Connection.receive_data | def receive_data(data)
@data << data
return unless data.index("\n\n")
begin
result = _receive_data(@data)
rescue
raise
result = nil
end
@callback.call(!result.nil?, result) unless @callback.nil?
@callback = nil
@available = true
end | ruby | def receive_data(data)
@data << data
return unless data.index("\n\n")
begin
result = _receive_data(@data)
rescue
raise
result = nil
end
@callback.call(!result.nil?, result) unless @callback.nil?
@callback = nil
@available = true
end | [
"def",
"receive_data",
"(",
"data",
")",
"@data",
"<<",
"data",
"return",
"unless",
"data",
".",
"index",
"(",
"\"\\n\\n\"",
")",
"begin",
"result",
"=",
"_receive_data",
"(",
"@data",
")",
"rescue",
"raise",
"result",
"=",
"nil",
"end",
"@callback",
".",
... | This method will be called by EventMachine when data arrived
then parse given data and execute callback method if exists
@api private | [
"This",
"method",
"will",
"be",
"called",
"by",
"EventMachine",
"when",
"data",
"arrived",
"then",
"parse",
"given",
"data",
"and",
"execute",
"callback",
"method",
"if",
"exists"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/connection.rb#L80-L93 | train |
ssut/telegram-rb | lib/telegram/connection_pool.rb | Telegram.ConnectionPool.acquire | def acquire(&callback)
acq = Proc.new {
conn = self.find { |conn| conn.available? }
if not conn.nil? and conn.connected?
callback.call(conn)
else
logger.warn("Failed to acquire available connection, retry after 0.1 second")
EM.add_timer(0.1, &acq)
end
... | ruby | def acquire(&callback)
acq = Proc.new {
conn = self.find { |conn| conn.available? }
if not conn.nil? and conn.connected?
callback.call(conn)
else
logger.warn("Failed to acquire available connection, retry after 0.1 second")
EM.add_timer(0.1, &acq)
end
... | [
"def",
"acquire",
"(",
"&",
"callback",
")",
"acq",
"=",
"Proc",
".",
"new",
"{",
"conn",
"=",
"self",
".",
"find",
"{",
"|",
"conn",
"|",
"conn",
".",
"available?",
"}",
"if",
"not",
"conn",
".",
"nil?",
"and",
"conn",
".",
"connected?",
"callback... | Acquire available connection
@see Connection
@param [Block] callback This block will be called when successfully acquired a connection
@yieldparam [Connection] connection acquired connection | [
"Acquire",
"available",
"connection"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/connection_pool.rb#L43-L54 | train |
ssut/telegram-rb | lib/telegram/client.rb | Telegram.Client.execute | def execute
cli_arguments = Telegram::CLIArguments.new(@config)
command = "'#{@config.daemon}' #{cli_arguments.to_s}"
@stdout = IO.popen(command, 'a+')
initialize_stdout_reading
end | ruby | def execute
cli_arguments = Telegram::CLIArguments.new(@config)
command = "'#{@config.daemon}' #{cli_arguments.to_s}"
@stdout = IO.popen(command, 'a+')
initialize_stdout_reading
end | [
"def",
"execute",
"cli_arguments",
"=",
"Telegram",
"::",
"CLIArguments",
".",
"new",
"(",
"@config",
")",
"command",
"=",
"\"'#{@config.daemon}' #{cli_arguments.to_s}\"",
"@stdout",
"=",
"IO",
".",
"popen",
"(",
"command",
",",
"'a+'",
")",
"initialize_stdout_readi... | Initialize Telegram Client
@yieldparam [Block] block
@yield [config] Given configuration struct to the block
Execute telegram-cli daemon and wait for the response
@api private | [
"Initialize",
"Telegram",
"Client"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/client.rb#L82-L87 | train |
ssut/telegram-rb | lib/telegram/client.rb | Telegram.Client.poll | def poll
logger.info("Start polling for events")
while (data = @stdout.gets)
begin
brace = data.index('{')
data = data[brace..-2]
data = Oj.load(data, mode: :compat)
@events << data
rescue
end
end
end | ruby | def poll
logger.info("Start polling for events")
while (data = @stdout.gets)
begin
brace = data.index('{')
data = data[brace..-2]
data = Oj.load(data, mode: :compat)
@events << data
rescue
end
end
end | [
"def",
"poll",
"logger",
".",
"info",
"(",
"\"Start polling for events\"",
")",
"while",
"(",
"data",
"=",
"@stdout",
".",
"gets",
")",
"begin",
"brace",
"=",
"data",
".",
"index",
"(",
"'{'",
")",
"data",
"=",
"data",
"[",
"brace",
"..",
"-",
"2",
"... | Do the long-polling from stdout of the telegram-cli
@api private | [
"Do",
"the",
"long",
"-",
"polling",
"from",
"stdout",
"of",
"the",
"telegram",
"-",
"cli"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/client.rb#L92-L103 | train |
ssut/telegram-rb | lib/telegram/client.rb | Telegram.Client.connect | def connect(&block)
logger.info("Trying to start telegram-cli and then connect")
@connect_callback = block
process_data
EM.defer(method(:execute), method(:create_pool), method(:execution_failed))
end | ruby | def connect(&block)
logger.info("Trying to start telegram-cli and then connect")
@connect_callback = block
process_data
EM.defer(method(:execute), method(:create_pool), method(:execution_failed))
end | [
"def",
"connect",
"(",
"&",
"block",
")",
"logger",
".",
"info",
"(",
"\"Trying to start telegram-cli and then connect\"",
")",
"@connect_callback",
"=",
"block",
"process_data",
"EM",
".",
"defer",
"(",
"method",
"(",
":execute",
")",
",",
"method",
"(",
":crea... | Start telegram-cli daemon
@yield This block will be executed when all connections have responded | [
"Start",
"telegram",
"-",
"cli",
"daemon"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/client.rb#L144-L149 | train |
bpot/poseidon | lib/poseidon/message_set.rb | Poseidon.MessageSet.flatten | def flatten
messages = struct.messages.map do |message|
if message.compressed?
s = message.decompressed_value
MessageSet.read_without_size(Protocol::ResponseBuffer.new(s)).flatten
else
message
end
end.flatten
end | ruby | def flatten
messages = struct.messages.map do |message|
if message.compressed?
s = message.decompressed_value
MessageSet.read_without_size(Protocol::ResponseBuffer.new(s)).flatten
else
message
end
end.flatten
end | [
"def",
"flatten",
"messages",
"=",
"struct",
".",
"messages",
".",
"map",
"do",
"|",
"message",
"|",
"if",
"message",
".",
"compressed?",
"s",
"=",
"message",
".",
"decompressed_value",
"MessageSet",
".",
"read_without_size",
"(",
"Protocol",
"::",
"ResponseBu... | Builds an array of Message objects from the MessageStruct objects.
Decompressing messages if necessary.
@return [Array<Message>] | [
"Builds",
"an",
"array",
"of",
"Message",
"objects",
"from",
"the",
"MessageStruct",
"objects",
".",
"Decompressing",
"messages",
"if",
"necessary",
"."
] | bfbf084ea21af2a31350ad5f58d8ef5dc30b948e | https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/message_set.rb#L59-L68 | train |
bpot/poseidon | lib/poseidon/messages_for_broker.rb | Poseidon.MessagesForBroker.add | def add(message, partition_id)
@messages << message
@topics[message.topic] ||= {}
@topics[message.topic][partition_id] ||= []
@topics[message.topic][partition_id] << message
end | ruby | def add(message, partition_id)
@messages << message
@topics[message.topic] ||= {}
@topics[message.topic][partition_id] ||= []
@topics[message.topic][partition_id] << message
end | [
"def",
"add",
"(",
"message",
",",
"partition_id",
")",
"@messages",
"<<",
"message",
"@topics",
"[",
"message",
".",
"topic",
"]",
"||=",
"{",
"}",
"@topics",
"[",
"message",
".",
"topic",
"]",
"[",
"partition_id",
"]",
"||=",
"[",
"]",
"@topics",
"["... | Add a messages for this broker | [
"Add",
"a",
"messages",
"for",
"this",
"broker"
] | bfbf084ea21af2a31350ad5f58d8ef5dc30b948e | https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/messages_for_broker.rb#L14-L20 | train |
bpot/poseidon | lib/poseidon/messages_for_broker.rb | Poseidon.MessagesForBroker.build_protocol_objects | def build_protocol_objects(compression_config)
@topics.map do |topic, messages_by_partition|
codec = compression_config.compression_codec_for_topic(topic)
messages_for_partitions = messages_by_partition.map do |partition, messages|
message_set = MessageSet.new(messages)
if cod... | ruby | def build_protocol_objects(compression_config)
@topics.map do |topic, messages_by_partition|
codec = compression_config.compression_codec_for_topic(topic)
messages_for_partitions = messages_by_partition.map do |partition, messages|
message_set = MessageSet.new(messages)
if cod... | [
"def",
"build_protocol_objects",
"(",
"compression_config",
")",
"@topics",
".",
"map",
"do",
"|",
"topic",
",",
"messages_by_partition",
"|",
"codec",
"=",
"compression_config",
".",
"compression_codec_for_topic",
"(",
"topic",
")",
"messages_for_partitions",
"=",
"m... | Build protocol objects for this broker! | [
"Build",
"protocol",
"objects",
"for",
"this",
"broker!"
] | bfbf084ea21af2a31350ad5f58d8ef5dc30b948e | https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/messages_for_broker.rb#L23-L37 | train |
bpot/poseidon | lib/poseidon/messages_to_send_batch.rb | Poseidon.MessagesToSendBatch.messages_for_brokers | def messages_for_brokers
messages_for_broker_ids = {}
@messages.each do |message|
partition_id, broker_id = @message_conductor.destination(message.topic,
message.key)
# Create a nested hash to group messages by broker_id, topi... | ruby | def messages_for_brokers
messages_for_broker_ids = {}
@messages.each do |message|
partition_id, broker_id = @message_conductor.destination(message.topic,
message.key)
# Create a nested hash to group messages by broker_id, topi... | [
"def",
"messages_for_brokers",
"messages_for_broker_ids",
"=",
"{",
"}",
"@messages",
".",
"each",
"do",
"|",
"message",
"|",
"partition_id",
",",
"broker_id",
"=",
"@message_conductor",
".",
"destination",
"(",
"message",
".",
"topic",
",",
"message",
".",
"key... | Groups messages by broker and preps them for transmission.
@return [Array<MessagesForBroker>] | [
"Groups",
"messages",
"by",
"broker",
"and",
"preps",
"them",
"for",
"transmission",
"."
] | bfbf084ea21af2a31350ad5f58d8ef5dc30b948e | https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/messages_to_send_batch.rb#L13-L25 | train |
bpot/poseidon | lib/poseidon/connection.rb | Poseidon.Connection.produce | def produce(required_acks, timeout, messages_for_topics)
ensure_connected
req = ProduceRequest.new( request_common(:produce),
required_acks,
timeout,
messages_for_topics)
send_request(req)
if require... | ruby | def produce(required_acks, timeout, messages_for_topics)
ensure_connected
req = ProduceRequest.new( request_common(:produce),
required_acks,
timeout,
messages_for_topics)
send_request(req)
if require... | [
"def",
"produce",
"(",
"required_acks",
",",
"timeout",
",",
"messages_for_topics",
")",
"ensure_connected",
"req",
"=",
"ProduceRequest",
".",
"new",
"(",
"request_common",
"(",
":produce",
")",
",",
"required_acks",
",",
"timeout",
",",
"messages_for_topics",
")... | Execute a produce call
@param [Integer] required_acks
@param [Integer] timeout
@param [Array<Protocol::MessagesForTopics>] messages_for_topics Messages to send
@return [ProduceResponse] | [
"Execute",
"a",
"produce",
"call"
] | bfbf084ea21af2a31350ad5f58d8ef5dc30b948e | https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/connection.rb#L49-L61 | train |
bpot/poseidon | lib/poseidon/connection.rb | Poseidon.Connection.fetch | def fetch(max_wait_time, min_bytes, topic_fetches)
ensure_connected
req = FetchRequest.new( request_common(:fetch),
REPLICA_ID,
max_wait_time,
min_bytes,
topic_fetches)
send... | ruby | def fetch(max_wait_time, min_bytes, topic_fetches)
ensure_connected
req = FetchRequest.new( request_common(:fetch),
REPLICA_ID,
max_wait_time,
min_bytes,
topic_fetches)
send... | [
"def",
"fetch",
"(",
"max_wait_time",
",",
"min_bytes",
",",
"topic_fetches",
")",
"ensure_connected",
"req",
"=",
"FetchRequest",
".",
"new",
"(",
"request_common",
"(",
":fetch",
")",
",",
"REPLICA_ID",
",",
"max_wait_time",
",",
"min_bytes",
",",
"topic_fetch... | Execute a fetch call
@param [Integer] max_wait_time
@param [Integer] min_bytes
@param [Integer] topic_fetches | [
"Execute",
"a",
"fetch",
"call"
] | bfbf084ea21af2a31350ad5f58d8ef5dc30b948e | https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/connection.rb#L68-L77 | train |
bpot/poseidon | lib/poseidon/connection.rb | Poseidon.Connection.topic_metadata | def topic_metadata(topic_names)
ensure_connected
req = MetadataRequest.new( request_common(:metadata),
topic_names)
send_request(req)
read_response(MetadataResponse)
end | ruby | def topic_metadata(topic_names)
ensure_connected
req = MetadataRequest.new( request_common(:metadata),
topic_names)
send_request(req)
read_response(MetadataResponse)
end | [
"def",
"topic_metadata",
"(",
"topic_names",
")",
"ensure_connected",
"req",
"=",
"MetadataRequest",
".",
"new",
"(",
"request_common",
"(",
":metadata",
")",
",",
"topic_names",
")",
"send_request",
"(",
"req",
")",
"read_response",
"(",
"MetadataResponse",
")",
... | Fetch metadata for +topic_names+
@param [Enumberable<String>] topic_names
A list of topics to retrive metadata for
@return [TopicMetadataResponse] metadata for the topics | [
"Fetch",
"metadata",
"for",
"+",
"topic_names",
"+"
] | bfbf084ea21af2a31350ad5f58d8ef5dc30b948e | https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/connection.rb#L93-L99 | train |
bpot/poseidon | lib/poseidon/cluster_metadata.rb | Poseidon.ClusterMetadata.update | def update(topic_metadata_response)
update_brokers(topic_metadata_response.brokers)
update_topics(topic_metadata_response.topics)
@last_refreshed_at = Time.now
nil
end | ruby | def update(topic_metadata_response)
update_brokers(topic_metadata_response.brokers)
update_topics(topic_metadata_response.topics)
@last_refreshed_at = Time.now
nil
end | [
"def",
"update",
"(",
"topic_metadata_response",
")",
"update_brokers",
"(",
"topic_metadata_response",
".",
"brokers",
")",
"update_topics",
"(",
"topic_metadata_response",
".",
"topics",
")",
"@last_refreshed_at",
"=",
"Time",
".",
"now",
"nil",
"end"
] | Update what we know about the cluter based on MetadataResponse
@param [MetadataResponse] topic_metadata_response
@return nil | [
"Update",
"what",
"we",
"know",
"about",
"the",
"cluter",
"based",
"on",
"MetadataResponse"
] | bfbf084ea21af2a31350ad5f58d8ef5dc30b948e | https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/cluster_metadata.rb#L18-L24 | train |
bpot/poseidon | lib/poseidon/message_conductor.rb | Poseidon.MessageConductor.destination | def destination(topic, key = nil)
topic_metadata = topic_metadatas[topic]
if topic_metadata && topic_metadata.leader_available?
partition_id = determine_partition(topic_metadata, key)
broker_id = topic_metadata.partition_leader(partition_id) || NO_BROKER
else
partition_id =... | ruby | def destination(topic, key = nil)
topic_metadata = topic_metadatas[topic]
if topic_metadata && topic_metadata.leader_available?
partition_id = determine_partition(topic_metadata, key)
broker_id = topic_metadata.partition_leader(partition_id) || NO_BROKER
else
partition_id =... | [
"def",
"destination",
"(",
"topic",
",",
"key",
"=",
"nil",
")",
"topic_metadata",
"=",
"topic_metadatas",
"[",
"topic",
"]",
"if",
"topic_metadata",
"&&",
"topic_metadata",
".",
"leader_available?",
"partition_id",
"=",
"determine_partition",
"(",
"topic_metadata",... | Create a new message conductor
@param [Hash<String,TopicMetadata>] topics_metadata
Metadata for all topics this conductor may receive.
@param [Object] partitioner
Custom partitioner
Determines which partition a message should be sent to.
@param [String] topic
Topic we are sending this message to
@param... | [
"Create",
"a",
"new",
"message",
"conductor"
] | bfbf084ea21af2a31350ad5f58d8ef5dc30b948e | https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/message_conductor.rb#L30-L41 | train |
bpot/poseidon | lib/poseidon/partition_consumer.rb | Poseidon.PartitionConsumer.fetch | def fetch(options = {})
fetch_max_wait = options.delete(:max_wait_ms) || max_wait_ms
fetch_max_bytes = options.delete(:max_bytes) || max_bytes
fetch_min_bytes = options.delete(:min_bytes) || min_bytes
if options.keys.any?
raise ArgumentError, "Unknown options: #{options.keys.inspect}"
... | ruby | def fetch(options = {})
fetch_max_wait = options.delete(:max_wait_ms) || max_wait_ms
fetch_max_bytes = options.delete(:max_bytes) || max_bytes
fetch_min_bytes = options.delete(:min_bytes) || min_bytes
if options.keys.any?
raise ArgumentError, "Unknown options: #{options.keys.inspect}"
... | [
"def",
"fetch",
"(",
"options",
"=",
"{",
"}",
")",
"fetch_max_wait",
"=",
"options",
".",
"delete",
"(",
":max_wait_ms",
")",
"||",
"max_wait_ms",
"fetch_max_bytes",
"=",
"options",
".",
"delete",
"(",
":max_bytes",
")",
"||",
"max_bytes",
"fetch_min_bytes",
... | Create a new consumer which reads the specified topic and partition from
the host.
@param [String] client_id Used to identify this client should be unique.
@param [String] host
@param [Integer] port
@param [String] topic Topic to read from
@param [Integer] partition Partitions are zero indexed.
@param [Integer... | [
"Create",
"a",
"new",
"consumer",
"which",
"reads",
"the",
"specified",
"topic",
"and",
"partition",
"from",
"the",
"host",
"."
] | bfbf084ea21af2a31350ad5f58d8ef5dc30b948e | https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/partition_consumer.rb#L100-L132 | train |
bpot/poseidon | lib/poseidon/producer.rb | Poseidon.Producer.send_messages | def send_messages(messages)
raise Errors::ProducerShutdownError if @shutdown
if !messages.respond_to?(:each)
raise ArgumentError, "messages must respond to #each"
end
@producer.send_messages(convert_to_messages_objects(messages))
end | ruby | def send_messages(messages)
raise Errors::ProducerShutdownError if @shutdown
if !messages.respond_to?(:each)
raise ArgumentError, "messages must respond to #each"
end
@producer.send_messages(convert_to_messages_objects(messages))
end | [
"def",
"send_messages",
"(",
"messages",
")",
"raise",
"Errors",
"::",
"ProducerShutdownError",
"if",
"@shutdown",
"if",
"!",
"messages",
".",
"respond_to?",
"(",
":each",
")",
"raise",
"ArgumentError",
",",
"\"messages must respond to #each\"",
"end",
"@producer",
... | Returns a new Producer.
@param [Array<String>] brokers An array of brokers in the form "host1:port1"
@param [String] client_id A client_id used to indentify the producer.
@param [Hash] options
@option options [:sync / :async] :type (:sync)
Whether we should send messages right away or queue them and send
... | [
"Returns",
"a",
"new",
"Producer",
"."
] | bfbf084ea21af2a31350ad5f58d8ef5dc30b948e | https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/producer.rb#L157-L164 | train |
piotrmurach/tty-screen | lib/tty/screen.rb | TTY.Screen.size | def size
size = size_from_java
size ||= size_from_win_api
size ||= size_from_ioctl
size ||= size_from_io_console
size ||= size_from_readline
size ||= size_from_tput
size ||= size_from_stty
size ||= size_from_env
size ||= size_from_ansicon
size || DEFAULT_SIZE... | ruby | def size
size = size_from_java
size ||= size_from_win_api
size ||= size_from_ioctl
size ||= size_from_io_console
size ||= size_from_readline
size ||= size_from_tput
size ||= size_from_stty
size ||= size_from_env
size ||= size_from_ansicon
size || DEFAULT_SIZE... | [
"def",
"size",
"size",
"=",
"size_from_java",
"size",
"||=",
"size_from_win_api",
"size",
"||=",
"size_from_ioctl",
"size",
"||=",
"size_from_io_console",
"size",
"||=",
"size_from_readline",
"size",
"||=",
"size_from_tput",
"size",
"||=",
"size_from_stty",
"size",
"|... | Get terminal rows and columns
@return [Array[Integer, Integer]]
return rows & columns
@api public | [
"Get",
"terminal",
"rows",
"and",
"columns"
] | 282ae528974059c16090212dbcfb4a3d5aa3bbeb | https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L39-L50 | train |
piotrmurach/tty-screen | lib/tty/screen.rb | TTY.Screen.size_from_win_api | def size_from_win_api(verbose: nil)
require 'fiddle'
kernel32 = Fiddle::Handle.new('kernel32')
get_std_handle = Fiddle::Function.new(kernel32['GetStdHandle'],
[-Fiddle::TYPE_INT], Fiddle::TYPE_INT)
get_console_buffer_info = Fiddle::Function.new(
kernel32['GetCons... | ruby | def size_from_win_api(verbose: nil)
require 'fiddle'
kernel32 = Fiddle::Handle.new('kernel32')
get_std_handle = Fiddle::Function.new(kernel32['GetStdHandle'],
[-Fiddle::TYPE_INT], Fiddle::TYPE_INT)
get_console_buffer_info = Fiddle::Function.new(
kernel32['GetCons... | [
"def",
"size_from_win_api",
"(",
"verbose",
":",
"nil",
")",
"require",
"'fiddle'",
"kernel32",
"=",
"Fiddle",
"::",
"Handle",
".",
"new",
"(",
"'kernel32'",
")",
"get_std_handle",
"=",
"Fiddle",
"::",
"Function",
".",
"new",
"(",
"kernel32",
"[",
"'GetStdHa... | Determine terminal size with a Windows native API
@return [nil, Array[Integer, Integer]]
@api private | [
"Determine",
"terminal",
"size",
"with",
"a",
"Windows",
"native",
"API"
] | 282ae528974059c16090212dbcfb4a3d5aa3bbeb | https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L80-L102 | train |
piotrmurach/tty-screen | lib/tty/screen.rb | TTY.Screen.size_from_java | def size_from_java(verbose: nil)
return unless jruby?
require 'java'
java_import 'jline.TerminalFactory'
terminal = TerminalFactory.get
size = [terminal.get_height, terminal.get_width]
return size if nonzero_column?(size[1])
rescue
warn 'failed to import java terminal packa... | ruby | def size_from_java(verbose: nil)
return unless jruby?
require 'java'
java_import 'jline.TerminalFactory'
terminal = TerminalFactory.get
size = [terminal.get_height, terminal.get_width]
return size if nonzero_column?(size[1])
rescue
warn 'failed to import java terminal packa... | [
"def",
"size_from_java",
"(",
"verbose",
":",
"nil",
")",
"return",
"unless",
"jruby?",
"require",
"'java'",
"java_import",
"'jline.TerminalFactory'",
"terminal",
"=",
"TerminalFactory",
".",
"get",
"size",
"=",
"[",
"terminal",
".",
"get_height",
",",
"terminal",... | Determine terminal size on jruby using native Java libs
@return [nil, Array[Integer, Integer]]
@api private | [
"Determine",
"terminal",
"size",
"on",
"jruby",
"using",
"native",
"Java",
"libs"
] | 282ae528974059c16090212dbcfb4a3d5aa3bbeb | https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L110-L119 | train |
piotrmurach/tty-screen | lib/tty/screen.rb | TTY.Screen.size_from_ioctl | def size_from_ioctl
return if jruby?
return unless @output.respond_to?(:ioctl)
format = 'SSSS'
buffer = ([0] * format.size).pack(format)
if ioctl?(TIOCGWINSZ, buffer) || ioctl?(TIOCGWINSZ_PPC, buffer)
rows, cols, = buffer.unpack(format)[0..1]
return [rows, cols] if nonzero... | ruby | def size_from_ioctl
return if jruby?
return unless @output.respond_to?(:ioctl)
format = 'SSSS'
buffer = ([0] * format.size).pack(format)
if ioctl?(TIOCGWINSZ, buffer) || ioctl?(TIOCGWINSZ_PPC, buffer)
rows, cols, = buffer.unpack(format)[0..1]
return [rows, cols] if nonzero... | [
"def",
"size_from_ioctl",
"return",
"if",
"jruby?",
"return",
"unless",
"@output",
".",
"respond_to?",
"(",
":ioctl",
")",
"format",
"=",
"'SSSS'",
"buffer",
"=",
"(",
"[",
"0",
"]",
"*",
"format",
".",
"size",
")",
".",
"pack",
"(",
"format",
")",
"if... | Read terminal size from Unix ioctl
@return [nil, Array[Integer, Integer]]
@api private | [
"Read",
"terminal",
"size",
"from",
"Unix",
"ioctl"
] | 282ae528974059c16090212dbcfb4a3d5aa3bbeb | https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L156-L166 | train |
piotrmurach/tty-screen | lib/tty/screen.rb | TTY.Screen.size_from_readline | def size_from_readline
if defined?(Readline) && Readline.respond_to?(:get_screen_size)
size = Readline.get_screen_size
size if nonzero_column?(size[1])
end
rescue NotImplementedError
end | ruby | def size_from_readline
if defined?(Readline) && Readline.respond_to?(:get_screen_size)
size = Readline.get_screen_size
size if nonzero_column?(size[1])
end
rescue NotImplementedError
end | [
"def",
"size_from_readline",
"if",
"defined?",
"(",
"Readline",
")",
"&&",
"Readline",
".",
"respond_to?",
"(",
":get_screen_size",
")",
"size",
"=",
"Readline",
".",
"get_screen_size",
"size",
"if",
"nonzero_column?",
"(",
"size",
"[",
"1",
"]",
")",
"end",
... | Detect screen size using Readline
@api private | [
"Detect",
"screen",
"size",
"using",
"Readline"
] | 282ae528974059c16090212dbcfb4a3d5aa3bbeb | https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L182-L188 | train |
piotrmurach/tty-screen | lib/tty/screen.rb | TTY.Screen.size_from_tput | def size_from_tput
return unless @output.tty?
lines = run_command('tput', 'lines').to_i
cols = run_command('tput', 'cols').to_i
[lines, cols] if nonzero_column?(lines)
rescue IOError, SystemCallError
end | ruby | def size_from_tput
return unless @output.tty?
lines = run_command('tput', 'lines').to_i
cols = run_command('tput', 'cols').to_i
[lines, cols] if nonzero_column?(lines)
rescue IOError, SystemCallError
end | [
"def",
"size_from_tput",
"return",
"unless",
"@output",
".",
"tty?",
"lines",
"=",
"run_command",
"(",
"'tput'",
",",
"'lines'",
")",
".",
"to_i",
"cols",
"=",
"run_command",
"(",
"'tput'",
",",
"'cols'",
")",
".",
"to_i",
"[",
"lines",
",",
"cols",
"]",... | Detect terminal size from tput utility
@api private | [
"Detect",
"terminal",
"size",
"from",
"tput",
"utility"
] | 282ae528974059c16090212dbcfb4a3d5aa3bbeb | https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L194-L200 | train |
piotrmurach/tty-screen | lib/tty/screen.rb | TTY.Screen.size_from_stty | def size_from_stty
return unless @output.tty?
out = run_command('stty', 'size')
return unless out
size = out.split.map(&:to_i)
size if nonzero_column?(size[1])
rescue IOError, SystemCallError
end | ruby | def size_from_stty
return unless @output.tty?
out = run_command('stty', 'size')
return unless out
size = out.split.map(&:to_i)
size if nonzero_column?(size[1])
rescue IOError, SystemCallError
end | [
"def",
"size_from_stty",
"return",
"unless",
"@output",
".",
"tty?",
"out",
"=",
"run_command",
"(",
"'stty'",
",",
"'size'",
")",
"return",
"unless",
"out",
"size",
"=",
"out",
".",
"split",
".",
"map",
"(",
"&",
":to_i",
")",
"size",
"if",
"nonzero_col... | Detect terminal size from stty utility
@api private | [
"Detect",
"terminal",
"size",
"from",
"stty",
"utility"
] | 282ae528974059c16090212dbcfb4a3d5aa3bbeb | https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L206-L213 | train |
piotrmurach/tty-screen | lib/tty/screen.rb | TTY.Screen.run_command | def run_command(*args)
require 'tempfile'
out = Tempfile.new('tty-screen')
result = system(*args, out: out.path, err: File::NULL)
return if result.nil?
out.rewind
out.read
ensure
out.close if out
end | ruby | def run_command(*args)
require 'tempfile'
out = Tempfile.new('tty-screen')
result = system(*args, out: out.path, err: File::NULL)
return if result.nil?
out.rewind
out.read
ensure
out.close if out
end | [
"def",
"run_command",
"(",
"*",
"args",
")",
"require",
"'tempfile'",
"out",
"=",
"Tempfile",
".",
"new",
"(",
"'tty-screen'",
")",
"result",
"=",
"system",
"(",
"*",
"args",
",",
"out",
":",
"out",
".",
"path",
",",
"err",
":",
"File",
"::",
"NULL",... | Runs command silently capturing the output
@api private | [
"Runs",
"command",
"silently",
"capturing",
"the",
"output"
] | 282ae528974059c16090212dbcfb4a3d5aa3bbeb | https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L246-L255 | train |
jpmckinney/multi_mail | lib/multi_mail/service.rb | MultiMail.Service.validate_options | def validate_options(options, raise_error_if_unrecognized = true)
keys = []
for key, value in options
unless value.nil?
keys << key
end
end
missing = requirements - keys
unless missing.empty?
raise ArgumentError, "Missing required arguments: #{missing.map... | ruby | def validate_options(options, raise_error_if_unrecognized = true)
keys = []
for key, value in options
unless value.nil?
keys << key
end
end
missing = requirements - keys
unless missing.empty?
raise ArgumentError, "Missing required arguments: #{missing.map... | [
"def",
"validate_options",
"(",
"options",
",",
"raise_error_if_unrecognized",
"=",
"true",
")",
"keys",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"options",
"unless",
"value",
".",
"nil?",
"keys",
"<<",
"key",
"end",
"end",
"missing",
"=",
"require... | Ensures that required arguments are present and that optional arguments
are recognized.
@param [Hash] options arguments
@raise [ArgumentError] if it can't find a required argument or can't
recognize an optional argument
@see Fog::Service::validate_options | [
"Ensures",
"that",
"required",
"arguments",
"are",
"present",
"and",
"that",
"optional",
"arguments",
"are",
"recognized",
"."
] | 4c9d7310633c1034afbef0dab873e89a8c608d00 | https://github.com/jpmckinney/multi_mail/blob/4c9d7310633c1034afbef0dab873e89a8c608d00/lib/multi_mail/service.rb#L45-L64 | train |
rgrove/crass | lib/crass/parser.rb | Crass.Parser.consume_at_rule | def consume_at_rule(input = @tokens)
rule = {}
rule[:tokens] = input.collect do
rule[:name] = input.consume[:value]
rule[:prelude] = []
while token = input.consume
node = token[:node]
if node == :comment # Non-standard.
next
elsif node... | ruby | def consume_at_rule(input = @tokens)
rule = {}
rule[:tokens] = input.collect do
rule[:name] = input.consume[:value]
rule[:prelude] = []
while token = input.consume
node = token[:node]
if node == :comment # Non-standard.
next
elsif node... | [
"def",
"consume_at_rule",
"(",
"input",
"=",
"@tokens",
")",
"rule",
"=",
"{",
"}",
"rule",
"[",
":tokens",
"]",
"=",
"input",
".",
"collect",
"do",
"rule",
"[",
":name",
"]",
"=",
"input",
".",
"consume",
"[",
":value",
"]",
"rule",
"[",
":prelude",... | Initializes a parser based on the given _input_, which may be a CSS string
or an array of tokens.
See {Tokenizer#initialize} for _options_.
Consumes an at-rule and returns it.
5.4.2. http://dev.w3.org/csswg/css-syntax-3/#consume-at-rule | [
"Initializes",
"a",
"parser",
"based",
"on",
"the",
"given",
"_input_",
"which",
"may",
"be",
"a",
"CSS",
"string",
"or",
"an",
"array",
"of",
"tokens",
"."
] | 074e56f2a9f10bb873fa8e708ef58a065d4281a2 | https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L137-L178 | train |
rgrove/crass | lib/crass/parser.rb | Crass.Parser.consume_component_value | def consume_component_value(input = @tokens)
return nil unless token = input.consume
case token[:node]
when :'{', :'[', :'('
consume_simple_block(input)
when :function
if token.key?(:name)
# This is a parsed function, not a function token. This step isn't
# ... | ruby | def consume_component_value(input = @tokens)
return nil unless token = input.consume
case token[:node]
when :'{', :'[', :'('
consume_simple_block(input)
when :function
if token.key?(:name)
# This is a parsed function, not a function token. This step isn't
# ... | [
"def",
"consume_component_value",
"(",
"input",
"=",
"@tokens",
")",
"return",
"nil",
"unless",
"token",
"=",
"input",
".",
"consume",
"case",
"token",
"[",
":node",
"]",
"when",
":'",
"'",
",",
":'",
"'",
",",
":'",
"'",
"consume_simple_block",
"(",
"in... | Consumes a component value and returns it, or `nil` if there are no more
tokens.
5.4.6. http://dev.w3.org/csswg/css-syntax-3/#consume-a-component-value | [
"Consumes",
"a",
"component",
"value",
"and",
"returns",
"it",
"or",
"nil",
"if",
"there",
"are",
"no",
"more",
"tokens",
"."
] | 074e56f2a9f10bb873fa8e708ef58a065d4281a2 | https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L184-L204 | train |
rgrove/crass | lib/crass/parser.rb | Crass.Parser.consume_declaration | def consume_declaration(input = @tokens)
declaration = {}
value = []
declaration[:tokens] = input.collect do
declaration[:name] = input.consume[:value]
next_token = input.peek
while next_token && next_token[:node] == :whitespace
input.consume
next_t... | ruby | def consume_declaration(input = @tokens)
declaration = {}
value = []
declaration[:tokens] = input.collect do
declaration[:name] = input.consume[:value]
next_token = input.peek
while next_token && next_token[:node] == :whitespace
input.consume
next_t... | [
"def",
"consume_declaration",
"(",
"input",
"=",
"@tokens",
")",
"declaration",
"=",
"{",
"}",
"value",
"=",
"[",
"]",
"declaration",
"[",
":tokens",
"]",
"=",
"input",
".",
"collect",
"do",
"declaration",
"[",
":name",
"]",
"=",
"input",
".",
"consume",... | Consumes a declaration and returns it, or `nil` on parse error.
5.4.5. http://dev.w3.org/csswg/css-syntax-3/#consume-a-declaration | [
"Consumes",
"a",
"declaration",
"and",
"returns",
"it",
"or",
"nil",
"on",
"parse",
"error",
"."
] | 074e56f2a9f10bb873fa8e708ef58a065d4281a2 | https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L209-L263 | train |
rgrove/crass | lib/crass/parser.rb | Crass.Parser.consume_declarations | def consume_declarations(input = @tokens, options = {})
declarations = []
while token = input.consume
case token[:node]
# Non-standard: Preserve comments, semicolons, and whitespace.
when :comment, :semicolon, :whitespace
declarations << token unless options[:strict]
... | ruby | def consume_declarations(input = @tokens, options = {})
declarations = []
while token = input.consume
case token[:node]
# Non-standard: Preserve comments, semicolons, and whitespace.
when :comment, :semicolon, :whitespace
declarations << token unless options[:strict]
... | [
"def",
"consume_declarations",
"(",
"input",
"=",
"@tokens",
",",
"options",
"=",
"{",
"}",
")",
"declarations",
"=",
"[",
"]",
"while",
"token",
"=",
"input",
".",
"consume",
"case",
"token",
"[",
":node",
"]",
"when",
":comment",
",",
":semicolon",
","... | Consumes a list of declarations and returns them.
By default, the returned list may include `:comment`, `:semicolon`, and
`:whitespace` nodes, which is non-standard.
Options:
* **:strict** - Set to `true` to exclude non-standard `:comment`,
`:semicolon`, and `:whitespace` nodes.
5.4.4. http://dev.w3.org... | [
"Consumes",
"a",
"list",
"of",
"declarations",
"and",
"returns",
"them",
"."
] | 074e56f2a9f10bb873fa8e708ef58a065d4281a2 | https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L276-L321 | train |
rgrove/crass | lib/crass/parser.rb | Crass.Parser.consume_function | def consume_function(input = @tokens)
function = {
:name => input.current[:value],
:value => [],
:tokens => [input.current] # Non-standard, used for serialization.
}
function[:tokens].concat(input.collect {
while token = input.consume
case token[:node]
... | ruby | def consume_function(input = @tokens)
function = {
:name => input.current[:value],
:value => [],
:tokens => [input.current] # Non-standard, used for serialization.
}
function[:tokens].concat(input.collect {
while token = input.consume
case token[:node]
... | [
"def",
"consume_function",
"(",
"input",
"=",
"@tokens",
")",
"function",
"=",
"{",
":name",
"=>",
"input",
".",
"current",
"[",
":value",
"]",
",",
":value",
"=>",
"[",
"]",
",",
":tokens",
"=>",
"[",
"input",
".",
"current",
"]",
"}",
"function",
"... | Consumes a function and returns it.
5.4.8. http://dev.w3.org/csswg/css-syntax-3/#consume-a-function | [
"Consumes",
"a",
"function",
"and",
"returns",
"it",
"."
] | 074e56f2a9f10bb873fa8e708ef58a065d4281a2 | https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L326-L351 | train |
rgrove/crass | lib/crass/parser.rb | Crass.Parser.consume_qualified_rule | def consume_qualified_rule(input = @tokens)
rule = {:prelude => []}
rule[:tokens] = input.collect do
while true
unless token = input.consume
# Parse error.
#
# Note: The spec explicitly says to return nothing here, but Simon
# Sapin's CSS pa... | ruby | def consume_qualified_rule(input = @tokens)
rule = {:prelude => []}
rule[:tokens] = input.collect do
while true
unless token = input.consume
# Parse error.
#
# Note: The spec explicitly says to return nothing here, but Simon
# Sapin's CSS pa... | [
"def",
"consume_qualified_rule",
"(",
"input",
"=",
"@tokens",
")",
"rule",
"=",
"{",
":prelude",
"=>",
"[",
"]",
"}",
"rule",
"[",
":tokens",
"]",
"=",
"input",
".",
"collect",
"do",
"while",
"true",
"unless",
"token",
"=",
"input",
".",
"consume",
"r... | Consumes a qualified rule and returns it, or `nil` if a parse error
occurs.
5.4.3. http://dev.w3.org/csswg/css-syntax-3/#consume-a-qualified-rule | [
"Consumes",
"a",
"qualified",
"rule",
"and",
"returns",
"it",
"or",
"nil",
"if",
"a",
"parse",
"error",
"occurs",
"."
] | 074e56f2a9f10bb873fa8e708ef58a065d4281a2 | https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L357-L393 | train |
rgrove/crass | lib/crass/parser.rb | Crass.Parser.consume_rules | def consume_rules(flags = {})
rules = []
while token = @tokens.consume
case token[:node]
# Non-standard. Spec says to discard comments and whitespace, but we
# keep them so we can serialize faithfully.
when :comment, :whitespace
rules << token
when :cd... | ruby | def consume_rules(flags = {})
rules = []
while token = @tokens.consume
case token[:node]
# Non-standard. Spec says to discard comments and whitespace, but we
# keep them so we can serialize faithfully.
when :comment, :whitespace
rules << token
when :cd... | [
"def",
"consume_rules",
"(",
"flags",
"=",
"{",
"}",
")",
"rules",
"=",
"[",
"]",
"while",
"token",
"=",
"@tokens",
".",
"consume",
"case",
"token",
"[",
":node",
"]",
"when",
":comment",
",",
":whitespace",
"rules",
"<<",
"token",
"when",
":cdc",
",",... | Consumes a list of rules and returns them.
5.4.1. http://dev.w3.org/csswg/css-syntax/#consume-a-list-of-rules | [
"Consumes",
"a",
"list",
"of",
"rules",
"and",
"returns",
"them",
"."
] | 074e56f2a9f10bb873fa8e708ef58a065d4281a2 | https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L398-L428 | train |
rgrove/crass | lib/crass/parser.rb | Crass.Parser.consume_simple_block | def consume_simple_block(input = @tokens)
start_token = input.current[:node]
end_token = BLOCK_END_TOKENS[start_token]
block = {
:start => start_token.to_s,
:end => end_token.to_s,
:value => [],
:tokens => [input.current] # Non-standard. Used for serialization.
... | ruby | def consume_simple_block(input = @tokens)
start_token = input.current[:node]
end_token = BLOCK_END_TOKENS[start_token]
block = {
:start => start_token.to_s,
:end => end_token.to_s,
:value => [],
:tokens => [input.current] # Non-standard. Used for serialization.
... | [
"def",
"consume_simple_block",
"(",
"input",
"=",
"@tokens",
")",
"start_token",
"=",
"input",
".",
"current",
"[",
":node",
"]",
"end_token",
"=",
"BLOCK_END_TOKENS",
"[",
"start_token",
"]",
"block",
"=",
"{",
":start",
"=>",
"start_token",
".",
"to_s",
",... | Consumes and returns a simple block associated with the current input
token.
5.4.7. http://dev.w3.org/csswg/css-syntax/#consume-a-simple-block | [
"Consumes",
"and",
"returns",
"a",
"simple",
"block",
"associated",
"with",
"the",
"current",
"input",
"token",
"."
] | 074e56f2a9f10bb873fa8e708ef58a065d4281a2 | https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L434-L455 | train |
rgrove/crass | lib/crass/parser.rb | Crass.Parser.parse_component_value | def parse_component_value(input = @tokens)
input = TokenScanner.new(input) unless input.is_a?(TokenScanner)
while input.peek && input.peek[:node] == :whitespace
input.consume
end
if input.peek.nil?
return create_node(:error, :value => 'empty')
end
value = consume_c... | ruby | def parse_component_value(input = @tokens)
input = TokenScanner.new(input) unless input.is_a?(TokenScanner)
while input.peek && input.peek[:node] == :whitespace
input.consume
end
if input.peek.nil?
return create_node(:error, :value => 'empty')
end
value = consume_c... | [
"def",
"parse_component_value",
"(",
"input",
"=",
"@tokens",
")",
"input",
"=",
"TokenScanner",
".",
"new",
"(",
"input",
")",
"unless",
"input",
".",
"is_a?",
"(",
"TokenScanner",
")",
"while",
"input",
".",
"peek",
"&&",
"input",
".",
"peek",
"[",
":n... | Parses a single component value and returns it.
5.3.7. http://dev.w3.org/csswg/css-syntax-3/#parse-a-component-value | [
"Parses",
"a",
"single",
"component",
"value",
"and",
"returns",
"it",
"."
] | 074e56f2a9f10bb873fa8e708ef58a065d4281a2 | https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L483-L505 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.