repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
crapooze/em-xmpp | lib/em-xmpp/entity.rb | EM::Xmpp.Entity.pubsub | def pubsub(nid=nil)
node_jid = if nid
JID.new(jid.node, jid.domain, nid)
else
jid.to_s
end
PubSub.new(connection, node_jid)
end | ruby | def pubsub(nid=nil)
node_jid = if nid
JID.new(jid.node, jid.domain, nid)
else
jid.to_s
end
PubSub.new(connection, node_jid)
end | [
"def",
"pubsub",
"(",
"nid",
"=",
"nil",
")",
"node_jid",
"=",
"if",
"nid",
"JID",
".",
"new",
"(",
"jid",
".",
"node",
",",
"jid",
".",
"domain",
",",
"nid",
")",
"else",
"jid",
".",
"to_s",
"end",
"PubSub",
".",
"new",
"(",
"connection",
",",
"node_jid",
")",
"end"
] | returns a PubSub entity with same bare jid
accepts an optional node-id | [
"returns",
"a",
"PubSub",
"entity",
"with",
"same",
"bare",
"jid",
"accepts",
"an",
"optional",
"node",
"-",
"id"
] | 804e139944c88bc317b359754d5ad69b75f42319 | https://github.com/crapooze/em-xmpp/blob/804e139944c88bc317b359754d5ad69b75f42319/lib/em-xmpp/entity.rb#L130-L137 | train |
crapooze/em-xmpp | lib/em-xmpp/entity.rb | EM::Xmpp.Entity.muc | def muc(nick=nil)
muc_jid = JID.new jid.node, jid.domain, nick
Muc.new(connection, muc_jid)
end | ruby | def muc(nick=nil)
muc_jid = JID.new jid.node, jid.domain, nick
Muc.new(connection, muc_jid)
end | [
"def",
"muc",
"(",
"nick",
"=",
"nil",
")",
"muc_jid",
"=",
"JID",
".",
"new",
"jid",
".",
"node",
",",
"jid",
".",
"domain",
",",
"nick",
"Muc",
".",
"new",
"(",
"connection",
",",
"muc_jid",
")",
"end"
] | Generates a MUC entity from this entity.
If the nick argument is null then the entity is the MUC itself.
If the nick argument is present, then the entity is the user with
the corresponding nickname. | [
"Generates",
"a",
"MUC",
"entity",
"from",
"this",
"entity",
".",
"If",
"the",
"nick",
"argument",
"is",
"null",
"then",
"the",
"entity",
"is",
"the",
"MUC",
"itself",
".",
"If",
"the",
"nick",
"argument",
"is",
"present",
"then",
"the",
"entity",
"is",
"the",
"user",
"with",
"the",
"corresponding",
"nickname",
"."
] | 804e139944c88bc317b359754d5ad69b75f42319 | https://github.com/crapooze/em-xmpp/blob/804e139944c88bc317b359754d5ad69b75f42319/lib/em-xmpp/entity.rb#L630-L633 | train |
skift/estore_conventions | lib/estore_conventions/archived_outliers.rb | EstoreConventions.ArchivedOutliers.versions_average_for_attribute | def versions_average_for_attribute(att, opts={})
_use_delta = opts[:delta] || false
if _use_delta
return historical_rate_per_day(att, nil, nil)
else
data = versions_complete_data_for_attribute(att, opts)
return data.e_mean
end
end | ruby | def versions_average_for_attribute(att, opts={})
_use_delta = opts[:delta] || false
if _use_delta
return historical_rate_per_day(att, nil, nil)
else
data = versions_complete_data_for_attribute(att, opts)
return data.e_mean
end
end | [
"def",
"versions_average_for_attribute",
"(",
"att",
",",
"opts",
"=",
"{",
"}",
")",
"_use_delta",
"=",
"opts",
"[",
":delta",
"]",
"||",
"false",
"if",
"_use_delta",
"return",
"historical_rate_per_day",
"(",
"att",
",",
"nil",
",",
"nil",
")",
"else",
"data",
"=",
"versions_complete_data_for_attribute",
"(",
"att",
",",
"opts",
")",
"return",
"data",
".",
"e_mean",
"end",
"end"
] | returns Float
this is wonky because of the wonky way we use historical_rate_by_day | [
"returns",
"Float",
"this",
"is",
"wonky",
"because",
"of",
"the",
"wonky",
"way",
"we",
"use",
"historical_rate_by_day"
] | b9f1dfa45d476ecbadaa0a50729aeef064961183 | https://github.com/skift/estore_conventions/blob/b9f1dfa45d476ecbadaa0a50729aeef064961183/lib/estore_conventions/archived_outliers.rb#L16-L25 | train |
linjunpop/jia | lib/jia/user.rb | Jia.User.phone | def phone
@phone ||= -> {
mac = Jia::Utils.load_data('phone_mac').sample
area_code = rand(9999).to_s.center(4, rand(9).to_s)
user_identifier = rand(9999).to_s.center(4, rand(9).to_s)
"#{mac}#{area_code}#{user_identifier}"
}.call
end | ruby | def phone
@phone ||= -> {
mac = Jia::Utils.load_data('phone_mac').sample
area_code = rand(9999).to_s.center(4, rand(9).to_s)
user_identifier = rand(9999).to_s.center(4, rand(9).to_s)
"#{mac}#{area_code}#{user_identifier}"
}.call
end | [
"def",
"phone",
"@phone",
"||=",
"->",
"{",
"mac",
"=",
"Jia",
"::",
"Utils",
".",
"load_data",
"(",
"'phone_mac'",
")",
".",
"sample",
"area_code",
"=",
"rand",
"(",
"9999",
")",
".",
"to_s",
".",
"center",
"(",
"4",
",",
"rand",
"(",
"9",
")",
".",
"to_s",
")",
"user_identifier",
"=",
"rand",
"(",
"9999",
")",
".",
"to_s",
".",
"center",
"(",
"4",
",",
"rand",
"(",
"9",
")",
".",
"to_s",
")",
"\"#{mac}#{area_code}#{user_identifier}\"",
"}",
".",
"call",
"end"
] | Get phone number
Jia::User.new.phone # => '18100000000' | [
"Get",
"phone",
"number"
] | 366da5916a4fca61198376d5bcae668a2841799e | https://github.com/linjunpop/jia/blob/366da5916a4fca61198376d5bcae668a2841799e/lib/jia/user.rb#L47-L54 | train |
charypar/cyclical | lib/cyclical/rule.rb | Cyclical.Rule.match? | def match?(time, base)
aligned?(time, base) && @filters.all? { |f| f.match?(time) }
end | ruby | def match?(time, base)
aligned?(time, base) && @filters.all? { |f| f.match?(time) }
end | [
"def",
"match?",
"(",
"time",
",",
"base",
")",
"aligned?",
"(",
"time",
",",
"base",
")",
"&&",
"@filters",
".",
"all?",
"{",
"|",
"f",
"|",
"f",
".",
"match?",
"(",
"time",
")",
"}",
"end"
] | returns true if time is aligned to the recurrence pattern and matches all the filters | [
"returns",
"true",
"if",
"time",
"is",
"aligned",
"to",
"the",
"recurrence",
"pattern",
"and",
"matches",
"all",
"the",
"filters"
] | 8e45b8f83e2dd59fcad01e220412bb361867f5c6 | https://github.com/charypar/cyclical/blob/8e45b8f83e2dd59fcad01e220412bb361867f5c6/lib/cyclical/rule.rb#L101-L103 | train |
charypar/cyclical | lib/cyclical/rule.rb | Cyclical.Rule.potential_previous | def potential_previous(current, base)
@filters.map { |f| f.previous(current) }.min || current
end | ruby | def potential_previous(current, base)
@filters.map { |f| f.previous(current) }.min || current
end | [
"def",
"potential_previous",
"(",
"current",
",",
"base",
")",
"@filters",
".",
"map",
"{",
"|",
"f",
"|",
"f",
".",
"previous",
"(",
"current",
")",
"}",
".",
"min",
"||",
"current",
"end"
] | Find a potential previous date matching the rule as a minimum of previous
valid dates from all the filters. Subclasses should add a check of
recurrence pattern match | [
"Find",
"a",
"potential",
"previous",
"date",
"matching",
"the",
"rule",
"as",
"a",
"minimum",
"of",
"previous",
"valid",
"dates",
"from",
"all",
"the",
"filters",
".",
"Subclasses",
"should",
"add",
"a",
"check",
"of",
"recurrence",
"pattern",
"match"
] | 8e45b8f83e2dd59fcad01e220412bb361867f5c6 | https://github.com/charypar/cyclical/blob/8e45b8f83e2dd59fcad01e220412bb361867f5c6/lib/cyclical/rule.rb#L216-L218 | train |
chetan/bixby-common | lib/bixby-common/util/hashify.rb | Bixby.Hashify.to_hash | def to_hash
self.instance_variables.inject({}) { |m,v| m[v[1,v.length].to_sym] = instance_variable_get(v); m }
end | ruby | def to_hash
self.instance_variables.inject({}) { |m,v| m[v[1,v.length].to_sym] = instance_variable_get(v); m }
end | [
"def",
"to_hash",
"self",
".",
"instance_variables",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"m",
",",
"v",
"|",
"m",
"[",
"v",
"[",
"1",
",",
"v",
".",
"length",
"]",
".",
"to_sym",
"]",
"=",
"instance_variable_get",
"(",
"v",
")",
";",
"m",
"}",
"end"
] | Creates a Hash representation of self
@return [Hash] | [
"Creates",
"a",
"Hash",
"representation",
"of",
"self"
] | 3fb8829987b115fc53ec820d97a20b4a8c49b4a2 | https://github.com/chetan/bixby-common/blob/3fb8829987b115fc53ec820d97a20b4a8c49b4a2/lib/bixby-common/util/hashify.rb#L10-L12 | train |
Timmehs/coals | lib/coals/task_tree.rb | Coals.TaskTree.build_tasks | def build_tasks
load_rakefile
Rake.application.tasks.reject { |t| t.comment.nil? }
end | ruby | def build_tasks
load_rakefile
Rake.application.tasks.reject { |t| t.comment.nil? }
end | [
"def",
"build_tasks",
"load_rakefile",
"Rake",
".",
"application",
".",
"tasks",
".",
"reject",
"{",
"|",
"t",
"|",
"t",
".",
"comment",
".",
"nil?",
"}",
"end"
] | Coals assumes that any task lacking a description
is not meant to be called directly, i.e. a 'subtask'
This is in line with the list rendered by `rake -T` | [
"Coals",
"assumes",
"that",
"any",
"task",
"lacking",
"a",
"description",
"is",
"not",
"meant",
"to",
"be",
"called",
"directly",
"i",
".",
"e",
".",
"a",
"subtask",
"This",
"is",
"in",
"line",
"with",
"the",
"list",
"rendered",
"by",
"rake",
"-",
"T"
] | 0b4b416386ab8775ecbc0965470ae1b7747ab884 | https://github.com/Timmehs/coals/blob/0b4b416386ab8775ecbc0965470ae1b7747ab884/lib/coals/task_tree.rb#L23-L26 | train |
ideonetwork/lato-blog | app/models/lato_blog/post.rb | LatoBlog.Post.check_lato_blog_post_parent | def check_lato_blog_post_parent
post_parent = LatoBlog::PostParent.find_by(id: lato_blog_post_parent_id)
if !post_parent
errors.add('Post parent', 'not exist for the post')
throw :abort
return
end
same_language_post = post_parent.posts.find_by(meta_language: meta_language)
if same_language_post && same_language_post.id != id
errors.add('Post parent', 'has another post for the same language')
throw :abort
return
end
end | ruby | def check_lato_blog_post_parent
post_parent = LatoBlog::PostParent.find_by(id: lato_blog_post_parent_id)
if !post_parent
errors.add('Post parent', 'not exist for the post')
throw :abort
return
end
same_language_post = post_parent.posts.find_by(meta_language: meta_language)
if same_language_post && same_language_post.id != id
errors.add('Post parent', 'has another post for the same language')
throw :abort
return
end
end | [
"def",
"check_lato_blog_post_parent",
"post_parent",
"=",
"LatoBlog",
"::",
"PostParent",
".",
"find_by",
"(",
"id",
":",
"lato_blog_post_parent_id",
")",
"if",
"!",
"post_parent",
"errors",
".",
"add",
"(",
"'Post parent'",
",",
"'not exist for the post'",
")",
"throw",
":abort",
"return",
"end",
"same_language_post",
"=",
"post_parent",
".",
"posts",
".",
"find_by",
"(",
"meta_language",
":",
"meta_language",
")",
"if",
"same_language_post",
"&&",
"same_language_post",
".",
"id",
"!=",
"id",
"errors",
".",
"add",
"(",
"'Post parent'",
",",
"'has another post for the same language'",
")",
"throw",
":abort",
"return",
"end",
"end"
] | This function check that the post parent exist and has not others post for the same language. | [
"This",
"function",
"check",
"that",
"the",
"post",
"parent",
"exist",
"and",
"has",
"not",
"others",
"post",
"for",
"the",
"same",
"language",
"."
] | a0d92de299a0e285851743b9d4a902f611187cba | https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/models/lato_blog/post.rb#L89-L103 | train |
ideonetwork/lato-blog | app/models/lato_blog/post.rb | LatoBlog.Post.add_to_default_category | def add_to_default_category
default_category_parent = LatoBlog::CategoryParent.find_by(meta_default: true)
return unless default_category_parent
category = default_category_parent.categories.find_by(meta_language: meta_language)
return unless category
LatoBlog::CategoryPost.create(lato_blog_post_id: id, lato_blog_category_id: category.id)
end | ruby | def add_to_default_category
default_category_parent = LatoBlog::CategoryParent.find_by(meta_default: true)
return unless default_category_parent
category = default_category_parent.categories.find_by(meta_language: meta_language)
return unless category
LatoBlog::CategoryPost.create(lato_blog_post_id: id, lato_blog_category_id: category.id)
end | [
"def",
"add_to_default_category",
"default_category_parent",
"=",
"LatoBlog",
"::",
"CategoryParent",
".",
"find_by",
"(",
"meta_default",
":",
"true",
")",
"return",
"unless",
"default_category_parent",
"category",
"=",
"default_category_parent",
".",
"categories",
".",
"find_by",
"(",
"meta_language",
":",
"meta_language",
")",
"return",
"unless",
"category",
"LatoBlog",
"::",
"CategoryPost",
".",
"create",
"(",
"lato_blog_post_id",
":",
"id",
",",
"lato_blog_category_id",
":",
"category",
".",
"id",
")",
"end"
] | This function add the post to the default category. | [
"This",
"function",
"add",
"the",
"post",
"to",
"the",
"default",
"category",
"."
] | a0d92de299a0e285851743b9d4a902f611187cba | https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/models/lato_blog/post.rb#L106-L114 | train |
teodor-pripoae/scalaroid | lib/scalaroid/json_connection.rb | Scalaroid.JSONConnection.call | def call(function, params)
start
req = Net::HTTP::Post.new(DEFAULT_PATH)
req.add_field('Content-Type', 'application/json; charset=utf-8')
req.body = URI::encode({
:jsonrpc => :'2.0',
:method => function,
:params => params,
:id => 0 }.to_json({:ascii_only => true}))
begin
res = @conn.request(req)
if res.is_a?(Net::HTTPSuccess)
data = res.body
return JSON.parse(data)['result']
else
raise ConnectionError.new(res)
end
rescue ConnectionError => error
raise error
rescue Exception => error
raise ConnectionError.new(error)
end
end | ruby | def call(function, params)
start
req = Net::HTTP::Post.new(DEFAULT_PATH)
req.add_field('Content-Type', 'application/json; charset=utf-8')
req.body = URI::encode({
:jsonrpc => :'2.0',
:method => function,
:params => params,
:id => 0 }.to_json({:ascii_only => true}))
begin
res = @conn.request(req)
if res.is_a?(Net::HTTPSuccess)
data = res.body
return JSON.parse(data)['result']
else
raise ConnectionError.new(res)
end
rescue ConnectionError => error
raise error
rescue Exception => error
raise ConnectionError.new(error)
end
end | [
"def",
"call",
"(",
"function",
",",
"params",
")",
"start",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"DEFAULT_PATH",
")",
"req",
".",
"add_field",
"(",
"'Content-Type'",
",",
"'application/json; charset=utf-8'",
")",
"req",
".",
"body",
"=",
"URI",
"::",
"encode",
"(",
"{",
":jsonrpc",
"=>",
":'",
"'",
",",
":method",
"=>",
"function",
",",
":params",
"=>",
"params",
",",
":id",
"=>",
"0",
"}",
".",
"to_json",
"(",
"{",
":ascii_only",
"=>",
"true",
"}",
")",
")",
"begin",
"res",
"=",
"@conn",
".",
"request",
"(",
"req",
")",
"if",
"res",
".",
"is_a?",
"(",
"Net",
"::",
"HTTPSuccess",
")",
"data",
"=",
"res",
".",
"body",
"return",
"JSON",
".",
"parse",
"(",
"data",
")",
"[",
"'result'",
"]",
"else",
"raise",
"ConnectionError",
".",
"new",
"(",
"res",
")",
"end",
"rescue",
"ConnectionError",
"=>",
"error",
"raise",
"error",
"rescue",
"Exception",
"=>",
"error",
"raise",
"ConnectionError",
".",
"new",
"(",
"error",
")",
"end",
"end"
] | Calls the given function with the given parameters via the JSON
interface of Scalaris. | [
"Calls",
"the",
"given",
"function",
"with",
"the",
"given",
"parameters",
"via",
"the",
"JSON",
"interface",
"of",
"Scalaris",
"."
] | 4e9e90e71ce3008da79a72eae40fe2f187580be2 | https://github.com/teodor-pripoae/scalaroid/blob/4e9e90e71ce3008da79a72eae40fe2f187580be2/lib/scalaroid/json_connection.rb#L27-L49 | train |
LRDesign/Caliph | lib/caliph/command-line.rb | Caliph.CommandLine.string_format | def string_format
(command_environment.map do |key, value|
[key, value].join("=")
end + [command]).join(" ")
end | ruby | def string_format
(command_environment.map do |key, value|
[key, value].join("=")
end + [command]).join(" ")
end | [
"def",
"string_format",
"(",
"command_environment",
".",
"map",
"do",
"|",
"key",
",",
"value",
"|",
"[",
"key",
",",
"value",
"]",
".",
"join",
"(",
"\"=\"",
")",
"end",
"+",
"[",
"command",
"]",
")",
".",
"join",
"(",
"\" \"",
")",
"end"
] | The command as a string, including arguments and options, plus prefixed
environment variables. | [
"The",
"command",
"as",
"a",
"string",
"including",
"arguments",
"and",
"options",
"plus",
"prefixed",
"environment",
"variables",
"."
] | 9ad99fb72f75b87fa76eb28d4fc3ab811b29bb99 | https://github.com/LRDesign/Caliph/blob/9ad99fb72f75b87fa76eb28d4fc3ab811b29bb99/lib/caliph/command-line.rb#L52-L56 | train |
rudionrails/little_log_friend | lib/little_log_friend/formatter.rb | LittleLogFriend.Formatter.call | def call ( severity, time, progname, msg )
msg = Format % [format_datetime(time), severity, $$, progname, msg2str(msg)]
msg = @@colors[severity] + msg + @@colors['DEFAULT'] if @@colorize
msg << "\n"
end | ruby | def call ( severity, time, progname, msg )
msg = Format % [format_datetime(time), severity, $$, progname, msg2str(msg)]
msg = @@colors[severity] + msg + @@colors['DEFAULT'] if @@colorize
msg << "\n"
end | [
"def",
"call",
"(",
"severity",
",",
"time",
",",
"progname",
",",
"msg",
")",
"msg",
"=",
"Format",
"%",
"[",
"format_datetime",
"(",
"time",
")",
",",
"severity",
",",
"$$",
",",
"progname",
",",
"msg2str",
"(",
"msg",
")",
"]",
"msg",
"=",
"@@colors",
"[",
"severity",
"]",
"+",
"msg",
"+",
"@@colors",
"[",
"'DEFAULT'",
"]",
"if",
"@@colorize",
"msg",
"<<",
"\"\\n\"",
"end"
] | This method is invoked when a log event occurs | [
"This",
"method",
"is",
"invoked",
"when",
"a",
"log",
"event",
"occurs"
] | eed4ecadbf4aeff0e7cd7cfb619e6a7695c6bfbd | https://github.com/rudionrails/little_log_friend/blob/eed4ecadbf4aeff0e7cd7cfb619e6a7695c6bfbd/lib/little_log_friend/formatter.rb#L30-L34 | train |
Gr3atWh173/hail_hydra | lib/client.rb | HailHydra.TPB.search | def search(query, pages=1, orderby=99)
get = make_search_request(query, pages, orderby)
raise "Invalid response: #{get.response.code}" unless get.response.code == "200"
return parse_search_results(get.response.body)
end | ruby | def search(query, pages=1, orderby=99)
get = make_search_request(query, pages, orderby)
raise "Invalid response: #{get.response.code}" unless get.response.code == "200"
return parse_search_results(get.response.body)
end | [
"def",
"search",
"(",
"query",
",",
"pages",
"=",
"1",
",",
"orderby",
"=",
"99",
")",
"get",
"=",
"make_search_request",
"(",
"query",
",",
"pages",
",",
"orderby",
")",
"raise",
"\"Invalid response: #{get.response.code}\"",
"unless",
"get",
".",
"response",
".",
"code",
"==",
"\"200\"",
"return",
"parse_search_results",
"(",
"get",
".",
"response",
".",
"body",
")",
"end"
] | remember the domain name and get the cookie to use from the TPB server
search torrents | [
"remember",
"the",
"domain",
"name",
"and",
"get",
"the",
"cookie",
"to",
"use",
"from",
"the",
"TPB",
"server",
"search",
"torrents"
] | 2ff9cd69b138182911c19f81905970979b2873a8 | https://github.com/Gr3atWh173/hail_hydra/blob/2ff9cd69b138182911c19f81905970979b2873a8/lib/client.rb#L16-L20 | train |
anthonator/skittles | lib/skittles/request.rb | Skittles.Request.post | def post(path, options = {}, headers = {}, raw = false)
request(:post, path, options, headers, raw)
end | ruby | def post(path, options = {}, headers = {}, raw = false)
request(:post, path, options, headers, raw)
end | [
"def",
"post",
"(",
"path",
",",
"options",
"=",
"{",
"}",
",",
"headers",
"=",
"{",
"}",
",",
"raw",
"=",
"false",
")",
"request",
"(",
":post",
",",
"path",
",",
"options",
",",
"headers",
",",
"raw",
")",
"end"
] | Performs an HTTP POST request | [
"Performs",
"an",
"HTTP",
"POST",
"request"
] | 1d7744a53089ef70f4a9c77a8e876d51d4c5bafc | https://github.com/anthonator/skittles/blob/1d7744a53089ef70f4a9c77a8e876d51d4c5bafc/lib/skittles/request.rb#L9-L11 | train |
anthonator/skittles | lib/skittles/request.rb | Skittles.Request.put | def put(path, options = {}, headers = {}, raw = false)
request(:put, path, options, headers, raw)
end | ruby | def put(path, options = {}, headers = {}, raw = false)
request(:put, path, options, headers, raw)
end | [
"def",
"put",
"(",
"path",
",",
"options",
"=",
"{",
"}",
",",
"headers",
"=",
"{",
"}",
",",
"raw",
"=",
"false",
")",
"request",
"(",
":put",
",",
"path",
",",
"options",
",",
"headers",
",",
"raw",
")",
"end"
] | Performs an HTTP PUT request | [
"Performs",
"an",
"HTTP",
"PUT",
"request"
] | 1d7744a53089ef70f4a9c77a8e876d51d4c5bafc | https://github.com/anthonator/skittles/blob/1d7744a53089ef70f4a9c77a8e876d51d4c5bafc/lib/skittles/request.rb#L14-L16 | train |
anthonator/skittles | lib/skittles/request.rb | Skittles.Request.delete | def delete(path, options = {}, headers = {}, raw = false)
request(:delete, path, options, headers, raw)
end | ruby | def delete(path, options = {}, headers = {}, raw = false)
request(:delete, path, options, headers, raw)
end | [
"def",
"delete",
"(",
"path",
",",
"options",
"=",
"{",
"}",
",",
"headers",
"=",
"{",
"}",
",",
"raw",
"=",
"false",
")",
"request",
"(",
":delete",
",",
"path",
",",
"options",
",",
"headers",
",",
"raw",
")",
"end"
] | Performs an HTTP DELETE request | [
"Performs",
"an",
"HTTP",
"DELETE",
"request"
] | 1d7744a53089ef70f4a9c77a8e876d51d4c5bafc | https://github.com/anthonator/skittles/blob/1d7744a53089ef70f4a9c77a8e876d51d4c5bafc/lib/skittles/request.rb#L19-L21 | train |
theablefew/ablerc | lib/ablerc/option.rb | Ablerc.Option.to_stub | def to_stub
stub = "## #{name}\n"
stub << "# #{description}\n" unless description.nil?
stub << "#{entry_for_refuse_allow_behavior}\n" unless refuses.nil? and allows.nil?
stub << "#{entry_for_key_value}\n"
stub << "\n"
end | ruby | def to_stub
stub = "## #{name}\n"
stub << "# #{description}\n" unless description.nil?
stub << "#{entry_for_refuse_allow_behavior}\n" unless refuses.nil? and allows.nil?
stub << "#{entry_for_key_value}\n"
stub << "\n"
end | [
"def",
"to_stub",
"stub",
"=",
"\"## #{name}\\n\"",
"stub",
"<<",
"\"# #{description}\\n\"",
"unless",
"description",
".",
"nil?",
"stub",
"<<",
"\"#{entry_for_refuse_allow_behavior}\\n\"",
"unless",
"refuses",
".",
"nil?",
"and",
"allows",
".",
"nil?",
"stub",
"<<",
"\"#{entry_for_key_value}\\n\"",
"stub",
"<<",
"\"\\n\"",
"end"
] | Initialize the option
==== Parameters
* <tt>name</tt> - A valid name for the option
* <tt>behaviors</tt> - Behaviors used to for this option
* <tt>block</tt> - A proc that should be run against the option value.
==== Options
* <tt>allow</tt> - The option value must be in this list
* <tt>boolean</tt> - The option will accept <tt>true</tt>, <tt>false</tt>, <tt>0</tt>, <tt>1</tt> | [
"Initialize",
"the",
"option"
] | 21ef74d92ef584c82a65b50cf9c908c13864b9e1 | https://github.com/theablefew/ablerc/blob/21ef74d92ef584c82a65b50cf9c908c13864b9e1/lib/ablerc/option.rb#L32-L38 | train |
aapis/notifaction | lib/notifaction/style.rb | Notifaction.Style.format | def format(message, colour = nil, style = nil)
c = @map[:colour][colour.to_sym] unless colour.nil?
if style.nil?
t = 0
else
t = @map[:style][style.to_sym]
end
"\e[#{t};#{c}m#{message}\e[0m"
end | ruby | def format(message, colour = nil, style = nil)
c = @map[:colour][colour.to_sym] unless colour.nil?
if style.nil?
t = 0
else
t = @map[:style][style.to_sym]
end
"\e[#{t};#{c}m#{message}\e[0m"
end | [
"def",
"format",
"(",
"message",
",",
"colour",
"=",
"nil",
",",
"style",
"=",
"nil",
")",
"c",
"=",
"@map",
"[",
":colour",
"]",
"[",
"colour",
".",
"to_sym",
"]",
"unless",
"colour",
".",
"nil?",
"if",
"style",
".",
"nil?",
"t",
"=",
"0",
"else",
"t",
"=",
"@map",
"[",
":style",
"]",
"[",
"style",
".",
"to_sym",
"]",
"end",
"\"\\e[#{t};#{c}m#{message}\\e[0m\"",
"end"
] | Create the map hash
@since 0.4.1
Return an ASCII-formatted string for display in common command line
terminals
@since 0.0.1 | [
"Create",
"the",
"map",
"hash"
] | dbad4c2888a1a59f2a3745d1c1e55c923e0d2039 | https://github.com/aapis/notifaction/blob/dbad4c2888a1a59f2a3745d1c1e55c923e0d2039/lib/notifaction/style.rb#L29-L39 | train |
jtzero/vigilem-support | lib/vigilem/ffi/array_pointer_sync.rb | Vigilem::FFI.ArrayPointerSync.update | def update
if (results = what_changed?)[:ary]
update_ptr
update_ary_cache
true
elsif results[:ptr]
update_ary
update_ptr_cache
true
else
false
end
end | ruby | def update
if (results = what_changed?)[:ary]
update_ptr
update_ary_cache
true
elsif results[:ptr]
update_ary
update_ptr_cache
true
else
false
end
end | [
"def",
"update",
"if",
"(",
"results",
"=",
"what_changed?",
")",
"[",
":ary",
"]",
"update_ptr",
"update_ary_cache",
"true",
"elsif",
"results",
"[",
":ptr",
"]",
"update_ary",
"update_ptr_cache",
"true",
"else",
"false",
"end",
"end"
] | detects what changed and updates as needed
@return [TrueClass || FalseClass] updated? | [
"detects",
"what",
"changed",
"and",
"updates",
"as",
"needed"
] | 4ce72bd01980ed9049e8c03c3d1437f1d4d0de7a | https://github.com/jtzero/vigilem-support/blob/4ce72bd01980ed9049e8c03c3d1437f1d4d0de7a/lib/vigilem/ffi/array_pointer_sync.rb#L305-L317 | train |
jtzero/vigilem-support | lib/vigilem/ffi/array_pointer_sync.rb | Vigilem::FFI.ArrayPointerSync.update_ptr | def update_ptr
ptr.clear
if (not (arry_type = self.class.ary_type).is_a?(Symbol))
if arry_type.respond_to? :to_native
ary.each {|item| ptr.write_pointer(arry_type.to_native(item, nil)) }
elsif arry_type.method_defined? :bytes
ptr.write_bytes(ary.map {|item| item.respond.bytes }.join)
elsif arry_type.method_defined? :pointer
ary.each do |item|
if item.size == item.pointer.size
ptr.write_bytes((itm_ptr = item.pointer).read_bytes(itm_ptr.size))
else
raise ArgumentError, "Cannot reliably convert `#{item}' to a native_type"
end
end
else
raise ArgumentError, "Cannot reliably convert `#{arry_type}' to a native_type"
end
else
Utils.put_array_typedef(ptr, arry_type, ary)
end
update_ptr_cache
#self.ptr_cache_hash = @bytes.hash # @FIXME ptr_hash() and @bytes.hash should be the same...
end | ruby | def update_ptr
ptr.clear
if (not (arry_type = self.class.ary_type).is_a?(Symbol))
if arry_type.respond_to? :to_native
ary.each {|item| ptr.write_pointer(arry_type.to_native(item, nil)) }
elsif arry_type.method_defined? :bytes
ptr.write_bytes(ary.map {|item| item.respond.bytes }.join)
elsif arry_type.method_defined? :pointer
ary.each do |item|
if item.size == item.pointer.size
ptr.write_bytes((itm_ptr = item.pointer).read_bytes(itm_ptr.size))
else
raise ArgumentError, "Cannot reliably convert `#{item}' to a native_type"
end
end
else
raise ArgumentError, "Cannot reliably convert `#{arry_type}' to a native_type"
end
else
Utils.put_array_typedef(ptr, arry_type, ary)
end
update_ptr_cache
#self.ptr_cache_hash = @bytes.hash # @FIXME ptr_hash() and @bytes.hash should be the same...
end | [
"def",
"update_ptr",
"ptr",
".",
"clear",
"if",
"(",
"not",
"(",
"arry_type",
"=",
"self",
".",
"class",
".",
"ary_type",
")",
".",
"is_a?",
"(",
"Symbol",
")",
")",
"if",
"arry_type",
".",
"respond_to?",
":to_native",
"ary",
".",
"each",
"{",
"|",
"item",
"|",
"ptr",
".",
"write_pointer",
"(",
"arry_type",
".",
"to_native",
"(",
"item",
",",
"nil",
")",
")",
"}",
"elsif",
"arry_type",
".",
"method_defined?",
":bytes",
"ptr",
".",
"write_bytes",
"(",
"ary",
".",
"map",
"{",
"|",
"item",
"|",
"item",
".",
"respond",
".",
"bytes",
"}",
".",
"join",
")",
"elsif",
"arry_type",
".",
"method_defined?",
":pointer",
"ary",
".",
"each",
"do",
"|",
"item",
"|",
"if",
"item",
".",
"size",
"==",
"item",
".",
"pointer",
".",
"size",
"ptr",
".",
"write_bytes",
"(",
"(",
"itm_ptr",
"=",
"item",
".",
"pointer",
")",
".",
"read_bytes",
"(",
"itm_ptr",
".",
"size",
")",
")",
"else",
"raise",
"ArgumentError",
",",
"\"Cannot reliably convert `#{item}' to a native_type\"",
"end",
"end",
"else",
"raise",
"ArgumentError",
",",
"\"Cannot reliably convert `#{arry_type}' to a native_type\"",
"end",
"else",
"Utils",
".",
"put_array_typedef",
"(",
"ptr",
",",
"arry_type",
",",
"ary",
")",
"end",
"update_ptr_cache",
"end"
] | this is slightly dangerous, if anything was still pointing to old pointer location
now its being reclaimed, this will change it
@return [Integer] hash | [
"this",
"is",
"slightly",
"dangerous",
"if",
"anything",
"was",
"still",
"pointing",
"to",
"old",
"pointer",
"location",
"now",
"its",
"being",
"reclaimed",
"this",
"will",
"change",
"it"
] | 4ce72bd01980ed9049e8c03c3d1437f1d4d0de7a | https://github.com/jtzero/vigilem-support/blob/4ce72bd01980ed9049e8c03c3d1437f1d4d0de7a/lib/vigilem/ffi/array_pointer_sync.rb#L323-L346 | train |
essfeed/ruby-ess | lib/ess/element.rb | ESS.Element.method_missing | def method_missing m, *args, &block
if method_name_is_tag_name? m
return assign_tag(m, args, &block)
elsif method_name_is_tag_adder_method? m
return extend_tag_list(m, args, &block)
elsif method_name_is_tag_list_method? m
return child_tags[m[0..-6].to_sym] ||= []
elsif method_name_is_attr_accessor_method? m
return assign_attribute(m[0..-6].to_sym, args, &block)
end
super(m, *args, &block)
end | ruby | def method_missing m, *args, &block
if method_name_is_tag_name? m
return assign_tag(m, args, &block)
elsif method_name_is_tag_adder_method? m
return extend_tag_list(m, args, &block)
elsif method_name_is_tag_list_method? m
return child_tags[m[0..-6].to_sym] ||= []
elsif method_name_is_attr_accessor_method? m
return assign_attribute(m[0..-6].to_sym, args, &block)
end
super(m, *args, &block)
end | [
"def",
"method_missing",
"m",
",",
"*",
"args",
",",
"&",
"block",
"if",
"method_name_is_tag_name?",
"m",
"return",
"assign_tag",
"(",
"m",
",",
"args",
",",
"&",
"block",
")",
"elsif",
"method_name_is_tag_adder_method?",
"m",
"return",
"extend_tag_list",
"(",
"m",
",",
"args",
",",
"&",
"block",
")",
"elsif",
"method_name_is_tag_list_method?",
"m",
"return",
"child_tags",
"[",
"m",
"[",
"0",
"..",
"-",
"6",
"]",
".",
"to_sym",
"]",
"||=",
"[",
"]",
"elsif",
"method_name_is_attr_accessor_method?",
"m",
"return",
"assign_attribute",
"(",
"m",
"[",
"0",
"..",
"-",
"6",
"]",
".",
"to_sym",
",",
"args",
",",
"&",
"block",
")",
"end",
"super",
"(",
"m",
",",
"*",
"args",
",",
"&",
"block",
")",
"end"
] | Handles methods corresponding to a tag name, ending with either
_list or _attr, or starting with add_ . | [
"Handles",
"methods",
"corresponding",
"to",
"a",
"tag",
"name",
"ending",
"with",
"either",
"_list",
"or",
"_attr",
"or",
"starting",
"with",
"add_",
"."
] | 25708228acd64e4abd0557e323f6e6adabf6e930 | https://github.com/essfeed/ruby-ess/blob/25708228acd64e4abd0557e323f6e6adabf6e930/lib/ess/element.rb#L149-L160 | train |
mkulumadzi/mediawiki-keiki | lib/mediawiki-keiki/page.rb | MediaWiki.Page.summary | def summary
text_array = to_text.split("\n")
text = text_array[0]
i = 1
while text.length <= 140 && i < text_array.length
text << "\n" + text_array[i]
i += 1
end
text
end | ruby | def summary
text_array = to_text.split("\n")
text = text_array[0]
i = 1
while text.length <= 140 && i < text_array.length
text << "\n" + text_array[i]
i += 1
end
text
end | [
"def",
"summary",
"text_array",
"=",
"to_text",
".",
"split",
"(",
"\"\\n\"",
")",
"text",
"=",
"text_array",
"[",
"0",
"]",
"i",
"=",
"1",
"while",
"text",
".",
"length",
"<=",
"140",
"&&",
"i",
"<",
"text_array",
".",
"length",
"text",
"<<",
"\"\\n\"",
"+",
"text_array",
"[",
"i",
"]",
"i",
"+=",
"1",
"end",
"text",
"end"
] | Returns a short summary that is at least 140 characters long | [
"Returns",
"a",
"short",
"summary",
"that",
"is",
"at",
"least",
"140",
"characters",
"long"
] | 849338f643543f3a432d209f0413346d513c1e81 | https://github.com/mkulumadzi/mediawiki-keiki/blob/849338f643543f3a432d209f0413346d513c1e81/lib/mediawiki-keiki/page.rb#L36-L48 | train |
chingor13/oauth_provider_engine | app/models/oauth_provider_engine/request_token.rb | OauthProviderEngine.RequestToken.upgrade! | def upgrade!
access_token = nil
transaction do
access_token = OauthProviderEngine::AccessToken.create!({
:application_id => self.application_id,
:user_id => self.user_id,
})
self.destroy || raise(ActiveRecord::Rollback)
end
return access_token
end | ruby | def upgrade!
access_token = nil
transaction do
access_token = OauthProviderEngine::AccessToken.create!({
:application_id => self.application_id,
:user_id => self.user_id,
})
self.destroy || raise(ActiveRecord::Rollback)
end
return access_token
end | [
"def",
"upgrade!",
"access_token",
"=",
"nil",
"transaction",
"do",
"access_token",
"=",
"OauthProviderEngine",
"::",
"AccessToken",
".",
"create!",
"(",
"{",
":application_id",
"=>",
"self",
".",
"application_id",
",",
":user_id",
"=>",
"self",
".",
"user_id",
",",
"}",
")",
"self",
".",
"destroy",
"||",
"raise",
"(",
"ActiveRecord",
"::",
"Rollback",
")",
"end",
"return",
"access_token",
"end"
] | this method with upgrade the RequestToken to an AccessToken
note that this will destroy the current RequestToken | [
"this",
"method",
"with",
"upgrade",
"the",
"RequestToken",
"to",
"an",
"AccessToken",
"note",
"that",
"this",
"will",
"destroy",
"the",
"current",
"RequestToken"
] | 3e742fd15834fa209d7289637e993f4061aa406e | https://github.com/chingor13/oauth_provider_engine/blob/3e742fd15834fa209d7289637e993f4061aa406e/app/models/oauth_provider_engine/request_token.rb#L18-L28 | train |
ddrscott/sort_index | lib/sort_index/file.rb | SortIndex.File.sorted_puts | def sorted_puts(line)
if line == nil || line.size == 0
raise ArgumentError, 'Line cannot be blank!'
end
if line.index($/)
raise ArgumentError, "Cannot `puts` a line with extra line endings. Make sure the line does not contain `#{$/.inspect}`"
end
matched, idx = binary_seek(line)
if matched
# an exact match was found, nothing to do
else
if idx == nil
# append to end of file
self.seek(0, IO::SEEK_END)
puts(line)
else
self.seek(cached_positions[idx][0], IO::SEEK_SET)
do_at_current_position{puts(line)}
end
update_cached_position(idx, line)
end
nil
end | ruby | def sorted_puts(line)
if line == nil || line.size == 0
raise ArgumentError, 'Line cannot be blank!'
end
if line.index($/)
raise ArgumentError, "Cannot `puts` a line with extra line endings. Make sure the line does not contain `#{$/.inspect}`"
end
matched, idx = binary_seek(line)
if matched
# an exact match was found, nothing to do
else
if idx == nil
# append to end of file
self.seek(0, IO::SEEK_END)
puts(line)
else
self.seek(cached_positions[idx][0], IO::SEEK_SET)
do_at_current_position{puts(line)}
end
update_cached_position(idx, line)
end
nil
end | [
"def",
"sorted_puts",
"(",
"line",
")",
"if",
"line",
"==",
"nil",
"||",
"line",
".",
"size",
"==",
"0",
"raise",
"ArgumentError",
",",
"'Line cannot be blank!'",
"end",
"if",
"line",
".",
"index",
"(",
"$/",
")",
"raise",
"ArgumentError",
",",
"\"Cannot `puts` a line with extra line endings. Make sure the line does not contain `#{$/.inspect}`\"",
"end",
"matched",
",",
"idx",
"=",
"binary_seek",
"(",
"line",
")",
"if",
"matched",
"else",
"if",
"idx",
"==",
"nil",
"self",
".",
"seek",
"(",
"0",
",",
"IO",
"::",
"SEEK_END",
")",
"puts",
"(",
"line",
")",
"else",
"self",
".",
"seek",
"(",
"cached_positions",
"[",
"idx",
"]",
"[",
"0",
"]",
",",
"IO",
"::",
"SEEK_SET",
")",
"do_at_current_position",
"{",
"puts",
"(",
"line",
")",
"}",
"end",
"update_cached_position",
"(",
"idx",
",",
"line",
")",
"end",
"nil",
"end"
] | adds the line to the while maintaining the data's sort order
@param [String] line to add to the file, it should not have it's own line ending.
@return [Nil] always returns nil to match standard #puts method | [
"adds",
"the",
"line",
"to",
"the",
"while",
"maintaining",
"the",
"data",
"s",
"sort",
"order"
] | f414152668216f6d4371a9fee7da4b3600765346 | https://github.com/ddrscott/sort_index/blob/f414152668216f6d4371a9fee7da4b3600765346/lib/sort_index/file.rb#L8-L32 | train |
ddrscott/sort_index | lib/sort_index/file.rb | SortIndex.File.index_each_line | def index_each_line
positions = []
size = 0
each_line do |line|
positions << [size, line.size]
size += line.size
end
rewind
positions
end | ruby | def index_each_line
positions = []
size = 0
each_line do |line|
positions << [size, line.size]
size += line.size
end
rewind
positions
end | [
"def",
"index_each_line",
"positions",
"=",
"[",
"]",
"size",
"=",
"0",
"each_line",
"do",
"|",
"line",
"|",
"positions",
"<<",
"[",
"size",
",",
"line",
".",
"size",
"]",
"size",
"+=",
"line",
".",
"size",
"end",
"rewind",
"positions",
"end"
] | Builds an Array of position and length of the current file.
@return [Array[Array[Fixnum,Fixnum]]] array of position, line length pairs | [
"Builds",
"an",
"Array",
"of",
"position",
"and",
"length",
"of",
"the",
"current",
"file",
"."
] | f414152668216f6d4371a9fee7da4b3600765346 | https://github.com/ddrscott/sort_index/blob/f414152668216f6d4371a9fee7da4b3600765346/lib/sort_index/file.rb#L38-L47 | train |
ddrscott/sort_index | lib/sort_index/file.rb | SortIndex.File.do_at_current_position | def do_at_current_position(&block)
current_position = self.tell
huge_buffer = self.read
self.seek(current_position, IO::SEEK_SET)
block.call
ensure
self.write huge_buffer
end | ruby | def do_at_current_position(&block)
current_position = self.tell
huge_buffer = self.read
self.seek(current_position, IO::SEEK_SET)
block.call
ensure
self.write huge_buffer
end | [
"def",
"do_at_current_position",
"(",
"&",
"block",
")",
"current_position",
"=",
"self",
".",
"tell",
"huge_buffer",
"=",
"self",
".",
"read",
"self",
".",
"seek",
"(",
"current_position",
",",
"IO",
"::",
"SEEK_SET",
")",
"block",
".",
"call",
"ensure",
"self",
".",
"write",
"huge_buffer",
"end"
] | remembers current file position, reads everything at the position
execute the block, and put everything back.
This routine is really bad for huge files since it could run out of
memory. | [
"remembers",
"current",
"file",
"position",
"reads",
"everything",
"at",
"the",
"position",
"execute",
"the",
"block",
"and",
"put",
"everything",
"back",
".",
"This",
"routine",
"is",
"really",
"bad",
"for",
"huge",
"files",
"since",
"it",
"could",
"run",
"out",
"of",
"memory",
"."
] | f414152668216f6d4371a9fee7da4b3600765346 | https://github.com/ddrscott/sort_index/blob/f414152668216f6d4371a9fee7da4b3600765346/lib/sort_index/file.rb#L53-L60 | train |
thebigdb/thebigdb-ruby | lib/thebigdb/request.rb | TheBigDB.Request.prepare | def prepare(method, request_uri, params = {})
method = method.downcase.to_s
if TheBigDB.api_key.is_a?(String) and !TheBigDB.api_key.empty?
params.merge!("api_key" => TheBigDB.api_key)
end
# we add the API version to the URL, with a trailing slash and the rest of the request
request_uri = "/v#{TheBigDB.api_version}" + (request_uri.start_with?("/") ? request_uri : "/#{request_uri}")
if method == "get"
encoded_params = TheBigDB::Helpers::serialize_query_params(params)
@http_request = Net::HTTP::Get.new(request_uri + "?" + encoded_params)
elsif method == "post"
@http_request = Net::HTTP::Post.new(request_uri)
@http_request.set_form_data(TheBigDB::Helpers::flatten_params_keys(params))
else
raise ArgumentError, "The request method must be 'get' or 'post'"
end
@http_request["user-agent"] = "TheBigDB RubyWrapper/#{TheBigDB::VERSION::STRING}"
client_user_agent = {
"publisher" => "thebigdb",
"version" => TheBigDB::VERSION::STRING,
"language" => "ruby",
"language_version" => "#{RUBY_VERSION} p#{RUBY_PATCHLEVEL} (#{RUBY_RELEASE_DATE})",
}
@http_request["X-TheBigDB-Client-User-Agent"] = JSON(client_user_agent)
self
end | ruby | def prepare(method, request_uri, params = {})
method = method.downcase.to_s
if TheBigDB.api_key.is_a?(String) and !TheBigDB.api_key.empty?
params.merge!("api_key" => TheBigDB.api_key)
end
# we add the API version to the URL, with a trailing slash and the rest of the request
request_uri = "/v#{TheBigDB.api_version}" + (request_uri.start_with?("/") ? request_uri : "/#{request_uri}")
if method == "get"
encoded_params = TheBigDB::Helpers::serialize_query_params(params)
@http_request = Net::HTTP::Get.new(request_uri + "?" + encoded_params)
elsif method == "post"
@http_request = Net::HTTP::Post.new(request_uri)
@http_request.set_form_data(TheBigDB::Helpers::flatten_params_keys(params))
else
raise ArgumentError, "The request method must be 'get' or 'post'"
end
@http_request["user-agent"] = "TheBigDB RubyWrapper/#{TheBigDB::VERSION::STRING}"
client_user_agent = {
"publisher" => "thebigdb",
"version" => TheBigDB::VERSION::STRING,
"language" => "ruby",
"language_version" => "#{RUBY_VERSION} p#{RUBY_PATCHLEVEL} (#{RUBY_RELEASE_DATE})",
}
@http_request["X-TheBigDB-Client-User-Agent"] = JSON(client_user_agent)
self
end | [
"def",
"prepare",
"(",
"method",
",",
"request_uri",
",",
"params",
"=",
"{",
"}",
")",
"method",
"=",
"method",
".",
"downcase",
".",
"to_s",
"if",
"TheBigDB",
".",
"api_key",
".",
"is_a?",
"(",
"String",
")",
"and",
"!",
"TheBigDB",
".",
"api_key",
".",
"empty?",
"params",
".",
"merge!",
"(",
"\"api_key\"",
"=>",
"TheBigDB",
".",
"api_key",
")",
"end",
"request_uri",
"=",
"\"/v#{TheBigDB.api_version}\"",
"+",
"(",
"request_uri",
".",
"start_with?",
"(",
"\"/\"",
")",
"?",
"request_uri",
":",
"\"/#{request_uri}\"",
")",
"if",
"method",
"==",
"\"get\"",
"encoded_params",
"=",
"TheBigDB",
"::",
"Helpers",
"::",
"serialize_query_params",
"(",
"params",
")",
"@http_request",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"request_uri",
"+",
"\"?\"",
"+",
"encoded_params",
")",
"elsif",
"method",
"==",
"\"post\"",
"@http_request",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"request_uri",
")",
"@http_request",
".",
"set_form_data",
"(",
"TheBigDB",
"::",
"Helpers",
"::",
"flatten_params_keys",
"(",
"params",
")",
")",
"else",
"raise",
"ArgumentError",
",",
"\"The request method must be 'get' or 'post'\"",
"end",
"@http_request",
"[",
"\"user-agent\"",
"]",
"=",
"\"TheBigDB RubyWrapper/#{TheBigDB::VERSION::STRING}\"",
"client_user_agent",
"=",
"{",
"\"publisher\"",
"=>",
"\"thebigdb\"",
",",
"\"version\"",
"=>",
"TheBigDB",
"::",
"VERSION",
"::",
"STRING",
",",
"\"language\"",
"=>",
"\"ruby\"",
",",
"\"language_version\"",
"=>",
"\"#{RUBY_VERSION} p#{RUBY_PATCHLEVEL} (#{RUBY_RELEASE_DATE})\"",
",",
"}",
"@http_request",
"[",
"\"X-TheBigDB-Client-User-Agent\"",
"]",
"=",
"JSON",
"(",
"client_user_agent",
")",
"self",
"end"
] | Prepares the basic @http object with the current values of the module (host, port, ...)
Prepares the @http_request object with the actual content of the request | [
"Prepares",
"the",
"basic"
] | 6c978e3b0712af43529f36c3324ff583bd133df8 | https://github.com/thebigdb/thebigdb-ruby/blob/6c978e3b0712af43529f36c3324ff583bd133df8/lib/thebigdb/request.rb#L22-L54 | train |
thebigdb/thebigdb-ruby | lib/thebigdb/request.rb | TheBigDB.Request.execute | def execute
# Here is the order of operations:
# -> setting @data_sent
# -> executing before_request_execution callback
# -> executing the HTTP request
# -> setting @response
# -> setting @data_received
# -> executing after_request_execution callback
# Setting @data_sent
params = Rack::Utils.parse_nested_query(URI.parse(@http_request.path).query)
# Since that's how it will be interpreted anyway on the server, we merge the POST params to the GET params,
# but it's not supposed to happen: either every params is prepared for GET/query params, or as POST body
params.merge!(Rack::Utils.parse_nested_query(@http_request.body.to_s))
# About: Hash[{}.map{|k,v| [k, v.join] }]
# it transforms the following hash:
# {"accept"=>["*/*"], "user-agent"=>["TheBigDB RubyWrapper/X.Y.Z"], "host"=>["computer.host"]}
# into the following hash:
# {"accept"=>"*/*", "user-agent"=>"TheBigDB RubyWrapper/X.Y.Z", "host"=>"computer.host"}
# which is way more useful and cleaner.
@data_sent = {
"headers" => Hash[@http_request.to_hash.map{|k,v| [k, v.join] }],
"host" => @http.address,
"port" => @http.port,
"path" => URI.parse(@http_request.path).path,
"method" => @http_request.method,
"params" => params
}
# Executing callback
TheBigDB.before_request_execution.call(self)
# Here is where the request is actually executed
@http_response = TheBigDB.http_request_executor.call(@http, @http_request)
# Setting @response
begin
# We parse the JSON answer and return it.
@response = JSON(@http_response.body)
rescue JSON::ParserError => e
@response = {"status" => "error", "error" => {"code" => "0000", "description" => "The server gave an invalid JSON body:\n#{@http_response.body}"}}
end
# Setting @data_received
@data_received = {
"headers" => Hash[@http_response.to_hash.map{|k,v| [k, v.join] }],
"content" => @response
}
# Executing callback
TheBigDB.after_request_execution.call(self)
# Raising exception if asked
if TheBigDB.raise_on_api_status_error and @response["status"] == "error"
raise ApiStatusError.new(@response["error"]["code"])
end
self
end | ruby | def execute
# Here is the order of operations:
# -> setting @data_sent
# -> executing before_request_execution callback
# -> executing the HTTP request
# -> setting @response
# -> setting @data_received
# -> executing after_request_execution callback
# Setting @data_sent
params = Rack::Utils.parse_nested_query(URI.parse(@http_request.path).query)
# Since that's how it will be interpreted anyway on the server, we merge the POST params to the GET params,
# but it's not supposed to happen: either every params is prepared for GET/query params, or as POST body
params.merge!(Rack::Utils.parse_nested_query(@http_request.body.to_s))
# About: Hash[{}.map{|k,v| [k, v.join] }]
# it transforms the following hash:
# {"accept"=>["*/*"], "user-agent"=>["TheBigDB RubyWrapper/X.Y.Z"], "host"=>["computer.host"]}
# into the following hash:
# {"accept"=>"*/*", "user-agent"=>"TheBigDB RubyWrapper/X.Y.Z", "host"=>"computer.host"}
# which is way more useful and cleaner.
@data_sent = {
"headers" => Hash[@http_request.to_hash.map{|k,v| [k, v.join] }],
"host" => @http.address,
"port" => @http.port,
"path" => URI.parse(@http_request.path).path,
"method" => @http_request.method,
"params" => params
}
# Executing callback
TheBigDB.before_request_execution.call(self)
# Here is where the request is actually executed
@http_response = TheBigDB.http_request_executor.call(@http, @http_request)
# Setting @response
begin
# We parse the JSON answer and return it.
@response = JSON(@http_response.body)
rescue JSON::ParserError => e
@response = {"status" => "error", "error" => {"code" => "0000", "description" => "The server gave an invalid JSON body:\n#{@http_response.body}"}}
end
# Setting @data_received
@data_received = {
"headers" => Hash[@http_response.to_hash.map{|k,v| [k, v.join] }],
"content" => @response
}
# Executing callback
TheBigDB.after_request_execution.call(self)
# Raising exception if asked
if TheBigDB.raise_on_api_status_error and @response["status"] == "error"
raise ApiStatusError.new(@response["error"]["code"])
end
self
end | [
"def",
"execute",
"params",
"=",
"Rack",
"::",
"Utils",
".",
"parse_nested_query",
"(",
"URI",
".",
"parse",
"(",
"@http_request",
".",
"path",
")",
".",
"query",
")",
"params",
".",
"merge!",
"(",
"Rack",
"::",
"Utils",
".",
"parse_nested_query",
"(",
"@http_request",
".",
"body",
".",
"to_s",
")",
")",
"@data_sent",
"=",
"{",
"\"headers\"",
"=>",
"Hash",
"[",
"@http_request",
".",
"to_hash",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"[",
"k",
",",
"v",
".",
"join",
"]",
"}",
"]",
",",
"\"host\"",
"=>",
"@http",
".",
"address",
",",
"\"port\"",
"=>",
"@http",
".",
"port",
",",
"\"path\"",
"=>",
"URI",
".",
"parse",
"(",
"@http_request",
".",
"path",
")",
".",
"path",
",",
"\"method\"",
"=>",
"@http_request",
".",
"method",
",",
"\"params\"",
"=>",
"params",
"}",
"TheBigDB",
".",
"before_request_execution",
".",
"call",
"(",
"self",
")",
"@http_response",
"=",
"TheBigDB",
".",
"http_request_executor",
".",
"call",
"(",
"@http",
",",
"@http_request",
")",
"begin",
"@response",
"=",
"JSON",
"(",
"@http_response",
".",
"body",
")",
"rescue",
"JSON",
"::",
"ParserError",
"=>",
"e",
"@response",
"=",
"{",
"\"status\"",
"=>",
"\"error\"",
",",
"\"error\"",
"=>",
"{",
"\"code\"",
"=>",
"\"0000\"",
",",
"\"description\"",
"=>",
"\"The server gave an invalid JSON body:\\n#{@http_response.body}\"",
"}",
"}",
"end",
"@data_received",
"=",
"{",
"\"headers\"",
"=>",
"Hash",
"[",
"@http_response",
".",
"to_hash",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"[",
"k",
",",
"v",
".",
"join",
"]",
"}",
"]",
",",
"\"content\"",
"=>",
"@response",
"}",
"TheBigDB",
".",
"after_request_execution",
".",
"call",
"(",
"self",
")",
"if",
"TheBigDB",
".",
"raise_on_api_status_error",
"and",
"@response",
"[",
"\"status\"",
"]",
"==",
"\"error\"",
"raise",
"ApiStatusError",
".",
"new",
"(",
"@response",
"[",
"\"error\"",
"]",
"[",
"\"code\"",
"]",
")",
"end",
"self",
"end"
] | Actually makes the request prepared in @http_request, and sets @http_response | [
"Actually",
"makes",
"the",
"request",
"prepared",
"in"
] | 6c978e3b0712af43529f36c3324ff583bd133df8 | https://github.com/thebigdb/thebigdb-ruby/blob/6c978e3b0712af43529f36c3324ff583bd133df8/lib/thebigdb/request.rb#L57-L116 | train |
NUBIC/aker | lib/aker/group_membership.rb | Aker.GroupMemberships.find | def find(group, *affiliate_ids)
candidates = self.select { |gm| gm.group.include?(group) }
return candidates if affiliate_ids.empty?
candidates.select { |gm| affiliate_ids.detect { |id| gm.include_affiliate?(id) } }
end | ruby | def find(group, *affiliate_ids)
candidates = self.select { |gm| gm.group.include?(group) }
return candidates if affiliate_ids.empty?
candidates.select { |gm| affiliate_ids.detect { |id| gm.include_affiliate?(id) } }
end | [
"def",
"find",
"(",
"group",
",",
"*",
"affiliate_ids",
")",
"candidates",
"=",
"self",
".",
"select",
"{",
"|",
"gm",
"|",
"gm",
".",
"group",
".",
"include?",
"(",
"group",
")",
"}",
"return",
"candidates",
"if",
"affiliate_ids",
".",
"empty?",
"candidates",
".",
"select",
"{",
"|",
"gm",
"|",
"affiliate_ids",
".",
"detect",
"{",
"|",
"id",
"|",
"gm",
".",
"include_affiliate?",
"(",
"id",
")",
"}",
"}",
"end"
] | Finds the group memberships that match the given group, possibly
constrained by one or more affiliates.
(Note that this method hides the `Enumerable` method `find`.
You can still use it under its `detect` alias.)
@param [Group,#to_s] group the group in question or its name
@param [Array<Object>,nil] *affiliate_ids the affiliates to use to
constrain the query.
@return [Array<GroupMembership>] | [
"Finds",
"the",
"group",
"memberships",
"that",
"match",
"the",
"given",
"group",
"possibly",
"constrained",
"by",
"one",
"or",
"more",
"affiliates",
"."
] | ff43606a8812e38f96bbe71b46e7f631cbeacf1c | https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/group_membership.rb#L108-L112 | train |
alfa-jpn/rails-kvs-driver | lib/rails_kvs_driver/session.rb | RailsKvsDriver.Session.session | def session(driver_config, &block)
driver_config = validate_driver_config!(driver_config)
driver_connection_pool(self, driver_config).with do |kvs_instance|
block.call(self.new(kvs_instance, driver_config))
end
end | ruby | def session(driver_config, &block)
driver_config = validate_driver_config!(driver_config)
driver_connection_pool(self, driver_config).with do |kvs_instance|
block.call(self.new(kvs_instance, driver_config))
end
end | [
"def",
"session",
"(",
"driver_config",
",",
"&",
"block",
")",
"driver_config",
"=",
"validate_driver_config!",
"(",
"driver_config",
")",
"driver_connection_pool",
"(",
"self",
",",
"driver_config",
")",
".",
"with",
"do",
"|",
"kvs_instance",
"|",
"block",
".",
"call",
"(",
"self",
".",
"new",
"(",
"kvs_instance",
",",
"driver_config",
")",
")",
"end",
"end"
] | connect kvs and exec block.
This function pools the connecting driver.
@example
config = {
:host => 'localhost', # host of KVS.
:port => 6379, # port of KVS.
:namespace => 'Example', # namespace of avoid a conflict with key
:timeout_sec => 5, # timeout seconds.
:pool_size => 5, # connection pool size.
:config_key => :none # this key is option.(defaults=:none)
# when set this key.
# will refer to a connection-pool based on config_key,
# even if driver setting is the same without this key.
}
result = Driver.session(config) do |kvs|
kvs['example'] = 'abc'
kvs['example']
end
puts result # => 'abc'
@param driver_config [Hash] driver_config.
@param &block [{|driver_instance| #something... }] exec block.
@return [Object] status | [
"connect",
"kvs",
"and",
"exec",
"block",
".",
"This",
"function",
"pools",
"the",
"connecting",
"driver",
"."
] | 0eaf5c649071f9d82dc5f2ff2f4d7efcf32d8982 | https://github.com/alfa-jpn/rails-kvs-driver/blob/0eaf5c649071f9d82dc5f2ff2f4d7efcf32d8982/lib/rails_kvs_driver/session.rb#L43-L48 | train |
alfa-jpn/rails-kvs-driver | lib/rails_kvs_driver/session.rb | RailsKvsDriver.Session.driver_connection_pool | def driver_connection_pool(driver_class, driver_config)
pool = search_driver_connection_pool(driver_class, driver_config)
return (pool.nil?) ? set_driver_connection_pool(driver_class, driver_config) : pool
end | ruby | def driver_connection_pool(driver_class, driver_config)
pool = search_driver_connection_pool(driver_class, driver_config)
return (pool.nil?) ? set_driver_connection_pool(driver_class, driver_config) : pool
end | [
"def",
"driver_connection_pool",
"(",
"driver_class",
",",
"driver_config",
")",
"pool",
"=",
"search_driver_connection_pool",
"(",
"driver_class",
",",
"driver_config",
")",
"return",
"(",
"pool",
".",
"nil?",
")",
"?",
"set_driver_connection_pool",
"(",
"driver_class",
",",
"driver_config",
")",
":",
"pool",
"end"
] | get driver connection pool
if doesn't exist pool, it's made newly.
@param driver_class [RailsKvsDriver::Base] driver_class
@param driver_config [Hash] driver_config
@return [ConnectionPool] connection pool of driver | [
"get",
"driver",
"connection",
"pool",
"if",
"doesn",
"t",
"exist",
"pool",
"it",
"s",
"made",
"newly",
"."
] | 0eaf5c649071f9d82dc5f2ff2f4d7efcf32d8982 | https://github.com/alfa-jpn/rails-kvs-driver/blob/0eaf5c649071f9d82dc5f2ff2f4d7efcf32d8982/lib/rails_kvs_driver/session.rb#L58-L61 | train |
alfa-jpn/rails-kvs-driver | lib/rails_kvs_driver/session.rb | RailsKvsDriver.Session.set_driver_connection_pool | def set_driver_connection_pool(driver_class, driver_config)
conf = {
size: driver_config[:pool_size],
timeout: driver_config[:timeout_sec]
}
pool = ConnectionPool.new(conf) { driver_class.connect(driver_config) }
RailsKvsDriver::KVS_CONNECTION_POOL[driver_class.name] ||= Array.new
RailsKvsDriver::KVS_CONNECTION_POOL[driver_class.name].push({config: driver_config, pool: pool})
return pool
end | ruby | def set_driver_connection_pool(driver_class, driver_config)
conf = {
size: driver_config[:pool_size],
timeout: driver_config[:timeout_sec]
}
pool = ConnectionPool.new(conf) { driver_class.connect(driver_config) }
RailsKvsDriver::KVS_CONNECTION_POOL[driver_class.name] ||= Array.new
RailsKvsDriver::KVS_CONNECTION_POOL[driver_class.name].push({config: driver_config, pool: pool})
return pool
end | [
"def",
"set_driver_connection_pool",
"(",
"driver_class",
",",
"driver_config",
")",
"conf",
"=",
"{",
"size",
":",
"driver_config",
"[",
":pool_size",
"]",
",",
"timeout",
":",
"driver_config",
"[",
":timeout_sec",
"]",
"}",
"pool",
"=",
"ConnectionPool",
".",
"new",
"(",
"conf",
")",
"{",
"driver_class",
".",
"connect",
"(",
"driver_config",
")",
"}",
"RailsKvsDriver",
"::",
"KVS_CONNECTION_POOL",
"[",
"driver_class",
".",
"name",
"]",
"||=",
"Array",
".",
"new",
"RailsKvsDriver",
"::",
"KVS_CONNECTION_POOL",
"[",
"driver_class",
".",
"name",
"]",
".",
"push",
"(",
"{",
"config",
":",
"driver_config",
",",
"pool",
":",
"pool",
"}",
")",
"return",
"pool",
"end"
] | set driver connection pool
@param driver_class [RailsKvsDriver::Base] driver_class
@param driver_config [Hash] driver_config
@return [ConnectionPool] connection pool of driver | [
"set",
"driver",
"connection",
"pool"
] | 0eaf5c649071f9d82dc5f2ff2f4d7efcf32d8982 | https://github.com/alfa-jpn/rails-kvs-driver/blob/0eaf5c649071f9d82dc5f2ff2f4d7efcf32d8982/lib/rails_kvs_driver/session.rb#L68-L79 | train |
alfa-jpn/rails-kvs-driver | lib/rails_kvs_driver/session.rb | RailsKvsDriver.Session.search_driver_connection_pool | def search_driver_connection_pool(driver_class, driver_config)
if RailsKvsDriver::KVS_CONNECTION_POOL.has_key?(driver_class.name)
RailsKvsDriver::KVS_CONNECTION_POOL[driver_class.name].each do |pool_set|
return pool_set[:pool] if equal_driver_config?(pool_set[:config], driver_config)
end
end
return nil
end | ruby | def search_driver_connection_pool(driver_class, driver_config)
if RailsKvsDriver::KVS_CONNECTION_POOL.has_key?(driver_class.name)
RailsKvsDriver::KVS_CONNECTION_POOL[driver_class.name].each do |pool_set|
return pool_set[:pool] if equal_driver_config?(pool_set[:config], driver_config)
end
end
return nil
end | [
"def",
"search_driver_connection_pool",
"(",
"driver_class",
",",
"driver_config",
")",
"if",
"RailsKvsDriver",
"::",
"KVS_CONNECTION_POOL",
".",
"has_key?",
"(",
"driver_class",
".",
"name",
")",
"RailsKvsDriver",
"::",
"KVS_CONNECTION_POOL",
"[",
"driver_class",
".",
"name",
"]",
".",
"each",
"do",
"|",
"pool_set",
"|",
"return",
"pool_set",
"[",
":pool",
"]",
"if",
"equal_driver_config?",
"(",
"pool_set",
"[",
":config",
"]",
",",
"driver_config",
")",
"end",
"end",
"return",
"nil",
"end"
] | search driver connection pool
@param driver_class [RailsKvsDriver::Base] driver_class
@param driver_config [Hash] driver_config
@return [ConnectionPool] connection pool of driver, or nil | [
"search",
"driver",
"connection",
"pool"
] | 0eaf5c649071f9d82dc5f2ff2f4d7efcf32d8982 | https://github.com/alfa-jpn/rails-kvs-driver/blob/0eaf5c649071f9d82dc5f2ff2f4d7efcf32d8982/lib/rails_kvs_driver/session.rb#L86-L94 | train |
alfa-jpn/rails-kvs-driver | lib/rails_kvs_driver/session.rb | RailsKvsDriver.Session.equal_driver_config? | def equal_driver_config?(config1, config2)
return false unless config1[:host] == config2[:host]
return false unless config1[:port] == config2[:port]
return false unless config1[:timeout_sec] == config2[:timeout_sec]
return false unless config1[:pool_size] == config2[:pool_size]
return false unless config1[:config_key] == config2[:config_key]
return true
end | ruby | def equal_driver_config?(config1, config2)
return false unless config1[:host] == config2[:host]
return false unless config1[:port] == config2[:port]
return false unless config1[:timeout_sec] == config2[:timeout_sec]
return false unless config1[:pool_size] == config2[:pool_size]
return false unless config1[:config_key] == config2[:config_key]
return true
end | [
"def",
"equal_driver_config?",
"(",
"config1",
",",
"config2",
")",
"return",
"false",
"unless",
"config1",
"[",
":host",
"]",
"==",
"config2",
"[",
":host",
"]",
"return",
"false",
"unless",
"config1",
"[",
":port",
"]",
"==",
"config2",
"[",
":port",
"]",
"return",
"false",
"unless",
"config1",
"[",
":timeout_sec",
"]",
"==",
"config2",
"[",
":timeout_sec",
"]",
"return",
"false",
"unless",
"config1",
"[",
":pool_size",
"]",
"==",
"config2",
"[",
":pool_size",
"]",
"return",
"false",
"unless",
"config1",
"[",
":config_key",
"]",
"==",
"config2",
"[",
":config_key",
"]",
"return",
"true",
"end"
] | compare driver config.
@param config1 [Hash] driver config
@param config2 [Hash] driver config | [
"compare",
"driver",
"config",
"."
] | 0eaf5c649071f9d82dc5f2ff2f4d7efcf32d8982 | https://github.com/alfa-jpn/rails-kvs-driver/blob/0eaf5c649071f9d82dc5f2ff2f4d7efcf32d8982/lib/rails_kvs_driver/session.rb#L100-L107 | train |
mgsnova/crisp | lib/crisp/function_runner.rb | Crisp.FunctionRunner.validate_args_count | def validate_args_count(expected, got)
if (expected.is_a?(Numeric) and expected != got) or
(expected.is_a?(Range) and !(expected === got))
raise ArgumentError, "wrong number of arguments for '#{name}' (#{got} for #{expected})"
end
end | ruby | def validate_args_count(expected, got)
if (expected.is_a?(Numeric) and expected != got) or
(expected.is_a?(Range) and !(expected === got))
raise ArgumentError, "wrong number of arguments for '#{name}' (#{got} for #{expected})"
end
end | [
"def",
"validate_args_count",
"(",
"expected",
",",
"got",
")",
"if",
"(",
"expected",
".",
"is_a?",
"(",
"Numeric",
")",
"and",
"expected",
"!=",
"got",
")",
"or",
"(",
"expected",
".",
"is_a?",
"(",
"Range",
")",
"and",
"!",
"(",
"expected",
"===",
"got",
")",
")",
"raise",
"ArgumentError",
",",
"\"wrong number of arguments for '#{name}' (#{got} for #{expected})\"",
"end",
"end"
] | following methods are used for calling from the function block
raise an error if argument count got does not match the expected | [
"following",
"methods",
"are",
"used",
"for",
"calling",
"from",
"the",
"function",
"block",
"raise",
"an",
"error",
"if",
"argument",
"count",
"got",
"does",
"not",
"match",
"the",
"expected"
] | 0b3695de59258971b8b39998602c5b6e9f10623b | https://github.com/mgsnova/crisp/blob/0b3695de59258971b8b39998602c5b6e9f10623b/lib/crisp/function_runner.rb#L23-L28 | train |
FineLinePrototyping/irie | lib/irie/class_methods.rb | Irie.ClassMethods.extensions! | def extensions!(*extension_syms)
return extension_syms if extension_syms.length == 0
extension_syms = extension_syms.flatten.collect {|es| es.to_sym}.compact
if extension_syms.include?(:all)
ordered_extension_syms = self.extension_include_order.dup
else
extensions_without_defined_order = extension_syms.uniq - self.extension_include_order.uniq
if extensions_without_defined_order.length > 0
raise ::Irie::ConfigurationError.new "The following must be added to the self.extension_include_order array in Irie configuration: #{extensions_without_defined_order.collect(&:inspect).join(', ')}"
else
ordered_extension_syms = self.extension_include_order & extension_syms
end
end
# load requested extensions
ordered_extension_syms.each do |arg_sym|
if module_class_name = self.available_extensions[arg_sym]
begin
::Irie.logger.debug("[Irie] Irie::ClassMethods.extensions! #{self} including #{module_class_name}") if ::Irie.debug?
include module_class_name.constantize
rescue NameError => e
raise ::Irie::ConfigurationError.new "Failed to constantize '#{module_class_name}' with extension key #{arg_sym.inspect} in self.available_extensions. Error: \n#{e.message}\n#{e.backtrace.join("\n")}"
end
else
raise ::Irie::ConfigurationError.new "#{arg_sym.inspect} isn't defined in self.available_extensions"
end
end
extension_syms
end | ruby | def extensions!(*extension_syms)
return extension_syms if extension_syms.length == 0
extension_syms = extension_syms.flatten.collect {|es| es.to_sym}.compact
if extension_syms.include?(:all)
ordered_extension_syms = self.extension_include_order.dup
else
extensions_without_defined_order = extension_syms.uniq - self.extension_include_order.uniq
if extensions_without_defined_order.length > 0
raise ::Irie::ConfigurationError.new "The following must be added to the self.extension_include_order array in Irie configuration: #{extensions_without_defined_order.collect(&:inspect).join(', ')}"
else
ordered_extension_syms = self.extension_include_order & extension_syms
end
end
# load requested extensions
ordered_extension_syms.each do |arg_sym|
if module_class_name = self.available_extensions[arg_sym]
begin
::Irie.logger.debug("[Irie] Irie::ClassMethods.extensions! #{self} including #{module_class_name}") if ::Irie.debug?
include module_class_name.constantize
rescue NameError => e
raise ::Irie::ConfigurationError.new "Failed to constantize '#{module_class_name}' with extension key #{arg_sym.inspect} in self.available_extensions. Error: \n#{e.message}\n#{e.backtrace.join("\n")}"
end
else
raise ::Irie::ConfigurationError.new "#{arg_sym.inspect} isn't defined in self.available_extensions"
end
end
extension_syms
end | [
"def",
"extensions!",
"(",
"*",
"extension_syms",
")",
"return",
"extension_syms",
"if",
"extension_syms",
".",
"length",
"==",
"0",
"extension_syms",
"=",
"extension_syms",
".",
"flatten",
".",
"collect",
"{",
"|",
"es",
"|",
"es",
".",
"to_sym",
"}",
".",
"compact",
"if",
"extension_syms",
".",
"include?",
"(",
":all",
")",
"ordered_extension_syms",
"=",
"self",
".",
"extension_include_order",
".",
"dup",
"else",
"extensions_without_defined_order",
"=",
"extension_syms",
".",
"uniq",
"-",
"self",
".",
"extension_include_order",
".",
"uniq",
"if",
"extensions_without_defined_order",
".",
"length",
">",
"0",
"raise",
"::",
"Irie",
"::",
"ConfigurationError",
".",
"new",
"\"The following must be added to the self.extension_include_order array in Irie configuration: #{extensions_without_defined_order.collect(&:inspect).join(', ')}\"",
"else",
"ordered_extension_syms",
"=",
"self",
".",
"extension_include_order",
"&",
"extension_syms",
"end",
"end",
"ordered_extension_syms",
".",
"each",
"do",
"|",
"arg_sym",
"|",
"if",
"module_class_name",
"=",
"self",
".",
"available_extensions",
"[",
"arg_sym",
"]",
"begin",
"::",
"Irie",
".",
"logger",
".",
"debug",
"(",
"\"[Irie] Irie::ClassMethods.extensions! #{self} including #{module_class_name}\"",
")",
"if",
"::",
"Irie",
".",
"debug?",
"include",
"module_class_name",
".",
"constantize",
"rescue",
"NameError",
"=>",
"e",
"raise",
"::",
"Irie",
"::",
"ConfigurationError",
".",
"new",
"\"Failed to constantize '#{module_class_name}' with extension key #{arg_sym.inspect} in self.available_extensions. Error: \\n#{e.message}\\n#{e.backtrace.join(\"\\n\")}\"",
"end",
"else",
"raise",
"::",
"Irie",
"::",
"ConfigurationError",
".",
"new",
"\"#{arg_sym.inspect} isn't defined in self.available_extensions\"",
"end",
"end",
"extension_syms",
"end"
] | Load specified extensions in the order defined by self.extension_include_order. | [
"Load",
"specified",
"extensions",
"in",
"the",
"order",
"defined",
"by",
"self",
".",
"extension_include_order",
"."
] | 522cd66bb41461d1b4a6512ad32b8bd2ab1edb0f | https://github.com/FineLinePrototyping/irie/blob/522cd66bb41461d1b4a6512ad32b8bd2ab1edb0f/lib/irie/class_methods.rb#L28-L59 | train |
humpyard/humpyard | app/controllers/humpyard/elements_controller.rb | Humpyard.ElementsController.new | def new
@element = Humpyard::config.element_types[params[:type]].new(
:page_id => params[:page_id],
:container_id => params[:container_id].to_i > 0 ? params[:container_id].to_i : nil,
:page_yield_name => params[:yield_name].blank? ? 'main' : params[:yield_name],
:shared_state => 0)
authorize! :create, @element.element
@element_type = params[:type]
@prev = Humpyard::Element.find_by_id(params[:prev_id])
@next = Humpyard::Element.find_by_id(params[:next_id])
render :partial => 'edit'
end | ruby | def new
@element = Humpyard::config.element_types[params[:type]].new(
:page_id => params[:page_id],
:container_id => params[:container_id].to_i > 0 ? params[:container_id].to_i : nil,
:page_yield_name => params[:yield_name].blank? ? 'main' : params[:yield_name],
:shared_state => 0)
authorize! :create, @element.element
@element_type = params[:type]
@prev = Humpyard::Element.find_by_id(params[:prev_id])
@next = Humpyard::Element.find_by_id(params[:next_id])
render :partial => 'edit'
end | [
"def",
"new",
"@element",
"=",
"Humpyard",
"::",
"config",
".",
"element_types",
"[",
"params",
"[",
":type",
"]",
"]",
".",
"new",
"(",
":page_id",
"=>",
"params",
"[",
":page_id",
"]",
",",
":container_id",
"=>",
"params",
"[",
":container_id",
"]",
".",
"to_i",
">",
"0",
"?",
"params",
"[",
":container_id",
"]",
".",
"to_i",
":",
"nil",
",",
":page_yield_name",
"=>",
"params",
"[",
":yield_name",
"]",
".",
"blank?",
"?",
"'main'",
":",
"params",
"[",
":yield_name",
"]",
",",
":shared_state",
"=>",
"0",
")",
"authorize!",
":create",
",",
"@element",
".",
"element",
"@element_type",
"=",
"params",
"[",
":type",
"]",
"@prev",
"=",
"Humpyard",
"::",
"Element",
".",
"find_by_id",
"(",
"params",
"[",
":prev_id",
"]",
")",
"@next",
"=",
"Humpyard",
"::",
"Element",
".",
"find_by_id",
"(",
"params",
"[",
":next_id",
"]",
")",
"render",
":partial",
"=>",
"'edit'",
"end"
] | Dialog content for a new element | [
"Dialog",
"content",
"for",
"a",
"new",
"element"
] | f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd | https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/controllers/humpyard/elements_controller.rb#L7-L21 | train |
humpyard/humpyard | app/controllers/humpyard/elements_controller.rb | Humpyard.ElementsController.create | def create
@element = Humpyard::config.element_types[params[:type]].new params[:element]
unless can? :create, @element.element
render :json => {
:status => :failed
}, :status => 403
return
end
if @element.save
@prev = Humpyard::Element.find_by_id(params[:prev_id])
@next = Humpyard::Element.find_by_id(params[:next_id])
do_move(@element, @prev, @next)
insert_options = {
:element => "hy-id-#{@element.element.id}",
:url => humpyard_element_path(@element.element),
:parent => @element.container ? "hy-id-#{@element.container.id}" : "hy-content-#{@element.page_yield_name}"
}
insert_options[:before] = "hy-id-#{@next.id}" if @next
insert_options[:after] = "hy-id-#{@prev.id}" if not @next and @prev
render :json => {
:status => :ok,
:dialog => :close,
:insert => [insert_options]
}
else
render :json => {
:status => :failed,
:errors => @element.errors
}
end
end | ruby | def create
@element = Humpyard::config.element_types[params[:type]].new params[:element]
unless can? :create, @element.element
render :json => {
:status => :failed
}, :status => 403
return
end
if @element.save
@prev = Humpyard::Element.find_by_id(params[:prev_id])
@next = Humpyard::Element.find_by_id(params[:next_id])
do_move(@element, @prev, @next)
insert_options = {
:element => "hy-id-#{@element.element.id}",
:url => humpyard_element_path(@element.element),
:parent => @element.container ? "hy-id-#{@element.container.id}" : "hy-content-#{@element.page_yield_name}"
}
insert_options[:before] = "hy-id-#{@next.id}" if @next
insert_options[:after] = "hy-id-#{@prev.id}" if not @next and @prev
render :json => {
:status => :ok,
:dialog => :close,
:insert => [insert_options]
}
else
render :json => {
:status => :failed,
:errors => @element.errors
}
end
end | [
"def",
"create",
"@element",
"=",
"Humpyard",
"::",
"config",
".",
"element_types",
"[",
"params",
"[",
":type",
"]",
"]",
".",
"new",
"params",
"[",
":element",
"]",
"unless",
"can?",
":create",
",",
"@element",
".",
"element",
"render",
":json",
"=>",
"{",
":status",
"=>",
":failed",
"}",
",",
":status",
"=>",
"403",
"return",
"end",
"if",
"@element",
".",
"save",
"@prev",
"=",
"Humpyard",
"::",
"Element",
".",
"find_by_id",
"(",
"params",
"[",
":prev_id",
"]",
")",
"@next",
"=",
"Humpyard",
"::",
"Element",
".",
"find_by_id",
"(",
"params",
"[",
":next_id",
"]",
")",
"do_move",
"(",
"@element",
",",
"@prev",
",",
"@next",
")",
"insert_options",
"=",
"{",
":element",
"=>",
"\"hy-id-#{@element.element.id}\"",
",",
":url",
"=>",
"humpyard_element_path",
"(",
"@element",
".",
"element",
")",
",",
":parent",
"=>",
"@element",
".",
"container",
"?",
"\"hy-id-#{@element.container.id}\"",
":",
"\"hy-content-#{@element.page_yield_name}\"",
"}",
"insert_options",
"[",
":before",
"]",
"=",
"\"hy-id-#{@next.id}\"",
"if",
"@next",
"insert_options",
"[",
":after",
"]",
"=",
"\"hy-id-#{@prev.id}\"",
"if",
"not",
"@next",
"and",
"@prev",
"render",
":json",
"=>",
"{",
":status",
"=>",
":ok",
",",
":dialog",
"=>",
":close",
",",
":insert",
"=>",
"[",
"insert_options",
"]",
"}",
"else",
"render",
":json",
"=>",
"{",
":status",
"=>",
":failed",
",",
":errors",
"=>",
"@element",
".",
"errors",
"}",
"end",
"end"
] | Create a new element | [
"Create",
"a",
"new",
"element"
] | f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd | https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/controllers/humpyard/elements_controller.rb#L24-L60 | train |
humpyard/humpyard | app/controllers/humpyard/elements_controller.rb | Humpyard.ElementsController.update | def update
@element = Humpyard::Element.find(params[:id])
if @element
unless can? :update, @element
render :json => {
:status => :failed
}, :status => 403
return
end
if @element.content_data.update_attributes params[:element]
render :json => {
:status => :ok,
:dialog => :close,
:replace => [
{
:element => "hy-id-#{@element.id}",
:url => humpyard_element_path(@element)
}
]
}
else
render :json => {
:status => :failed,
:errors => @element.content_data.errors
}
end
else
render :json => {
:status => :failed
}, :status => 404
end
end | ruby | def update
@element = Humpyard::Element.find(params[:id])
if @element
unless can? :update, @element
render :json => {
:status => :failed
}, :status => 403
return
end
if @element.content_data.update_attributes params[:element]
render :json => {
:status => :ok,
:dialog => :close,
:replace => [
{
:element => "hy-id-#{@element.id}",
:url => humpyard_element_path(@element)
}
]
}
else
render :json => {
:status => :failed,
:errors => @element.content_data.errors
}
end
else
render :json => {
:status => :failed
}, :status => 404
end
end | [
"def",
"update",
"@element",
"=",
"Humpyard",
"::",
"Element",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"if",
"@element",
"unless",
"can?",
":update",
",",
"@element",
"render",
":json",
"=>",
"{",
":status",
"=>",
":failed",
"}",
",",
":status",
"=>",
"403",
"return",
"end",
"if",
"@element",
".",
"content_data",
".",
"update_attributes",
"params",
"[",
":element",
"]",
"render",
":json",
"=>",
"{",
":status",
"=>",
":ok",
",",
":dialog",
"=>",
":close",
",",
":replace",
"=>",
"[",
"{",
":element",
"=>",
"\"hy-id-#{@element.id}\"",
",",
":url",
"=>",
"humpyard_element_path",
"(",
"@element",
")",
"}",
"]",
"}",
"else",
"render",
":json",
"=>",
"{",
":status",
"=>",
":failed",
",",
":errors",
"=>",
"@element",
".",
"content_data",
".",
"errors",
"}",
"end",
"else",
"render",
":json",
"=>",
"{",
":status",
"=>",
":failed",
"}",
",",
":status",
"=>",
"404",
"end",
"end"
] | Update an existing element | [
"Update",
"an",
"existing",
"element"
] | f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd | https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/controllers/humpyard/elements_controller.rb#L81-L113 | train |
humpyard/humpyard | app/controllers/humpyard/elements_controller.rb | Humpyard.ElementsController.move | def move
@element = Humpyard::Element.find(params[:id])
if @element
unless can? :update, @element
render :json => {
:status => :failed
}, :status => 403
return
end
@element.update_attributes(
:container => Humpyard::Element.find_by_id(params[:container_id]),
:page_yield_name => params[:yield_name]
)
@prev = Humpyard::Element.find_by_id(params[:prev_id])
@next = Humpyard::Element.find_by_id(params[:next_id])
do_move(@element, @prev, @next)
render :json => {
:status => :ok
}
else
render :json => {
:status => :failed
}, :status => 404
end
end | ruby | def move
@element = Humpyard::Element.find(params[:id])
if @element
unless can? :update, @element
render :json => {
:status => :failed
}, :status => 403
return
end
@element.update_attributes(
:container => Humpyard::Element.find_by_id(params[:container_id]),
:page_yield_name => params[:yield_name]
)
@prev = Humpyard::Element.find_by_id(params[:prev_id])
@next = Humpyard::Element.find_by_id(params[:next_id])
do_move(@element, @prev, @next)
render :json => {
:status => :ok
}
else
render :json => {
:status => :failed
}, :status => 404
end
end | [
"def",
"move",
"@element",
"=",
"Humpyard",
"::",
"Element",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"if",
"@element",
"unless",
"can?",
":update",
",",
"@element",
"render",
":json",
"=>",
"{",
":status",
"=>",
":failed",
"}",
",",
":status",
"=>",
"403",
"return",
"end",
"@element",
".",
"update_attributes",
"(",
":container",
"=>",
"Humpyard",
"::",
"Element",
".",
"find_by_id",
"(",
"params",
"[",
":container_id",
"]",
")",
",",
":page_yield_name",
"=>",
"params",
"[",
":yield_name",
"]",
")",
"@prev",
"=",
"Humpyard",
"::",
"Element",
".",
"find_by_id",
"(",
"params",
"[",
":prev_id",
"]",
")",
"@next",
"=",
"Humpyard",
"::",
"Element",
".",
"find_by_id",
"(",
"params",
"[",
":next_id",
"]",
")",
"do_move",
"(",
"@element",
",",
"@prev",
",",
"@next",
")",
"render",
":json",
"=>",
"{",
":status",
"=>",
":ok",
"}",
"else",
"render",
":json",
"=>",
"{",
":status",
"=>",
":failed",
"}",
",",
":status",
"=>",
"404",
"end",
"end"
] | Move an element | [
"Move",
"an",
"element"
] | f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd | https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/controllers/humpyard/elements_controller.rb#L116-L144 | train |
NUBIC/aker | lib/aker/configuration.rb | Aker.Configuration.api_modes= | def api_modes=(*new_modes)
new_modes = new_modes.first if new_modes.size == 1 && Array === new_modes.first
@api_modes = new_modes.compact.collect(&:to_sym)
end | ruby | def api_modes=(*new_modes)
new_modes = new_modes.first if new_modes.size == 1 && Array === new_modes.first
@api_modes = new_modes.compact.collect(&:to_sym)
end | [
"def",
"api_modes",
"=",
"(",
"*",
"new_modes",
")",
"new_modes",
"=",
"new_modes",
".",
"first",
"if",
"new_modes",
".",
"size",
"==",
"1",
"&&",
"Array",
"===",
"new_modes",
".",
"first",
"@api_modes",
"=",
"new_modes",
".",
"compact",
".",
"collect",
"(",
"&",
":to_sym",
")",
"end"
] | Replaces the non-interactive authentication modes.
@param [List<#to_sym>] new_modes the names of the desired modes
@return [void] | [
"Replaces",
"the",
"non",
"-",
"interactive",
"authentication",
"modes",
"."
] | ff43606a8812e38f96bbe71b46e7f631cbeacf1c | https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/configuration.rb#L110-L113 | train |
NUBIC/aker | lib/aker/configuration.rb | Aker.Configuration.central | def central(filename)
params = ::Aker::CentralParameters.new(filename)
params.each { |k, v| add_parameters_for(k, v) }
end | ruby | def central(filename)
params = ::Aker::CentralParameters.new(filename)
params.each { |k, v| add_parameters_for(k, v) }
end | [
"def",
"central",
"(",
"filename",
")",
"params",
"=",
"::",
"Aker",
"::",
"CentralParameters",
".",
"new",
"(",
"filename",
")",
"params",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"add_parameters_for",
"(",
"k",
",",
"v",
")",
"}",
"end"
] | Loads parameters from the given aker central parameters
file.
@see Aker::CentralParameters
@param [String] filename the filename
@return [void] | [
"Loads",
"parameters",
"from",
"the",
"given",
"aker",
"central",
"parameters",
"file",
"."
] | ff43606a8812e38f96bbe71b46e7f631cbeacf1c | https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/configuration.rb#L224-L228 | train |
ktemkin/ruby-adept | lib/adept/core.rb | Adept.Core.configure | def configure(elf_file, [email protected])
#Ensure the target is a string.
target = target.to_s
#Get the path to the bitfile and memory map which will be used to generate the new bitfile.
memory_map = "#@base_path/#{@targets[target]['memory_map']}"
bit_file = "#@base_path/#{@targets[target]['bit_file']}"
p target, bit_file
#Generate the new raw bitfile...
hex = with_temporary_files { |dest, _| system("avr-objcopy -O ihex -R .eeprom -R .fuse -R .lock #{elf_file} #{dest}") }
mem = with_temporary_files(hex, '.mem', '.hex') { |dest, source| system("srec_cat #{source} -Intel -Byte_Swap 2 -Data_Only -Line_Length 100000000 -o #{dest} -vmem 8") }
bit = with_temporary_files(mem, '.bit', '.mem') { |dest, source| system("data2mem -bm #{memory_map} -bt #{bit_file} -bd #{source} -o b #{dest}") }
#... wrap it in a Bitstream object, and return it.
Adept::DataFormats::Bitstream.from_string(bit)
end | ruby | def configure(elf_file, [email protected])
#Ensure the target is a string.
target = target.to_s
#Get the path to the bitfile and memory map which will be used to generate the new bitfile.
memory_map = "#@base_path/#{@targets[target]['memory_map']}"
bit_file = "#@base_path/#{@targets[target]['bit_file']}"
p target, bit_file
#Generate the new raw bitfile...
hex = with_temporary_files { |dest, _| system("avr-objcopy -O ihex -R .eeprom -R .fuse -R .lock #{elf_file} #{dest}") }
mem = with_temporary_files(hex, '.mem', '.hex') { |dest, source| system("srec_cat #{source} -Intel -Byte_Swap 2 -Data_Only -Line_Length 100000000 -o #{dest} -vmem 8") }
bit = with_temporary_files(mem, '.bit', '.mem') { |dest, source| system("data2mem -bm #{memory_map} -bt #{bit_file} -bd #{source} -o b #{dest}") }
#... wrap it in a Bitstream object, and return it.
Adept::DataFormats::Bitstream.from_string(bit)
end | [
"def",
"configure",
"(",
"elf_file",
",",
"target",
"=",
"@targets",
".",
"keys",
".",
"first",
")",
"target",
"=",
"target",
".",
"to_s",
"memory_map",
"=",
"\"#@base_path/#{@targets[target]['memory_map']}\"",
"bit_file",
"=",
"\"#@base_path/#{@targets[target]['bit_file']}\"",
"p",
"target",
",",
"bit_file",
"hex",
"=",
"with_temporary_files",
"{",
"|",
"dest",
",",
"_",
"|",
"system",
"(",
"\"avr-objcopy -O ihex -R .eeprom -R .fuse -R .lock #{elf_file} #{dest}\"",
")",
"}",
"mem",
"=",
"with_temporary_files",
"(",
"hex",
",",
"'.mem'",
",",
"'.hex'",
")",
"{",
"|",
"dest",
",",
"source",
"|",
"system",
"(",
"\"srec_cat #{source} -Intel -Byte_Swap 2 -Data_Only -Line_Length 100000000 -o #{dest} -vmem 8\"",
")",
"}",
"bit",
"=",
"with_temporary_files",
"(",
"mem",
",",
"'.bit'",
",",
"'.mem'",
")",
"{",
"|",
"dest",
",",
"source",
"|",
"system",
"(",
"\"data2mem -bm #{memory_map} -bt #{bit_file} -bd #{source} -o b #{dest}\"",
")",
"}",
"Adept",
"::",
"DataFormats",
"::",
"Bitstream",
".",
"from_string",
"(",
"bit",
")",
"end"
] | Initializes a new instance of a Core object.
Configures the given | [
"Initializes",
"a",
"new",
"instance",
"of",
"a",
"Core",
"object",
"."
] | c24eb7bb15162632a83dc2f389f60c98447c7d5c | https://github.com/ktemkin/ruby-adept/blob/c24eb7bb15162632a83dc2f389f60c98447c7d5c/lib/adept/core.rb#L71-L90 | train |
ktemkin/ruby-adept | lib/adept/core.rb | Adept.Core.with_temporary_files | def with_temporary_files(file_contents='', dest_extension = '', source_extension = '', message=nil)
#File mode for all of the created temporary files.
#Create the files, and allow read/write, but do not lock for exclusive access.
file_mode = File::CREAT | File::RDWR
#Create a new file which contains the provided file content.
#Used to pass arbitrary data into an external tool.
Tempfile.open(['core_prev', source_extension], :mode => file_mode) do |source_file|
#Fill the source file with the provided file contents...
source_file.write(file_contents)
source_file.flush
#Create a new file which will store the resultant file content.
Tempfile.open(['core_next', dest_extension], :mode => file_mode) do |destination_file|
#Yield the file's paths the provided block.
raise CommandFailedError, message unless yield [destination_file.path, source_file.path]
#And return the content of the destination file.
return File::read(destination_file)
end
end
end | ruby | def with_temporary_files(file_contents='', dest_extension = '', source_extension = '', message=nil)
#File mode for all of the created temporary files.
#Create the files, and allow read/write, but do not lock for exclusive access.
file_mode = File::CREAT | File::RDWR
#Create a new file which contains the provided file content.
#Used to pass arbitrary data into an external tool.
Tempfile.open(['core_prev', source_extension], :mode => file_mode) do |source_file|
#Fill the source file with the provided file contents...
source_file.write(file_contents)
source_file.flush
#Create a new file which will store the resultant file content.
Tempfile.open(['core_next', dest_extension], :mode => file_mode) do |destination_file|
#Yield the file's paths the provided block.
raise CommandFailedError, message unless yield [destination_file.path, source_file.path]
#And return the content of the destination file.
return File::read(destination_file)
end
end
end | [
"def",
"with_temporary_files",
"(",
"file_contents",
"=",
"''",
",",
"dest_extension",
"=",
"''",
",",
"source_extension",
"=",
"''",
",",
"message",
"=",
"nil",
")",
"file_mode",
"=",
"File",
"::",
"CREAT",
"|",
"File",
"::",
"RDWR",
"Tempfile",
".",
"open",
"(",
"[",
"'core_prev'",
",",
"source_extension",
"]",
",",
":mode",
"=>",
"file_mode",
")",
"do",
"|",
"source_file",
"|",
"source_file",
".",
"write",
"(",
"file_contents",
")",
"source_file",
".",
"flush",
"Tempfile",
".",
"open",
"(",
"[",
"'core_next'",
",",
"dest_extension",
"]",
",",
":mode",
"=>",
"file_mode",
")",
"do",
"|",
"destination_file",
"|",
"raise",
"CommandFailedError",
",",
"message",
"unless",
"yield",
"[",
"destination_file",
".",
"path",
",",
"source_file",
".",
"path",
"]",
"return",
"File",
"::",
"read",
"(",
"destination_file",
")",
"end",
"end",
"end"
] | Executes a given block with an "anonymous" temporary file.
The temporary file is deleted at the end of the block, and its contents
are returned. | [
"Executes",
"a",
"given",
"block",
"with",
"an",
"anonymous",
"temporary",
"file",
".",
"The",
"temporary",
"file",
"is",
"deleted",
"at",
"the",
"end",
"of",
"the",
"block",
"and",
"its",
"contents",
"are",
"returned",
"."
] | c24eb7bb15162632a83dc2f389f60c98447c7d5c | https://github.com/ktemkin/ruby-adept/blob/c24eb7bb15162632a83dc2f389f60c98447c7d5c/lib/adept/core.rb#L107-L133 | train |
eet-nu/cheers | lib/cheers/color.rb | Cheers.Color.to_s | def to_s
return '#' + r.to_s(16).rjust(2, '0') +
g.to_s(16).rjust(2, '0') +
b.to_s(16).rjust(2, '0')
end | ruby | def to_s
return '#' + r.to_s(16).rjust(2, '0') +
g.to_s(16).rjust(2, '0') +
b.to_s(16).rjust(2, '0')
end | [
"def",
"to_s",
"return",
"'#'",
"+",
"r",
".",
"to_s",
"(",
"16",
")",
".",
"rjust",
"(",
"2",
",",
"'0'",
")",
"+",
"g",
".",
"to_s",
"(",
"16",
")",
".",
"rjust",
"(",
"2",
",",
"'0'",
")",
"+",
"b",
".",
"to_s",
"(",
"16",
")",
".",
"rjust",
"(",
"2",
",",
"'0'",
")",
"end"
] | Create new color from a hex value | [
"Create",
"new",
"color",
"from",
"a",
"hex",
"value"
] | 4b94bf8ce2a1ca929b9b56277e12f3e94e7a5399 | https://github.com/eet-nu/cheers/blob/4b94bf8ce2a1ca929b9b56277e12f3e94e7a5399/lib/cheers/color.rb#L16-L20 | train |
plangrade/plangrade-ruby | lib/plangrade/client.rb | Plangrade.Client.request | def request(method, path, params={})
headers = @default_headers.merge({'Authorization' => "Bearer #{@access_token}"})
result = http_client.send_request(method, path, {
:params => params,
:headers => headers
})
result
end | ruby | def request(method, path, params={})
headers = @default_headers.merge({'Authorization' => "Bearer #{@access_token}"})
result = http_client.send_request(method, path, {
:params => params,
:headers => headers
})
result
end | [
"def",
"request",
"(",
"method",
",",
"path",
",",
"params",
"=",
"{",
"}",
")",
"headers",
"=",
"@default_headers",
".",
"merge",
"(",
"{",
"'Authorization'",
"=>",
"\"Bearer #{@access_token}\"",
"}",
")",
"result",
"=",
"http_client",
".",
"send_request",
"(",
"method",
",",
"path",
",",
"{",
":params",
"=>",
"params",
",",
":headers",
"=>",
"headers",
"}",
")",
"result",
"end"
] | Makes an HTTP request using the provided parameters
@raise [Plangrade::Error::Unauthorized]
@param method [string]
@param path [string]
@param params [Hash]
@return [Plangrade::ApiResponse]
@!visibility private | [
"Makes",
"an",
"HTTP",
"request",
"using",
"the",
"provided",
"parameters"
] | fe7240753825358c9b3c6887b51b5858a984c5f8 | https://github.com/plangrade/plangrade-ruby/blob/fe7240753825358c9b3c6887b51b5858a984c5f8/lib/plangrade/client.rb#L67-L74 | train |
jeremyd/virtualmonkey | lib/virtualmonkey/application.rb | VirtualMonkey.Application.app_servers | def app_servers
ret = @servers.select { |s| s.nickname =~ /App Server/ }
raise "No app servers in deployment" unless ret.length > 0
ret
end | ruby | def app_servers
ret = @servers.select { |s| s.nickname =~ /App Server/ }
raise "No app servers in deployment" unless ret.length > 0
ret
end | [
"def",
"app_servers",
"ret",
"=",
"@servers",
".",
"select",
"{",
"|",
"s",
"|",
"s",
".",
"nickname",
"=~",
"/",
"/",
"}",
"raise",
"\"No app servers in deployment\"",
"unless",
"ret",
".",
"length",
">",
"0",
"ret",
"end"
] | returns an Array of the App Servers in the deployment | [
"returns",
"an",
"Array",
"of",
"the",
"App",
"Servers",
"in",
"the",
"deployment"
] | b2c7255f20ac5ec881eb90afbb5e712160db0dcb | https://github.com/jeremyd/virtualmonkey/blob/b2c7255f20ac5ec881eb90afbb5e712160db0dcb/lib/virtualmonkey/application.rb#L7-L11 | train |
mhs/rvideo | lib/rvideo/inspector.rb | RVideo.Inspector.duration | def duration
return nil unless valid?
units = raw_duration.split(":")
(units[0].to_i * 60 * 60 * 1000) + (units[1].to_i * 60 * 1000) + (units[2].to_f * 1000).to_i
end | ruby | def duration
return nil unless valid?
units = raw_duration.split(":")
(units[0].to_i * 60 * 60 * 1000) + (units[1].to_i * 60 * 1000) + (units[2].to_f * 1000).to_i
end | [
"def",
"duration",
"return",
"nil",
"unless",
"valid?",
"units",
"=",
"raw_duration",
".",
"split",
"(",
"\":\"",
")",
"(",
"units",
"[",
"0",
"]",
".",
"to_i",
"*",
"60",
"*",
"60",
"*",
"1000",
")",
"+",
"(",
"units",
"[",
"1",
"]",
".",
"to_i",
"*",
"60",
"*",
"1000",
")",
"+",
"(",
"units",
"[",
"2",
"]",
".",
"to_f",
"*",
"1000",
")",
".",
"to_i",
"end"
] | The duration of the movie in milliseconds, as an integer.
Example:
24400 # 24.4 seconds
Note that the precision of the duration is in tenths of a second, not
thousandths, but milliseconds are a more standard unit of time than
deciseconds. | [
"The",
"duration",
"of",
"the",
"movie",
"in",
"milliseconds",
"as",
"an",
"integer",
"."
] | 5d12bafc5b63888f01c42de272fddcef0ac528b1 | https://github.com/mhs/rvideo/blob/5d12bafc5b63888f01c42de272fddcef0ac528b1/lib/rvideo/inspector.rb#L304-L309 | train |
genaromadrid/email_checker | lib/email_checker/domain.rb | EmailChecker.Domain.valid? | def valid?
return false unless @domain
Timeout.timeout(SERVER_TIMEOUT) do
return true if valid_mx_records?
return true if a_records?
end
rescue Timeout::Error, Errno::ECONNREFUSED
false
end | ruby | def valid?
return false unless @domain
Timeout.timeout(SERVER_TIMEOUT) do
return true if valid_mx_records?
return true if a_records?
end
rescue Timeout::Error, Errno::ECONNREFUSED
false
end | [
"def",
"valid?",
"return",
"false",
"unless",
"@domain",
"Timeout",
".",
"timeout",
"(",
"SERVER_TIMEOUT",
")",
"do",
"return",
"true",
"if",
"valid_mx_records?",
"return",
"true",
"if",
"a_records?",
"end",
"rescue",
"Timeout",
"::",
"Error",
",",
"Errno",
"::",
"ECONNREFUSED",
"false",
"end"
] | Returns a new instance of Domain
@param domain [String] The domain name.
@example EmailChecker::Domain.new('google.com')
Checks if the domian exists and has valid MX and A records.
@return [Boolean] | [
"Returns",
"a",
"new",
"instance",
"of",
"Domain"
] | 34cae07ddf5bb86efff030d062e420d5aa15486a | https://github.com/genaromadrid/email_checker/blob/34cae07ddf5bb86efff030d062e420d5aa15486a/lib/email_checker/domain.rb#L20-L28 | train |
genaromadrid/email_checker | lib/email_checker/domain.rb | EmailChecker.Domain.valid_mx_records? | def valid_mx_records?
mx_servers.each do |server|
exchange_a_records = dns.getresources(server[:address], Resolv::DNS::Resource::IN::A)
return true if exchange_a_records.any?
end
false
end | ruby | def valid_mx_records?
mx_servers.each do |server|
exchange_a_records = dns.getresources(server[:address], Resolv::DNS::Resource::IN::A)
return true if exchange_a_records.any?
end
false
end | [
"def",
"valid_mx_records?",
"mx_servers",
".",
"each",
"do",
"|",
"server",
"|",
"exchange_a_records",
"=",
"dns",
".",
"getresources",
"(",
"server",
"[",
":address",
"]",
",",
"Resolv",
"::",
"DNS",
"::",
"Resource",
"::",
"IN",
"::",
"A",
")",
"return",
"true",
"if",
"exchange_a_records",
".",
"any?",
"end",
"false",
"end"
] | Check if the domian has valid MX records and it can receive emails.
The MX server exists and it has valid A records.
@return [Boolean] | [
"Check",
"if",
"the",
"domian",
"has",
"valid",
"MX",
"records",
"and",
"it",
"can",
"receive",
"emails",
".",
"The",
"MX",
"server",
"exists",
"and",
"it",
"has",
"valid",
"A",
"records",
"."
] | 34cae07ddf5bb86efff030d062e420d5aa15486a | https://github.com/genaromadrid/email_checker/blob/34cae07ddf5bb86efff030d062e420d5aa15486a/lib/email_checker/domain.rb#L34-L40 | train |
genaromadrid/email_checker | lib/email_checker/domain.rb | EmailChecker.Domain.mx_servers | def mx_servers
return @mx_servers if @mx_servers
@mx_servers = []
mx_records.each do |mx|
@mx_servers.push(preference: mx.preference, address: mx.exchange.to_s)
end
@mx_servers
end | ruby | def mx_servers
return @mx_servers if @mx_servers
@mx_servers = []
mx_records.each do |mx|
@mx_servers.push(preference: mx.preference, address: mx.exchange.to_s)
end
@mx_servers
end | [
"def",
"mx_servers",
"return",
"@mx_servers",
"if",
"@mx_servers",
"@mx_servers",
"=",
"[",
"]",
"mx_records",
".",
"each",
"do",
"|",
"mx",
"|",
"@mx_servers",
".",
"push",
"(",
"preference",
":",
"mx",
".",
"preference",
",",
"address",
":",
"mx",
".",
"exchange",
".",
"to_s",
")",
"end",
"@mx_servers",
"end"
] | The servers that this domian MX records point at.
@return [Array<Hash>] Array of type { preference: 1, address: '127.0.0.1' } | [
"The",
"servers",
"that",
"this",
"domian",
"MX",
"records",
"point",
"at",
"."
] | 34cae07ddf5bb86efff030d062e420d5aa15486a | https://github.com/genaromadrid/email_checker/blob/34cae07ddf5bb86efff030d062e420d5aa15486a/lib/email_checker/domain.rb#L67-L74 | train |
userhello/bit_magic | lib/bit_magic/bits_generator.rb | BitMagic.BitsGenerator.bits_for | def bits_for(*field_names)
bits = []
field_names.flatten.each do |i|
if i.is_a?(Integer)
bits << i
next
end
if i.respond_to?(:to_sym) and @field_list[i.to_sym]
bits << @field_list[i.to_sym]
end
end
bits.flatten
end | ruby | def bits_for(*field_names)
bits = []
field_names.flatten.each do |i|
if i.is_a?(Integer)
bits << i
next
end
if i.respond_to?(:to_sym) and @field_list[i.to_sym]
bits << @field_list[i.to_sym]
end
end
bits.flatten
end | [
"def",
"bits_for",
"(",
"*",
"field_names",
")",
"bits",
"=",
"[",
"]",
"field_names",
".",
"flatten",
".",
"each",
"do",
"|",
"i",
"|",
"if",
"i",
".",
"is_a?",
"(",
"Integer",
")",
"bits",
"<<",
"i",
"next",
"end",
"if",
"i",
".",
"respond_to?",
"(",
":to_sym",
")",
"and",
"@field_list",
"[",
"i",
".",
"to_sym",
"]",
"bits",
"<<",
"@field_list",
"[",
"i",
".",
"to_sym",
"]",
"end",
"end",
"bits",
".",
"flatten",
"end"
] | Initialize the generator.
@param [BitMagic::Adapters::Magician, Hash] magician_or_field_list a Magician
object that contains field_list, bits, and options OR a Hash object of
:name => bit index or bit index array, key-value pairs
@param [Hash] options options and defaults, will override Magician action_options
if given
@option options [Integer] :default a default value, default: 0
@option options [Proc] :bool_caster a callable Method, Proc or lambda that
is used to cast a value into a boolean
@return [BitsGenerator] the resulting object
Given a field name or list of field names, return their corresponding bits
Field names are the key values of the field_list hash during initialization
@param [Symbol, Integer] one or more keys for the field name or an integer
for a known bit index
@example Get a list of bits
gen = BitMagic::BitsGenerator.new(:is_odd => 0, :amount => [1, 2, 3], :is_cool => 4)
gen.bits_for(:is_odd) #=> [0]
gen.bits_for(:amount) #=> [1, 2, 3]
gen.bits_for(:is_odd, :amount) #=> [0, 1, 2, 3]
gen.bits_for(:is_cool, 5, 6) #=> [4, 5, 6]
gen.bits_for(9, 10) #=> [9, 10]
@return [Array<Integer>] an array of bit indices | [
"Initialize",
"the",
"generator",
"."
] | 78b7fc28313af9c9506220812573576d229186bb | https://github.com/userhello/bit_magic/blob/78b7fc28313af9c9506220812573576d229186bb/lib/bit_magic/bits_generator.rb#L63-L78 | train |
userhello/bit_magic | lib/bit_magic/bits_generator.rb | BitMagic.BitsGenerator.each_value | def each_value(each_bits = nil, &block)
# Warning! This has exponential complexity (time and space)
# 2**n to be precise, use sparingly
yield 0
count = 1
if @options[:default] != 0
yield @options[:default]
count += 1
end
each_bits = self.bits if each_bits == nil
1.upto(each_bits.length).each do |i|
each_bits.combination(i).each do |bits_list|
num = bits_list.reduce(0) { |m, j| m |= (1 << j) }
yield num
count += 1
end
end
count
end | ruby | def each_value(each_bits = nil, &block)
# Warning! This has exponential complexity (time and space)
# 2**n to be precise, use sparingly
yield 0
count = 1
if @options[:default] != 0
yield @options[:default]
count += 1
end
each_bits = self.bits if each_bits == nil
1.upto(each_bits.length).each do |i|
each_bits.combination(i).each do |bits_list|
num = bits_list.reduce(0) { |m, j| m |= (1 << j) }
yield num
count += 1
end
end
count
end | [
"def",
"each_value",
"(",
"each_bits",
"=",
"nil",
",",
"&",
"block",
")",
"yield",
"0",
"count",
"=",
"1",
"if",
"@options",
"[",
":default",
"]",
"!=",
"0",
"yield",
"@options",
"[",
":default",
"]",
"count",
"+=",
"1",
"end",
"each_bits",
"=",
"self",
".",
"bits",
"if",
"each_bits",
"==",
"nil",
"1",
".",
"upto",
"(",
"each_bits",
".",
"length",
")",
".",
"each",
"do",
"|",
"i",
"|",
"each_bits",
".",
"combination",
"(",
"i",
")",
".",
"each",
"do",
"|",
"bits_list",
"|",
"num",
"=",
"bits_list",
".",
"reduce",
"(",
"0",
")",
"{",
"|",
"m",
",",
"j",
"|",
"m",
"|=",
"(",
"1",
"<<",
"j",
")",
"}",
"yield",
"num",
"count",
"+=",
"1",
"end",
"end",
"count",
"end"
] | Iterates over the entire combination of all possible values utilizing the
list of bits we are given.
Warning: Because we are iteration over possible values, the total available
values grows exponentially with the given number of bits. For example, if
you use only 8 bits, there are 2*8 = 256 possible values, with 20 bits it
grows to 2**20 = 1048576. At 32 bits, 2**32 = 4294967296.
Warning 2: We're using combinations to generate each individual number, so
there's additional overhead causing O(n * 2^(n-1)) time complexity. Carefully
benchmark when you have large bit lists (more than 16 bits total) and
check both timing and memory for your use case.
@param [optional, Array<Integer>] each_bits a list of bits used to generate
the combination list. default: the list of bits given during initialization
@param [Proc] block a callable method to yield individual values
@yield num will yield to the given block multiple times, each time with one
of the integer values that are possible from the given bits list
@example Iterate over a list of bits
gen = BitsGenerator.new(:is_odd => 0, :amount => [1, 2, 3], :is_cool => 4)
values = []
gen.each_value { |val| values << val } #=> 32
values #=> [0, 1, 2, 4, 8, 16, 3, 5, 9, 17, 6, 10, 18, 12, 20, 24, 7, 11, 19, 13, 21, 25, 14, 22, 26, 28, 15, 23, 27, 29, 30, 31]
values2 = []
gen.each_value([0, 5]) { |val| values2 << val } #=> 4
values2 #=> [0, 1, 32, 33]
@return [Integer] total number of values yielded | [
"Iterates",
"over",
"the",
"entire",
"combination",
"of",
"all",
"possible",
"values",
"utilizing",
"the",
"list",
"of",
"bits",
"we",
"are",
"given",
"."
] | 78b7fc28313af9c9506220812573576d229186bb | https://github.com/userhello/bit_magic/blob/78b7fc28313af9c9506220812573576d229186bb/lib/bit_magic/bits_generator.rb#L111-L134 | train |
userhello/bit_magic | lib/bit_magic/bits_generator.rb | BitMagic.BitsGenerator.all_values | def all_values(each_bits = nil, opts = {warn_threshold: 12})
# Shuffle things around so that people can call #all_values(warn_threshold: false)
if each_bits.is_a?(Hash)
opts = each_bits
each_bits = nil
end
each_bits = self.bits if each_bits == nil
if opts[:warn_threshold] and each_bits.length > opts[:warn_threshold]
warn "There are #{each_bits.length} bits. You will have #{2**(each_bits.length)} values in the result. Please carefully benchmark the execution time and memory usage of your use-case."
warn "You can disable this warning by using #all_values(warn_threshold: false)"
end
values = []
self.each_value(each_bits) {|num| values << num }
values
end | ruby | def all_values(each_bits = nil, opts = {warn_threshold: 12})
# Shuffle things around so that people can call #all_values(warn_threshold: false)
if each_bits.is_a?(Hash)
opts = each_bits
each_bits = nil
end
each_bits = self.bits if each_bits == nil
if opts[:warn_threshold] and each_bits.length > opts[:warn_threshold]
warn "There are #{each_bits.length} bits. You will have #{2**(each_bits.length)} values in the result. Please carefully benchmark the execution time and memory usage of your use-case."
warn "You can disable this warning by using #all_values(warn_threshold: false)"
end
values = []
self.each_value(each_bits) {|num| values << num }
values
end | [
"def",
"all_values",
"(",
"each_bits",
"=",
"nil",
",",
"opts",
"=",
"{",
"warn_threshold",
":",
"12",
"}",
")",
"if",
"each_bits",
".",
"is_a?",
"(",
"Hash",
")",
"opts",
"=",
"each_bits",
"each_bits",
"=",
"nil",
"end",
"each_bits",
"=",
"self",
".",
"bits",
"if",
"each_bits",
"==",
"nil",
"if",
"opts",
"[",
":warn_threshold",
"]",
"and",
"each_bits",
".",
"length",
">",
"opts",
"[",
":warn_threshold",
"]",
"warn",
"\"There are #{each_bits.length} bits. You will have #{2**(each_bits.length)} values in the result. Please carefully benchmark the execution time and memory usage of your use-case.\"",
"warn",
"\"You can disable this warning by using #all_values(warn_threshold: false)\"",
"end",
"values",
"=",
"[",
"]",
"self",
".",
"each_value",
"(",
"each_bits",
")",
"{",
"|",
"num",
"|",
"values",
"<<",
"num",
"}",
"values",
"end"
] | Gives you an array of all possible integer values based off the bit
combinations of the bit list.
Note: This will include all possible values from the bit list, but there
are no guarantees on their order. If you need an ordered list, sort the result.
Warning: Please see the warnings on each_value.
Warning: Memory usage grows exponentially to the number of bits! For example,
on a 64 bit platform (assuming pointers are 8 bytes) if you have 8 bits,
this array will have 256 values, taking up 2KB of memory. At 20 bits, it's
1048576 values, taking up 8MB. At 32 bits, 4294967296 values take up 34GB!
@param [optional, Array<Integer>] each_bits a list of bits used to generate
the combination list. default: the list of bits given during initialization
@param [Hash] opts additional options
@option opts [Integer] :warn_threshold will output warning messages if
the total number of bits is above this number. false to disable. default: 20
@example Get an array for all values from our bit list
gen = BitsGenerator.new(:is_odd => 0, :amount => [1, 2, 3], :is_cool => 4)
gen.all_values
@return [Array<Integer>] an array of all possible values from the bit list
Order is not guaranteed to be consistent. | [
"Gives",
"you",
"an",
"array",
"of",
"all",
"possible",
"integer",
"values",
"based",
"off",
"the",
"bit",
"combinations",
"of",
"the",
"bit",
"list",
"."
] | 78b7fc28313af9c9506220812573576d229186bb | https://github.com/userhello/bit_magic/blob/78b7fc28313af9c9506220812573576d229186bb/lib/bit_magic/bits_generator.rb#L161-L180 | train |
userhello/bit_magic | lib/bit_magic/bits_generator.rb | BitMagic.BitsGenerator.equal_to | def equal_to(field_values = {})
all_num, none_num = self.equal_to_numbers(field_values)
[].tap do |list|
self.each_value { |num| list << num if (num & all_num) == all_num and (num & none_num) == 0 }
end
end | ruby | def equal_to(field_values = {})
all_num, none_num = self.equal_to_numbers(field_values)
[].tap do |list|
self.each_value { |num| list << num if (num & all_num) == all_num and (num & none_num) == 0 }
end
end | [
"def",
"equal_to",
"(",
"field_values",
"=",
"{",
"}",
")",
"all_num",
",",
"none_num",
"=",
"self",
".",
"equal_to_numbers",
"(",
"field_values",
")",
"[",
"]",
".",
"tap",
"do",
"|",
"list",
"|",
"self",
".",
"each_value",
"{",
"|",
"num",
"|",
"list",
"<<",
"num",
"if",
"(",
"num",
"&",
"all_num",
")",
"==",
"all_num",
"and",
"(",
"num",
"&",
"none_num",
")",
"==",
"0",
"}",
"end",
"end"
] | Gives you an array of values where the given field names are exactly
equal to their given field values.
Possible values are derived from the bits list during initialization.
Note: Order is not guaranteed. All numbers will be present, but there is
no expectation that the numbers will be in the same order every time. If
you need an ordered list, you can sort the result.
@param [Hash] one or more field names or an integer for a known bit index
as the key, and the value (integer or boolean) for that field as the hash
value. Values that have more bits than available will be truncated for
comparison. eg. a field with one bit setting value to 2 means field is 0
@example Get different amount values
gen = BitsGenerator.new(:is_odd => 0, :amount => [1, 2, 3], :is_cool => 4)
gen.equal_to(:amount => 5) #=> [10, 11, 26, 27]
gen.equal_to(:amount => 7) #=> [14, 15, 30, 31]
gen.equal_to(:amount => 7, :is_odd => 1, :is_cool => 1) #=> [31]
@return [Array<Integer>] an array of integer values where the bits and values
match the given input | [
"Gives",
"you",
"an",
"array",
"of",
"values",
"where",
"the",
"given",
"field",
"names",
"are",
"exactly",
"equal",
"to",
"their",
"given",
"field",
"values",
"."
] | 78b7fc28313af9c9506220812573576d229186bb | https://github.com/userhello/bit_magic/blob/78b7fc28313af9c9506220812573576d229186bb/lib/bit_magic/bits_generator.rb#L299-L305 | train |
userhello/bit_magic | lib/bit_magic/bits_generator.rb | BitMagic.BitsGenerator.equal_to_numbers | def equal_to_numbers(field_values = {})
fields = {}
field_values.each_pair do |field_name, v|
bits = self.bits_for(field_name)
fields[bits] = v if bits.length > 0
end
all_num = 0
none_num = 0
fields.each_pair { |field_bits, val|
field_bits.each_with_index do |bit, i|
if @options[:bool_caster].call(val[i])
all_num |= (1 << bit)
else
none_num |= (1 << bit)
end
end
}
[all_num, none_num]
end | ruby | def equal_to_numbers(field_values = {})
fields = {}
field_values.each_pair do |field_name, v|
bits = self.bits_for(field_name)
fields[bits] = v if bits.length > 0
end
all_num = 0
none_num = 0
fields.each_pair { |field_bits, val|
field_bits.each_with_index do |bit, i|
if @options[:bool_caster].call(val[i])
all_num |= (1 << bit)
else
none_num |= (1 << bit)
end
end
}
[all_num, none_num]
end | [
"def",
"equal_to_numbers",
"(",
"field_values",
"=",
"{",
"}",
")",
"fields",
"=",
"{",
"}",
"field_values",
".",
"each_pair",
"do",
"|",
"field_name",
",",
"v",
"|",
"bits",
"=",
"self",
".",
"bits_for",
"(",
"field_name",
")",
"fields",
"[",
"bits",
"]",
"=",
"v",
"if",
"bits",
".",
"length",
">",
"0",
"end",
"all_num",
"=",
"0",
"none_num",
"=",
"0",
"fields",
".",
"each_pair",
"{",
"|",
"field_bits",
",",
"val",
"|",
"field_bits",
".",
"each_with_index",
"do",
"|",
"bit",
",",
"i",
"|",
"if",
"@options",
"[",
":bool_caster",
"]",
".",
"call",
"(",
"val",
"[",
"i",
"]",
")",
"all_num",
"|=",
"(",
"1",
"<<",
"bit",
")",
"else",
"none_num",
"|=",
"(",
"1",
"<<",
"bit",
")",
"end",
"end",
"}",
"[",
"all_num",
",",
"none_num",
"]",
"end"
] | Will return an array of two numbers, the first of which has all bits set
where the corresponding value bit is 1, and the second has all bits set
where the corresponding value bit is 0.
These numbers can be used in advanced bitwise operations to test fields
for exact equality.
@param [Hash] one or more field names or an integer for a known bit index
as the key, and the value (integer or boolean) for that field as the hash
value. Values that have more bits than available will be truncated for
comparison. eg. a field with one bit setting value to 2 means field is 0
@example Retrieve the representation for various amounts
gen = BitsGenerator.new(:is_odd => 0, :amount => [1, 2, 3], :is_cool => 4)
gen.equal_to_numbers(:amount => 5) #=> [10, 4]
# 5 is 101, 10 is 1010 and 4 is 100. (Note that amount uses bits 1, 2, 3)
gen.equal_to_numbers(:amount => 7) #=> [14, 0]
gen.equal_to_numbers(:amount => 7, :is_odd => 1) #=> [15, 0]
@return [Array<Integer>] an array of two integers, first representing bits
of given field bit values as 1 set to 1, and the second representing bits
of given field bit values as 0 set to 1. See the example. | [
"Will",
"return",
"an",
"array",
"of",
"two",
"numbers",
"the",
"first",
"of",
"which",
"has",
"all",
"bits",
"set",
"where",
"the",
"corresponding",
"value",
"bit",
"is",
"1",
"and",
"the",
"second",
"has",
"all",
"bits",
"set",
"where",
"the",
"corresponding",
"value",
"bit",
"is",
"0",
".",
"These",
"numbers",
"can",
"be",
"used",
"in",
"advanced",
"bitwise",
"operations",
"to",
"test",
"fields",
"for",
"exact",
"equality",
"."
] | 78b7fc28313af9c9506220812573576d229186bb | https://github.com/userhello/bit_magic/blob/78b7fc28313af9c9506220812573576d229186bb/lib/bit_magic/bits_generator.rb#L329-L350 | train |
ideonetwork/lato-blog | app/models/lato_blog/category/entity_helpers.rb | LatoBlog.Category::EntityHelpers.get_all_category_children | def get_all_category_children
direct_children = self.category_children
all_children = []
direct_children.each do |direct_child|
all_children.push(direct_child)
all_children = all_children + direct_child.get_all_category_children
end
all_children
end | ruby | def get_all_category_children
direct_children = self.category_children
all_children = []
direct_children.each do |direct_child|
all_children.push(direct_child)
all_children = all_children + direct_child.get_all_category_children
end
all_children
end | [
"def",
"get_all_category_children",
"direct_children",
"=",
"self",
".",
"category_children",
"all_children",
"=",
"[",
"]",
"direct_children",
".",
"each",
"do",
"|",
"direct_child",
"|",
"all_children",
".",
"push",
"(",
"direct_child",
")",
"all_children",
"=",
"all_children",
"+",
"direct_child",
".",
"get_all_category_children",
"end",
"all_children",
"end"
] | This function return all category children of the current category. | [
"This",
"function",
"return",
"all",
"category",
"children",
"of",
"the",
"current",
"category",
"."
] | a0d92de299a0e285851743b9d4a902f611187cba | https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/models/lato_blog/category/entity_helpers.rb#L37-L47 | train |
lanvige/chinese_lunar | lib/chinese_lunar/lunar.rb | ChineseLunar.Lunar.lunar_date | def lunar_date()
l = convert(@date.year, @date.month, @date.day)
l[0].to_s + "-" + l[1].to_s + "-" + (/^\d+/.match(l[2].to_s)).to_s
end | ruby | def lunar_date()
l = convert(@date.year, @date.month, @date.day)
l[0].to_s + "-" + l[1].to_s + "-" + (/^\d+/.match(l[2].to_s)).to_s
end | [
"def",
"lunar_date",
"(",
")",
"l",
"=",
"convert",
"(",
"@date",
".",
"year",
",",
"@date",
".",
"month",
",",
"@date",
".",
"day",
")",
"l",
"[",
"0",
"]",
".",
"to_s",
"+",
"\"-\"",
"+",
"l",
"[",
"1",
"]",
".",
"to_s",
"+",
"\"-\"",
"+",
"(",
"/",
"\\d",
"/",
".",
"match",
"(",
"l",
"[",
"2",
"]",
".",
"to_s",
")",
")",
".",
"to_s",
"end"
] | Get the Lundar date in 'xxxx-xx-xx' fromat | [
"Get",
"the",
"Lundar",
"date",
"in",
"xxxx",
"-",
"xx",
"-",
"xx",
"fromat"
] | f4e4a4f19fc1a7098fabe31f41b58b0e6c86e779 | https://github.com/lanvige/chinese_lunar/blob/f4e4a4f19fc1a7098fabe31f41b58b0e6c86e779/lib/chinese_lunar/lunar.rb#L53-L56 | train |
lanvige/chinese_lunar | lib/chinese_lunar/lunar.rb | ChineseLunar.Lunar.days_in_lunar_date | def days_in_lunar_date(y)
sum = 348
i = 0x8000
while i > 0x8
if ((@@lunar_info[y - 1900] & i) != 0)
sum += 1
end
i >>= 1
end
sum + leap_days(y)
end | ruby | def days_in_lunar_date(y)
sum = 348
i = 0x8000
while i > 0x8
if ((@@lunar_info[y - 1900] & i) != 0)
sum += 1
end
i >>= 1
end
sum + leap_days(y)
end | [
"def",
"days_in_lunar_date",
"(",
"y",
")",
"sum",
"=",
"348",
"i",
"=",
"0x8000",
"while",
"i",
">",
"0x8",
"if",
"(",
"(",
"@@lunar_info",
"[",
"y",
"-",
"1900",
"]",
"&",
"i",
")",
"!=",
"0",
")",
"sum",
"+=",
"1",
"end",
"i",
">>=",
"1",
"end",
"sum",
"+",
"leap_days",
"(",
"y",
")",
"end"
] | Return the days in lunar of y year. | [
"Return",
"the",
"days",
"in",
"lunar",
"of",
"y",
"year",
"."
] | f4e4a4f19fc1a7098fabe31f41b58b0e6c86e779 | https://github.com/lanvige/chinese_lunar/blob/f4e4a4f19fc1a7098fabe31f41b58b0e6c86e779/lib/chinese_lunar/lunar.rb#L190-L201 | train |
mig-hub/sequel-crushyform | lib/sequel_crushyform.rb | ::Sequel::Plugins::Crushyform.ClassMethods.to_dropdown | def to_dropdown(selection=nil, nil_name='** UNDEFINED **')
dropdown_cache.inject("<option value=''>#{nil_name}</option>\n") do |out, row|
selected = 'selected' if row[0]==selection
"%s%s%s%s" % [out, row[1], selected, row[2]]
end
end | ruby | def to_dropdown(selection=nil, nil_name='** UNDEFINED **')
dropdown_cache.inject("<option value=''>#{nil_name}</option>\n") do |out, row|
selected = 'selected' if row[0]==selection
"%s%s%s%s" % [out, row[1], selected, row[2]]
end
end | [
"def",
"to_dropdown",
"(",
"selection",
"=",
"nil",
",",
"nil_name",
"=",
"'** UNDEFINED **'",
")",
"dropdown_cache",
".",
"inject",
"(",
"\"<option value=''>#{nil_name}</option>\\n\"",
")",
"do",
"|",
"out",
",",
"row",
"|",
"selected",
"=",
"'selected'",
"if",
"row",
"[",
"0",
"]",
"==",
"selection",
"\"%s%s%s%s\"",
"%",
"[",
"out",
",",
"row",
"[",
"1",
"]",
",",
"selected",
",",
"row",
"[",
"2",
"]",
"]",
"end",
"end"
] | Cache dropdown options for children classes to use
Meant to be reseted each time an entry is created, updated or destroyed
So it is only rebuild once required after the list has changed
Maintaining an array and not rebuilding it all might be faster
But it will not happen much so that it is fairly acceptable | [
"Cache",
"dropdown",
"options",
"for",
"children",
"classes",
"to",
"use",
"Meant",
"to",
"be",
"reseted",
"each",
"time",
"an",
"entry",
"is",
"created",
"updated",
"or",
"destroyed",
"So",
"it",
"is",
"only",
"rebuild",
"once",
"required",
"after",
"the",
"list",
"has",
"changed",
"Maintaining",
"an",
"array",
"and",
"not",
"rebuilding",
"it",
"all",
"might",
"be",
"faster",
"But",
"it",
"will",
"not",
"happen",
"much",
"so",
"that",
"it",
"is",
"fairly",
"acceptable"
] | c717df86dea0206487d9b3ee340fbd529fc7b91f | https://github.com/mig-hub/sequel-crushyform/blob/c717df86dea0206487d9b3ee340fbd529fc7b91f/lib/sequel_crushyform.rb#L93-L98 | train |
mig-hub/sequel-crushyform | lib/sequel_crushyform.rb | ::Sequel::Plugins::Crushyform.InstanceMethods.crushyfield | def crushyfield(col, o={})
return '' if (o[:type]==:none || model.crushyform_schema[col][:type]==:none)
field_name = o[:name] || model.crushyform_schema[col][:name] || col.to_s.sub(/_id$/, '').tr('_', ' ').capitalize
error_list = errors.on(col).map{|e|" - #{e}"} if !errors.on(col).nil?
"<p class='crushyfield %s'><label for='%s'>%s</label><span class='crushyfield-error-list'>%s</span><br />\n%s</p>\n" % [error_list&&'crushyfield-error', crushyid_for(col), field_name, error_list, crushyinput(col, o)]
end | ruby | def crushyfield(col, o={})
return '' if (o[:type]==:none || model.crushyform_schema[col][:type]==:none)
field_name = o[:name] || model.crushyform_schema[col][:name] || col.to_s.sub(/_id$/, '').tr('_', ' ').capitalize
error_list = errors.on(col).map{|e|" - #{e}"} if !errors.on(col).nil?
"<p class='crushyfield %s'><label for='%s'>%s</label><span class='crushyfield-error-list'>%s</span><br />\n%s</p>\n" % [error_list&&'crushyfield-error', crushyid_for(col), field_name, error_list, crushyinput(col, o)]
end | [
"def",
"crushyfield",
"(",
"col",
",",
"o",
"=",
"{",
"}",
")",
"return",
"''",
"if",
"(",
"o",
"[",
":type",
"]",
"==",
":none",
"||",
"model",
".",
"crushyform_schema",
"[",
"col",
"]",
"[",
":type",
"]",
"==",
":none",
")",
"field_name",
"=",
"o",
"[",
":name",
"]",
"||",
"model",
".",
"crushyform_schema",
"[",
"col",
"]",
"[",
":name",
"]",
"||",
"col",
".",
"to_s",
".",
"sub",
"(",
"/",
"/",
",",
"''",
")",
".",
"tr",
"(",
"'_'",
",",
"' '",
")",
".",
"capitalize",
"error_list",
"=",
"errors",
".",
"on",
"(",
"col",
")",
".",
"map",
"{",
"|",
"e",
"|",
"\" - #{e}\"",
"}",
"if",
"!",
"errors",
".",
"on",
"(",
"col",
")",
".",
"nil?",
"\"<p class='crushyfield %s'><label for='%s'>%s</label><span class='crushyfield-error-list'>%s</span><br />\\n%s</p>\\n\"",
"%",
"[",
"error_list",
"&&",
"'crushyfield-error'",
",",
"crushyid_for",
"(",
"col",
")",
",",
"field_name",
",",
"error_list",
",",
"crushyinput",
"(",
"col",
",",
"o",
")",
"]",
"end"
] | crushyfield is crushyinput but with label+error | [
"crushyfield",
"is",
"crushyinput",
"but",
"with",
"label",
"+",
"error"
] | c717df86dea0206487d9b3ee340fbd529fc7b91f | https://github.com/mig-hub/sequel-crushyform/blob/c717df86dea0206487d9b3ee340fbd529fc7b91f/lib/sequel_crushyform.rb#L124-L129 | train |
mig-hub/sequel-crushyform | lib/sequel_crushyform.rb | ::Sequel::Plugins::Crushyform.InstanceMethods.to_thumb | def to_thumb(c)
current = self.__send__(c)
if model.respond_to?(:stash_reflection) && model.stash_reflection.key?(c)
!current.nil? && current[:type][/^image\//] ? "<img src='#{file_url(c, 'stash_thumb.gif')}?#{::Time.now.to_i.to_s}' /><br />\n" : ''
else
"<img src='#{current}?#{::Time.now.to_i.to_s}' width='100' onerror=\"this.style.display='none'\" />\n"
end
end | ruby | def to_thumb(c)
current = self.__send__(c)
if model.respond_to?(:stash_reflection) && model.stash_reflection.key?(c)
!current.nil? && current[:type][/^image\//] ? "<img src='#{file_url(c, 'stash_thumb.gif')}?#{::Time.now.to_i.to_s}' /><br />\n" : ''
else
"<img src='#{current}?#{::Time.now.to_i.to_s}' width='100' onerror=\"this.style.display='none'\" />\n"
end
end | [
"def",
"to_thumb",
"(",
"c",
")",
"current",
"=",
"self",
".",
"__send__",
"(",
"c",
")",
"if",
"model",
".",
"respond_to?",
"(",
":stash_reflection",
")",
"&&",
"model",
".",
"stash_reflection",
".",
"key?",
"(",
"c",
")",
"!",
"current",
".",
"nil?",
"&&",
"current",
"[",
":type",
"]",
"[",
"/",
"\\/",
"/",
"]",
"?",
"\"<img src='#{file_url(c, 'stash_thumb.gif')}?#{::Time.now.to_i.to_s}' /><br />\\n\"",
":",
"''",
"else",
"\"<img src='#{current}?#{::Time.now.to_i.to_s}' width='100' onerror=\\\"this.style.display='none'\\\" />\\n\"",
"end",
"end"
] | Provide a thumbnail for the column | [
"Provide",
"a",
"thumbnail",
"for",
"the",
"column"
] | c717df86dea0206487d9b3ee340fbd529fc7b91f | https://github.com/mig-hub/sequel-crushyform/blob/c717df86dea0206487d9b3ee340fbd529fc7b91f/lib/sequel_crushyform.rb#L151-L158 | train |
tbuehlmann/ponder | lib/ponder/thaum.rb | Ponder.Thaum.parse | def parse(message)
message.chomp!
if message =~ /^PING \S+$/
if @config.hide_ping_pongs
send_data message.sub(/PING/, 'PONG')
else
@loggers.info "<< #{message}"
raw message.sub(/PING/, 'PONG')
end
else
@loggers.info "<< #{message}"
event_data = IRC::Events::Parser.parse(message, @isupport['CHANTYPES'])
parse_event_data(event_data) unless event_data.empty?
end
end | ruby | def parse(message)
message.chomp!
if message =~ /^PING \S+$/
if @config.hide_ping_pongs
send_data message.sub(/PING/, 'PONG')
else
@loggers.info "<< #{message}"
raw message.sub(/PING/, 'PONG')
end
else
@loggers.info "<< #{message}"
event_data = IRC::Events::Parser.parse(message, @isupport['CHANTYPES'])
parse_event_data(event_data) unless event_data.empty?
end
end | [
"def",
"parse",
"(",
"message",
")",
"message",
".",
"chomp!",
"if",
"message",
"=~",
"/",
"\\S",
"/",
"if",
"@config",
".",
"hide_ping_pongs",
"send_data",
"message",
".",
"sub",
"(",
"/",
"/",
",",
"'PONG'",
")",
"else",
"@loggers",
".",
"info",
"\"<< #{message}\"",
"raw",
"message",
".",
"sub",
"(",
"/",
"/",
",",
"'PONG'",
")",
"end",
"else",
"@loggers",
".",
"info",
"\"<< #{message}\"",
"event_data",
"=",
"IRC",
"::",
"Events",
"::",
"Parser",
".",
"parse",
"(",
"message",
",",
"@isupport",
"[",
"'CHANTYPES'",
"]",
")",
"parse_event_data",
"(",
"event_data",
")",
"unless",
"event_data",
".",
"empty?",
"end",
"end"
] | parsing incoming traffic | [
"parsing",
"incoming",
"traffic"
] | 930912e1b78b41afa1359121aca46197e9edff9c | https://github.com/tbuehlmann/ponder/blob/930912e1b78b41afa1359121aca46197e9edff9c/lib/ponder/thaum.rb#L79-L94 | train |
tbuehlmann/ponder | lib/ponder/thaum.rb | Ponder.Thaum.setup_default_callbacks | def setup_default_callbacks
on :query, /^\001PING \d+\001$/ do |event_data|
time = event_data[:message].scan(/\d+/)[0]
notice event_data[:nick], "\001PING #{time}\001"
end
on :query, /^\001VERSION\001$/ do |event_data|
notice event_data[:nick], "\001VERSION Ponder #{Ponder::VERSION} (https://github.com/tbuehlmann/ponder)\001"
end
on :query, /^\001TIME\001$/ do |event_data|
notice event_data[:nick], "\001TIME #{Time.now.strftime('%a %b %d %H:%M:%S %Y')}\001"
end
on 005 do |event_data|
@isupport.parse event_data[:params]
end
end | ruby | def setup_default_callbacks
on :query, /^\001PING \d+\001$/ do |event_data|
time = event_data[:message].scan(/\d+/)[0]
notice event_data[:nick], "\001PING #{time}\001"
end
on :query, /^\001VERSION\001$/ do |event_data|
notice event_data[:nick], "\001VERSION Ponder #{Ponder::VERSION} (https://github.com/tbuehlmann/ponder)\001"
end
on :query, /^\001TIME\001$/ do |event_data|
notice event_data[:nick], "\001TIME #{Time.now.strftime('%a %b %d %H:%M:%S %Y')}\001"
end
on 005 do |event_data|
@isupport.parse event_data[:params]
end
end | [
"def",
"setup_default_callbacks",
"on",
":query",
",",
"/",
"\\001",
"\\d",
"\\001",
"/",
"do",
"|",
"event_data",
"|",
"time",
"=",
"event_data",
"[",
":message",
"]",
".",
"scan",
"(",
"/",
"\\d",
"/",
")",
"[",
"0",
"]",
"notice",
"event_data",
"[",
":nick",
"]",
",",
"\"\\001PING #{time}\\001\"",
"end",
"on",
":query",
",",
"/",
"\\001",
"\\001",
"/",
"do",
"|",
"event_data",
"|",
"notice",
"event_data",
"[",
":nick",
"]",
",",
"\"\\001VERSION Ponder #{Ponder::VERSION} (https://github.com/tbuehlmann/ponder)\\001\"",
"end",
"on",
":query",
",",
"/",
"\\001",
"\\001",
"/",
"do",
"|",
"event_data",
"|",
"notice",
"event_data",
"[",
":nick",
"]",
",",
"\"\\001TIME #{Time.now.strftime('%a %b %d %H:%M:%S %Y')}\\001\"",
"end",
"on",
"005",
"do",
"|",
"event_data",
"|",
"@isupport",
".",
"parse",
"event_data",
"[",
":params",
"]",
"end",
"end"
] | Default callbacks for PING, VERSION, TIME and ISUPPORT processing. | [
"Default",
"callbacks",
"for",
"PING",
"VERSION",
"TIME",
"and",
"ISUPPORT",
"processing",
"."
] | 930912e1b78b41afa1359121aca46197e9edff9c | https://github.com/tbuehlmann/ponder/blob/930912e1b78b41afa1359121aca46197e9edff9c/lib/ponder/thaum.rb#L135-L152 | train |
Deradon/Rails-LookUpTable | lib/look_up_table/cache.rb | LookUpTable.ClassMethods.lut_write_to_cache | def lut_write_to_cache(lut_key)
if lut_options(lut_key)[:sql_mode]
count = lut_write_to_cache_sql_mode(lut_key)
else
count = lut_write_to_cache_no_sql_mode(lut_key)
end
# HACK: Writing a \0 to terminate batch_items
lut_write_cache_item(lut_key, count, nil)
end | ruby | def lut_write_to_cache(lut_key)
if lut_options(lut_key)[:sql_mode]
count = lut_write_to_cache_sql_mode(lut_key)
else
count = lut_write_to_cache_no_sql_mode(lut_key)
end
# HACK: Writing a \0 to terminate batch_items
lut_write_cache_item(lut_key, count, nil)
end | [
"def",
"lut_write_to_cache",
"(",
"lut_key",
")",
"if",
"lut_options",
"(",
"lut_key",
")",
"[",
":sql_mode",
"]",
"count",
"=",
"lut_write_to_cache_sql_mode",
"(",
"lut_key",
")",
"else",
"count",
"=",
"lut_write_to_cache_no_sql_mode",
"(",
"lut_key",
")",
"end",
"lut_write_cache_item",
"(",
"lut_key",
",",
"count",
",",
"nil",
")",
"end"
] | Write a LookUpTable into Cache | [
"Write",
"a",
"LookUpTable",
"into",
"Cache"
] | da873f48b039ef01ed3d3820d3a59d8886281be1 | https://github.com/Deradon/Rails-LookUpTable/blob/da873f48b039ef01ed3d3820d3a59d8886281be1/lib/look_up_table/cache.rb#L41-L50 | train |
charmkit/charmkit | lib/charmkit/helpers/template.rb | Charmkit.Helpers.template | def template(src, dst, **context)
rendered = TemplateRenderer.render(File.read(src), context)
File.write(dst, rendered)
end | ruby | def template(src, dst, **context)
rendered = TemplateRenderer.render(File.read(src), context)
File.write(dst, rendered)
end | [
"def",
"template",
"(",
"src",
",",
"dst",
",",
"**",
"context",
")",
"rendered",
"=",
"TemplateRenderer",
".",
"render",
"(",
"File",
".",
"read",
"(",
"src",
")",
",",
"context",
")",
"File",
".",
"write",
"(",
"dst",
",",
"rendered",
")",
"end"
] | Reads from a erb file and renders the content with context
@param src String - file path of template
@param dst String - file path location to save
@param context Hash - parametized variables to pass to template
@return Boolean
@example
template('examples/my-demo-charm/templates/vhost.conf',
'/tmp/nginx-data.conf',
public_address: 'localhost',
app_path: '/srv/app') | [
"Reads",
"from",
"a",
"erb",
"file",
"and",
"renders",
"the",
"content",
"with",
"context"
] | cdb51bbbe0a14c681edc00fdeb318307b80fd613 | https://github.com/charmkit/charmkit/blob/cdb51bbbe0a14c681edc00fdeb318307b80fd613/lib/charmkit/helpers/template.rb#L30-L33 | train |
charmkit/charmkit | lib/charmkit/helpers/template.rb | Charmkit.Helpers.inline_template | def inline_template(name, dst, **context)
templates = {}
begin
app, data = File.read(caller.first.split(":").first).split("__END__", 2)
rescue Errno::ENOENT
app, data = nil
end
data.strip!
if data
template = nil
data.each_line do |line|
if line =~ /^@@\s*(.*\S)\s*$/
template = String.new
templates[$1.to_s] = template
elsif
template << line
end
end
begin
rendered = TemplateRenderer.render(templates[name], context)
rescue
puts "Unable to load inline template #{name}"
exit 1
end
File.write(dst, rendered)
end
end | ruby | def inline_template(name, dst, **context)
templates = {}
begin
app, data = File.read(caller.first.split(":").first).split("__END__", 2)
rescue Errno::ENOENT
app, data = nil
end
data.strip!
if data
template = nil
data.each_line do |line|
if line =~ /^@@\s*(.*\S)\s*$/
template = String.new
templates[$1.to_s] = template
elsif
template << line
end
end
begin
rendered = TemplateRenderer.render(templates[name], context)
rescue
puts "Unable to load inline template #{name}"
exit 1
end
File.write(dst, rendered)
end
end | [
"def",
"inline_template",
"(",
"name",
",",
"dst",
",",
"**",
"context",
")",
"templates",
"=",
"{",
"}",
"begin",
"app",
",",
"data",
"=",
"File",
".",
"read",
"(",
"caller",
".",
"first",
".",
"split",
"(",
"\":\"",
")",
".",
"first",
")",
".",
"split",
"(",
"\"__END__\"",
",",
"2",
")",
"rescue",
"Errno",
"::",
"ENOENT",
"app",
",",
"data",
"=",
"nil",
"end",
"data",
".",
"strip!",
"if",
"data",
"template",
"=",
"nil",
"data",
".",
"each_line",
"do",
"|",
"line",
"|",
"if",
"line",
"=~",
"/",
"\\s",
"\\S",
"\\s",
"/",
"template",
"=",
"String",
".",
"new",
"templates",
"[",
"$1",
".",
"to_s",
"]",
"=",
"template",
"elsif",
"template",
"<<",
"line",
"end",
"end",
"begin",
"rendered",
"=",
"TemplateRenderer",
".",
"render",
"(",
"templates",
"[",
"name",
"]",
",",
"context",
")",
"rescue",
"puts",
"\"Unable to load inline template #{name}\"",
"exit",
"1",
"end",
"File",
".",
"write",
"(",
"dst",
",",
"rendered",
")",
"end",
"end"
] | Reads from a embedded template in the rake task itself.
@param src String - The data found after __END__
@param dst String - Save location
@param context Hash - variables to pass into template
@return Boolean
@example
inline_template('vhost.conf',
'/etc/nginx/sites-enabled/default')
server_name: "example.com")
__END__
@@ vhost.conf
server { name <%= server_name %> } | [
"Reads",
"from",
"a",
"embedded",
"template",
"in",
"the",
"rake",
"task",
"itself",
"."
] | cdb51bbbe0a14c681edc00fdeb318307b80fd613 | https://github.com/charmkit/charmkit/blob/cdb51bbbe0a14c681edc00fdeb318307b80fd613/lib/charmkit/helpers/template.rb#L50-L78 | train |
conversation/raca | lib/raca/container.rb | Raca.Container.delete | def delete(key)
log "deleting #{key} from #{container_path}"
object_path = File.join(container_path, Raca::Util.url_encode(key))
response = storage_client.delete(object_path)
(200..299).cover?(response.code.to_i)
end | ruby | def delete(key)
log "deleting #{key} from #{container_path}"
object_path = File.join(container_path, Raca::Util.url_encode(key))
response = storage_client.delete(object_path)
(200..299).cover?(response.code.to_i)
end | [
"def",
"delete",
"(",
"key",
")",
"log",
"\"deleting #{key} from #{container_path}\"",
"object_path",
"=",
"File",
".",
"join",
"(",
"container_path",
",",
"Raca",
"::",
"Util",
".",
"url_encode",
"(",
"key",
")",
")",
"response",
"=",
"storage_client",
".",
"delete",
"(",
"object_path",
")",
"(",
"200",
"..",
"299",
")",
".",
"cover?",
"(",
"response",
".",
"code",
".",
"to_i",
")",
"end"
] | Delete +key+ from the container. If the container is on the CDN, the object will
still be served from the CDN until the TTL expires. | [
"Delete",
"+",
"key",
"+",
"from",
"the",
"container",
".",
"If",
"the",
"container",
"is",
"on",
"the",
"CDN",
"the",
"object",
"will",
"still",
"be",
"served",
"from",
"the",
"CDN",
"until",
"the",
"TTL",
"expires",
"."
] | fa69dfde22359cc0e06f655055be4eadcc7019c0 | https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/container.rb#L50-L55 | train |
conversation/raca | lib/raca/container.rb | Raca.Container.object_metadata | def object_metadata(key)
object_path = File.join(container_path, Raca::Util.url_encode(key))
log "Requesting metadata from #{object_path}"
response = storage_client.head(object_path)
{
:content_type => response["Content-Type"],
:bytes => response["Content-Length"].to_i
}
end | ruby | def object_metadata(key)
object_path = File.join(container_path, Raca::Util.url_encode(key))
log "Requesting metadata from #{object_path}"
response = storage_client.head(object_path)
{
:content_type => response["Content-Type"],
:bytes => response["Content-Length"].to_i
}
end | [
"def",
"object_metadata",
"(",
"key",
")",
"object_path",
"=",
"File",
".",
"join",
"(",
"container_path",
",",
"Raca",
"::",
"Util",
".",
"url_encode",
"(",
"key",
")",
")",
"log",
"\"Requesting metadata from #{object_path}\"",
"response",
"=",
"storage_client",
".",
"head",
"(",
"object_path",
")",
"{",
":content_type",
"=>",
"response",
"[",
"\"Content-Type\"",
"]",
",",
":bytes",
"=>",
"response",
"[",
"\"Content-Length\"",
"]",
".",
"to_i",
"}",
"end"
] | Returns some metadata about a single object in this container. | [
"Returns",
"some",
"metadata",
"about",
"a",
"single",
"object",
"in",
"this",
"container",
"."
] | fa69dfde22359cc0e06f655055be4eadcc7019c0 | https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/container.rb#L75-L84 | train |
conversation/raca | lib/raca/container.rb | Raca.Container.download | def download(key, filepath)
log "downloading #{key} from #{container_path}"
object_path = File.join(container_path, Raca::Util.url_encode(key))
outer_response = storage_client.get(object_path) do |response|
File.open(filepath, 'wb') do |io|
response.read_body do |chunk|
io.write(chunk)
end
end
end
outer_response["Content-Length"].to_i
end | ruby | def download(key, filepath)
log "downloading #{key} from #{container_path}"
object_path = File.join(container_path, Raca::Util.url_encode(key))
outer_response = storage_client.get(object_path) do |response|
File.open(filepath, 'wb') do |io|
response.read_body do |chunk|
io.write(chunk)
end
end
end
outer_response["Content-Length"].to_i
end | [
"def",
"download",
"(",
"key",
",",
"filepath",
")",
"log",
"\"downloading #{key} from #{container_path}\"",
"object_path",
"=",
"File",
".",
"join",
"(",
"container_path",
",",
"Raca",
"::",
"Util",
".",
"url_encode",
"(",
"key",
")",
")",
"outer_response",
"=",
"storage_client",
".",
"get",
"(",
"object_path",
")",
"do",
"|",
"response",
"|",
"File",
".",
"open",
"(",
"filepath",
",",
"'wb'",
")",
"do",
"|",
"io",
"|",
"response",
".",
"read_body",
"do",
"|",
"chunk",
"|",
"io",
".",
"write",
"(",
"chunk",
")",
"end",
"end",
"end",
"outer_response",
"[",
"\"Content-Length\"",
"]",
".",
"to_i",
"end"
] | Download the object at key into a local file at filepath.
Returns the number of downloaded bytes. | [
"Download",
"the",
"object",
"at",
"key",
"into",
"a",
"local",
"file",
"at",
"filepath",
"."
] | fa69dfde22359cc0e06f655055be4eadcc7019c0 | https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/container.rb#L90-L101 | train |
conversation/raca | lib/raca/container.rb | Raca.Container.list | def list(options = {})
max = options.fetch(:max, 100_000_000)
marker = options.fetch(:marker, nil)
prefix = options.fetch(:prefix, nil)
details = options.fetch(:details, nil)
limit = [max, MAX_ITEMS_PER_LIST].min
log "retrieving up to #{max} items from #{container_path}"
request_path = list_request_path(marker, prefix, details, limit)
result = storage_client.get(request_path).body || ""
if details
result = JSON.parse(result)
else
result = result.split("\n")
end
result.tap {|items|
if max <= limit
log "Got #{items.length} items; we don't need any more."
elsif items.length < limit
log "Got #{items.length} items; there can't be any more."
else
log "Got #{items.length} items; requesting #{limit} more."
details ? marker = items.last["name"] : marker = items.last
items.concat list(max: max-items.length, marker: marker, prefix: prefix, details: details)
end
}
end | ruby | def list(options = {})
max = options.fetch(:max, 100_000_000)
marker = options.fetch(:marker, nil)
prefix = options.fetch(:prefix, nil)
details = options.fetch(:details, nil)
limit = [max, MAX_ITEMS_PER_LIST].min
log "retrieving up to #{max} items from #{container_path}"
request_path = list_request_path(marker, prefix, details, limit)
result = storage_client.get(request_path).body || ""
if details
result = JSON.parse(result)
else
result = result.split("\n")
end
result.tap {|items|
if max <= limit
log "Got #{items.length} items; we don't need any more."
elsif items.length < limit
log "Got #{items.length} items; there can't be any more."
else
log "Got #{items.length} items; requesting #{limit} more."
details ? marker = items.last["name"] : marker = items.last
items.concat list(max: max-items.length, marker: marker, prefix: prefix, details: details)
end
}
end | [
"def",
"list",
"(",
"options",
"=",
"{",
"}",
")",
"max",
"=",
"options",
".",
"fetch",
"(",
":max",
",",
"100_000_000",
")",
"marker",
"=",
"options",
".",
"fetch",
"(",
":marker",
",",
"nil",
")",
"prefix",
"=",
"options",
".",
"fetch",
"(",
":prefix",
",",
"nil",
")",
"details",
"=",
"options",
".",
"fetch",
"(",
":details",
",",
"nil",
")",
"limit",
"=",
"[",
"max",
",",
"MAX_ITEMS_PER_LIST",
"]",
".",
"min",
"log",
"\"retrieving up to #{max} items from #{container_path}\"",
"request_path",
"=",
"list_request_path",
"(",
"marker",
",",
"prefix",
",",
"details",
",",
"limit",
")",
"result",
"=",
"storage_client",
".",
"get",
"(",
"request_path",
")",
".",
"body",
"||",
"\"\"",
"if",
"details",
"result",
"=",
"JSON",
".",
"parse",
"(",
"result",
")",
"else",
"result",
"=",
"result",
".",
"split",
"(",
"\"\\n\"",
")",
"end",
"result",
".",
"tap",
"{",
"|",
"items",
"|",
"if",
"max",
"<=",
"limit",
"log",
"\"Got #{items.length} items; we don't need any more.\"",
"elsif",
"items",
".",
"length",
"<",
"limit",
"log",
"\"Got #{items.length} items; there can't be any more.\"",
"else",
"log",
"\"Got #{items.length} items; requesting #{limit} more.\"",
"details",
"?",
"marker",
"=",
"items",
".",
"last",
"[",
"\"name\"",
"]",
":",
"marker",
"=",
"items",
".",
"last",
"items",
".",
"concat",
"list",
"(",
"max",
":",
"max",
"-",
"items",
".",
"length",
",",
"marker",
":",
"marker",
",",
"prefix",
":",
"prefix",
",",
"details",
":",
"details",
")",
"end",
"}",
"end"
] | Return an array of files in the container.
Supported options
max - the maximum number of items to return
marker - return items alphabetically after this key. Useful for pagination
prefix - only return items that start with this string
details - return extra details for each file - size, md5, etc | [
"Return",
"an",
"array",
"of",
"files",
"in",
"the",
"container",
"."
] | fa69dfde22359cc0e06f655055be4eadcc7019c0 | https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/container.rb#L112-L137 | train |
conversation/raca | lib/raca/container.rb | Raca.Container.metadata | def metadata
log "retrieving container metadata from #{container_path}"
response = storage_client.head(container_path)
custom = {}
response.each_capitalized_name { |name|
custom[name] = response[name] if name[/\AX-Container-Meta-/]
}
{
:objects => response["X-Container-Object-Count"].to_i,
:bytes => response["X-Container-Bytes-Used"].to_i,
:custom => custom,
}
end | ruby | def metadata
log "retrieving container metadata from #{container_path}"
response = storage_client.head(container_path)
custom = {}
response.each_capitalized_name { |name|
custom[name] = response[name] if name[/\AX-Container-Meta-/]
}
{
:objects => response["X-Container-Object-Count"].to_i,
:bytes => response["X-Container-Bytes-Used"].to_i,
:custom => custom,
}
end | [
"def",
"metadata",
"log",
"\"retrieving container metadata from #{container_path}\"",
"response",
"=",
"storage_client",
".",
"head",
"(",
"container_path",
")",
"custom",
"=",
"{",
"}",
"response",
".",
"each_capitalized_name",
"{",
"|",
"name",
"|",
"custom",
"[",
"name",
"]",
"=",
"response",
"[",
"name",
"]",
"if",
"name",
"[",
"/",
"\\A",
"/",
"]",
"}",
"{",
":objects",
"=>",
"response",
"[",
"\"X-Container-Object-Count\"",
"]",
".",
"to_i",
",",
":bytes",
"=>",
"response",
"[",
"\"X-Container-Bytes-Used\"",
"]",
".",
"to_i",
",",
":custom",
"=>",
"custom",
",",
"}",
"end"
] | Return some basic stats on the current container. | [
"Return",
"some",
"basic",
"stats",
"on",
"the",
"current",
"container",
"."
] | fa69dfde22359cc0e06f655055be4eadcc7019c0 | https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/container.rb#L151-L163 | train |
conversation/raca | lib/raca/container.rb | Raca.Container.set_metadata | def set_metadata(headers)
log "setting headers for container #{container_path}"
response = storage_client.post(container_path, '', headers)
(200..299).cover?(response.code.to_i)
end | ruby | def set_metadata(headers)
log "setting headers for container #{container_path}"
response = storage_client.post(container_path, '', headers)
(200..299).cover?(response.code.to_i)
end | [
"def",
"set_metadata",
"(",
"headers",
")",
"log",
"\"setting headers for container #{container_path}\"",
"response",
"=",
"storage_client",
".",
"post",
"(",
"container_path",
",",
"''",
",",
"headers",
")",
"(",
"200",
"..",
"299",
")",
".",
"cover?",
"(",
"response",
".",
"code",
".",
"to_i",
")",
"end"
] | Set metadata headers on the container
headers = { "X-Container-Meta-Access-Control-Allow-Origin" => "*" }
container.set_metadata(headers)
Note: Rackspace requires some headers to begin with 'X-Container-Meta-' or other prefixes, e.g. when setting
'Access-Control-Allow-Origin', it needs to be set as 'X-Container-Meta-Access-Control-Allow-Origin'.
See: http://docs.rackspace.com/files/api/v1/cf-devguide/content/CORS_Container_Header-d1e1300.html
http://docs.rackspace.com/files/api/v1/cf-devguide/content/
POST_updateacontainermeta_v1__account___container__containerServicesOperations_d1e000.html | [
"Set",
"metadata",
"headers",
"on",
"the",
"container"
] | fa69dfde22359cc0e06f655055be4eadcc7019c0 | https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/container.rb#L176-L180 | train |
conversation/raca | lib/raca/container.rb | Raca.Container.cdn_metadata | def cdn_metadata
log "retrieving container CDN metadata from #{container_path}"
response = cdn_client.head(container_path)
{
:cdn_enabled => response["X-CDN-Enabled"] == "True",
:host => response["X-CDN-URI"],
:ssl_host => response["X-CDN-SSL-URI"],
:streaming_host => response["X-CDN-STREAMING-URI"],
:ttl => response["X-TTL"].to_i,
:log_retention => response["X-Log-Retention"] == "True"
}
end | ruby | def cdn_metadata
log "retrieving container CDN metadata from #{container_path}"
response = cdn_client.head(container_path)
{
:cdn_enabled => response["X-CDN-Enabled"] == "True",
:host => response["X-CDN-URI"],
:ssl_host => response["X-CDN-SSL-URI"],
:streaming_host => response["X-CDN-STREAMING-URI"],
:ttl => response["X-TTL"].to_i,
:log_retention => response["X-Log-Retention"] == "True"
}
end | [
"def",
"cdn_metadata",
"log",
"\"retrieving container CDN metadata from #{container_path}\"",
"response",
"=",
"cdn_client",
".",
"head",
"(",
"container_path",
")",
"{",
":cdn_enabled",
"=>",
"response",
"[",
"\"X-CDN-Enabled\"",
"]",
"==",
"\"True\"",
",",
":host",
"=>",
"response",
"[",
"\"X-CDN-URI\"",
"]",
",",
":ssl_host",
"=>",
"response",
"[",
"\"X-CDN-SSL-URI\"",
"]",
",",
":streaming_host",
"=>",
"response",
"[",
"\"X-CDN-STREAMING-URI\"",
"]",
",",
":ttl",
"=>",
"response",
"[",
"\"X-TTL\"",
"]",
".",
"to_i",
",",
":log_retention",
"=>",
"response",
"[",
"\"X-Log-Retention\"",
"]",
"==",
"\"True\"",
"}",
"end"
] | Return the key details for CDN access to this container. Can be called
on non CDN enabled containers, but the details won't make much sense. | [
"Return",
"the",
"key",
"details",
"for",
"CDN",
"access",
"to",
"this",
"container",
".",
"Can",
"be",
"called",
"on",
"non",
"CDN",
"enabled",
"containers",
"but",
"the",
"details",
"won",
"t",
"make",
"much",
"sense",
"."
] | fa69dfde22359cc0e06f655055be4eadcc7019c0 | https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/container.rb#L185-L196 | train |
conversation/raca | lib/raca/container.rb | Raca.Container.cdn_enable | def cdn_enable(ttl = 259200)
log "enabling CDN access to #{container_path} with a cache expiry of #{ttl / 60} minutes"
response = cdn_client.put(container_path, "X-TTL" => ttl.to_i.to_s)
(200..299).cover?(response.code.to_i)
end | ruby | def cdn_enable(ttl = 259200)
log "enabling CDN access to #{container_path} with a cache expiry of #{ttl / 60} minutes"
response = cdn_client.put(container_path, "X-TTL" => ttl.to_i.to_s)
(200..299).cover?(response.code.to_i)
end | [
"def",
"cdn_enable",
"(",
"ttl",
"=",
"259200",
")",
"log",
"\"enabling CDN access to #{container_path} with a cache expiry of #{ttl / 60} minutes\"",
"response",
"=",
"cdn_client",
".",
"put",
"(",
"container_path",
",",
"\"X-TTL\"",
"=>",
"ttl",
".",
"to_i",
".",
"to_s",
")",
"(",
"200",
"..",
"299",
")",
".",
"cover?",
"(",
"response",
".",
"code",
".",
"to_i",
")",
"end"
] | use this with caution, it will make EVERY object in the container publicly available
via the CDN. CDN enabling can be done via the web UI but only with a TTL of 72 hours.
Using the API it's possible to set a TTL of 50 years.
TTL is defined in seconds, default is 72 hours. | [
"use",
"this",
"with",
"caution",
"it",
"will",
"make",
"EVERY",
"object",
"in",
"the",
"container",
"publicly",
"available",
"via",
"the",
"CDN",
".",
"CDN",
"enabling",
"can",
"be",
"done",
"via",
"the",
"web",
"UI",
"but",
"only",
"with",
"a",
"TTL",
"of",
"72",
"hours",
".",
"Using",
"the",
"API",
"it",
"s",
"possible",
"to",
"set",
"a",
"TTL",
"of",
"50",
"years",
"."
] | fa69dfde22359cc0e06f655055be4eadcc7019c0 | https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/container.rb#L204-L209 | train |
conversation/raca | lib/raca/container.rb | Raca.Container.temp_url | def temp_url(object_key, temp_url_key, expires_at = Time.now.to_i + 60)
private_url("GET", object_key, temp_url_key, expires_at)
end | ruby | def temp_url(object_key, temp_url_key, expires_at = Time.now.to_i + 60)
private_url("GET", object_key, temp_url_key, expires_at)
end | [
"def",
"temp_url",
"(",
"object_key",
",",
"temp_url_key",
",",
"expires_at",
"=",
"Time",
".",
"now",
".",
"to_i",
"+",
"60",
")",
"private_url",
"(",
"\"GET\"",
",",
"object_key",
",",
"temp_url_key",
",",
"expires_at",
")",
"end"
] | Generate an expiring URL for downloading a file that is otherwise private.
Useful for providing temporary access to files. | [
"Generate",
"an",
"expiring",
"URL",
"for",
"downloading",
"a",
"file",
"that",
"is",
"otherwise",
"private",
".",
"Useful",
"for",
"providing",
"temporary",
"access",
"to",
"files",
"."
] | fa69dfde22359cc0e06f655055be4eadcc7019c0 | https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/container.rb#L214-L216 | train |
conversation/raca | lib/raca/container.rb | Raca.Container.temp_upload_url | def temp_upload_url(object_key, temp_url_key, expires_at = Time.now.to_i + 60)
private_url("PUT", object_key, temp_url_key, expires_at)
end | ruby | def temp_upload_url(object_key, temp_url_key, expires_at = Time.now.to_i + 60)
private_url("PUT", object_key, temp_url_key, expires_at)
end | [
"def",
"temp_upload_url",
"(",
"object_key",
",",
"temp_url_key",
",",
"expires_at",
"=",
"Time",
".",
"now",
".",
"to_i",
"+",
"60",
")",
"private_url",
"(",
"\"PUT\"",
",",
"object_key",
",",
"temp_url_key",
",",
"expires_at",
")",
"end"
] | Generate a temporary URL for uploading a file to a private container. Anyone
can perform a PUT request to the URL returned from this method and an object
will be created in the container. | [
"Generate",
"a",
"temporary",
"URL",
"for",
"uploading",
"a",
"file",
"to",
"a",
"private",
"container",
".",
"Anyone",
"can",
"perform",
"a",
"PUT",
"request",
"to",
"the",
"URL",
"returned",
"from",
"this",
"method",
"and",
"an",
"object",
"will",
"be",
"created",
"in",
"the",
"container",
"."
] | fa69dfde22359cc0e06f655055be4eadcc7019c0 | https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/container.rb#L228-L230 | train |
conversation/raca | lib/raca/container.rb | Raca.Container.list_request_path | def list_request_path(marker, prefix, details, limit)
query_string = "limit=#{limit}"
query_string += "&marker=#{Raca::Util.url_encode(marker)}" if marker
query_string += "&prefix=#{Raca::Util.url_encode(prefix)}" if prefix
query_string += "&format=json" if details
container_path + "?#{query_string}"
end | ruby | def list_request_path(marker, prefix, details, limit)
query_string = "limit=#{limit}"
query_string += "&marker=#{Raca::Util.url_encode(marker)}" if marker
query_string += "&prefix=#{Raca::Util.url_encode(prefix)}" if prefix
query_string += "&format=json" if details
container_path + "?#{query_string}"
end | [
"def",
"list_request_path",
"(",
"marker",
",",
"prefix",
",",
"details",
",",
"limit",
")",
"query_string",
"=",
"\"limit=#{limit}\"",
"query_string",
"+=",
"\"&marker=#{Raca::Util.url_encode(marker)}\"",
"if",
"marker",
"query_string",
"+=",
"\"&prefix=#{Raca::Util.url_encode(prefix)}\"",
"if",
"prefix",
"query_string",
"+=",
"\"&format=json\"",
"if",
"details",
"container_path",
"+",
"\"?#{query_string}\"",
"end"
] | build the request path for listing the contents of a container | [
"build",
"the",
"request",
"path",
"for",
"listing",
"the",
"contents",
"of",
"a",
"container"
] | fa69dfde22359cc0e06f655055be4eadcc7019c0 | https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/container.rb#L255-L261 | train |
sugaryourcoffee/timeleap | lib/syctimeleap/time_leap.rb | SycTimeleap.TimeLeap.method_missing | def method_missing(name, *args)
add_regex = %r{
^([ib])(?:n|ack)?
(?:\.|_|-| )?
(\d+)
(?:\.|_|-| )?
([dwmy])
(?:ays?|eeks?|onths?|ears?)?$
}x
weekday_regex = %r{
^(tod|tom|y)(?:a?y?|o?r?r?o?w?|e?s?t?e?r?d?a?y?)?$
}xi
next_weekday_regex = %r{
^(n|p)(?:e?x?t|r?e?v?i?o?u?s?)?
(?:\.|_| |-)?
(mo|tu|we|th|fr|sa|su)
(?:n?|e?s?|d?n?e?s?|u?r?s?|i?|t?u?r?|n?)(?:d?a?y?)$
}xi
next_weekday_in_regex = %r{
^(mo|tu|we|th|fr|sa|su)
(?:n?|e?s?|d?n?e?s?|u?r?s?|i?|t?u?r?|n?)(?:d?a?y?)(?:_?)
(i|b)
(?:n?|a?c?k?)(?:_?)
(\d+)(?:_?)([dwmy])(?:a?y?s?|e?e?k?s?|o?n?t?h?s?|e?a?r?s?)$
}xi
return add($1, $2, $3) if name =~ add_regex
return weekday($1) if name =~ weekday_regex
return next_weekday($1, $2) if name =~ next_weekday_regex
return next_weekday_in($1, $2, $3, $4) if name =~ next_weekday_in_regex
super
end | ruby | def method_missing(name, *args)
add_regex = %r{
^([ib])(?:n|ack)?
(?:\.|_|-| )?
(\d+)
(?:\.|_|-| )?
([dwmy])
(?:ays?|eeks?|onths?|ears?)?$
}x
weekday_regex = %r{
^(tod|tom|y)(?:a?y?|o?r?r?o?w?|e?s?t?e?r?d?a?y?)?$
}xi
next_weekday_regex = %r{
^(n|p)(?:e?x?t|r?e?v?i?o?u?s?)?
(?:\.|_| |-)?
(mo|tu|we|th|fr|sa|su)
(?:n?|e?s?|d?n?e?s?|u?r?s?|i?|t?u?r?|n?)(?:d?a?y?)$
}xi
next_weekday_in_regex = %r{
^(mo|tu|we|th|fr|sa|su)
(?:n?|e?s?|d?n?e?s?|u?r?s?|i?|t?u?r?|n?)(?:d?a?y?)(?:_?)
(i|b)
(?:n?|a?c?k?)(?:_?)
(\d+)(?:_?)([dwmy])(?:a?y?s?|e?e?k?s?|o?n?t?h?s?|e?a?r?s?)$
}xi
return add($1, $2, $3) if name =~ add_regex
return weekday($1) if name =~ weekday_regex
return next_weekday($1, $2) if name =~ next_weekday_regex
return next_weekday_in($1, $2, $3, $4) if name =~ next_weekday_in_regex
super
end | [
"def",
"method_missing",
"(",
"name",
",",
"*",
"args",
")",
"add_regex",
"=",
"%r{",
"\\.",
"\\d",
"\\.",
"}x",
"weekday_regex",
"=",
"%r{",
"}xi",
"next_weekday_regex",
"=",
"%r{",
"\\.",
"}xi",
"next_weekday_in_regex",
"=",
"%r{",
"\\d",
"}xi",
"return",
"add",
"(",
"$1",
",",
"$2",
",",
"$3",
")",
"if",
"name",
"=~",
"add_regex",
"return",
"weekday",
"(",
"$1",
")",
"if",
"name",
"=~",
"weekday_regex",
"return",
"next_weekday",
"(",
"$1",
",",
"$2",
")",
"if",
"name",
"=~",
"next_weekday_regex",
"return",
"next_weekday_in",
"(",
"$1",
",",
"$2",
",",
"$3",
",",
"$4",
")",
"if",
"name",
"=~",
"next_weekday_in_regex",
"super",
"end"
] | Creates a new Temp and initializes it with the current date if no date
is provided
Provides the date calculation methods dynamically | [
"Creates",
"a",
"new",
"Temp",
"and",
"initializes",
"it",
"with",
"the",
"current",
"date",
"if",
"no",
"date",
"is",
"provided",
"Provides",
"the",
"date",
"calculation",
"methods",
"dynamically"
] | f24e819c11f6bc7c423ad77dc71c5b76130e8c10 | https://github.com/sugaryourcoffee/timeleap/blob/f24e819c11f6bc7c423ad77dc71c5b76130e8c10/lib/syctimeleap/time_leap.rb#L28-L62 | train |
jtkendall/ruser | lib/ruser/person.rb | RUser.Person.convert | def convert(data)
data.each do |k, v|
k = KEYS[k] if KEYS.include?(k)
v = v.to_s if k.eql? 'zip'
if NIDT.include?(k)
instance_variable_set('@nidt', k)
k = 'nidn'
v = v.to_s
end
var_set(k, v)
end
end | ruby | def convert(data)
data.each do |k, v|
k = KEYS[k] if KEYS.include?(k)
v = v.to_s if k.eql? 'zip'
if NIDT.include?(k)
instance_variable_set('@nidt', k)
k = 'nidn'
v = v.to_s
end
var_set(k, v)
end
end | [
"def",
"convert",
"(",
"data",
")",
"data",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"k",
"=",
"KEYS",
"[",
"k",
"]",
"if",
"KEYS",
".",
"include?",
"(",
"k",
")",
"v",
"=",
"v",
".",
"to_s",
"if",
"k",
".",
"eql?",
"'zip'",
"if",
"NIDT",
".",
"include?",
"(",
"k",
")",
"instance_variable_set",
"(",
"'@nidt'",
",",
"k",
")",
"k",
"=",
"'nidn'",
"v",
"=",
"v",
".",
"to_s",
"end",
"var_set",
"(",
"k",
",",
"v",
")",
"end",
"end"
] | Creates a new person object
@param [Hash] data the data used to create the user
@return [Person]
Converts a hash to instance variables
@param [Hash] data the data used to create the instance variables | [
"Creates",
"a",
"new",
"person",
"object"
] | 2d038c65da8f4710a1e1b7fddabaab7a2f771172 | https://github.com/jtkendall/ruser/blob/2d038c65da8f4710a1e1b7fddabaab7a2f771172/lib/ruser/person.rb#L107-L120 | train |
jtkendall/ruser | lib/ruser/person.rb | RUser.Person.var_set | def var_set(k, v)
varget = proc { instance_variable_get("@#{k}") }
varset = proc { |y| instance_variable_set("@#{k}", y) }
v.is_a?(Hash) ? convert(v) : instance_variable_set("@#{k}", v)
self.class.send(:define_method, k, varget)
self.class.send(:define_method, "#{k}=", varset)
end | ruby | def var_set(k, v)
varget = proc { instance_variable_get("@#{k}") }
varset = proc { |y| instance_variable_set("@#{k}", y) }
v.is_a?(Hash) ? convert(v) : instance_variable_set("@#{k}", v)
self.class.send(:define_method, k, varget)
self.class.send(:define_method, "#{k}=", varset)
end | [
"def",
"var_set",
"(",
"k",
",",
"v",
")",
"varget",
"=",
"proc",
"{",
"instance_variable_get",
"(",
"\"@#{k}\"",
")",
"}",
"varset",
"=",
"proc",
"{",
"|",
"y",
"|",
"instance_variable_set",
"(",
"\"@#{k}\"",
",",
"y",
")",
"}",
"v",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"convert",
"(",
"v",
")",
":",
"instance_variable_set",
"(",
"\"@#{k}\"",
",",
"v",
")",
"self",
".",
"class",
".",
"send",
"(",
":define_method",
",",
"k",
",",
"varget",
")",
"self",
".",
"class",
".",
"send",
"(",
":define_method",
",",
"\"#{k}=\"",
",",
"varset",
")",
"end"
] | Sets all instance variables
@param [String] k the key used to create the instance variables
@param [String] v the value used to create the instance variables | [
"Sets",
"all",
"instance",
"variables"
] | 2d038c65da8f4710a1e1b7fddabaab7a2f771172 | https://github.com/jtkendall/ruser/blob/2d038c65da8f4710a1e1b7fddabaab7a2f771172/lib/ruser/person.rb#L126-L132 | train |
gregspurrier/has_enumeration | lib/has_enumeration/aggregate_conditions_override.rb | HasEnumeration.AggregateConditionsOverride.expand_hash_conditions_for_aggregates | def expand_hash_conditions_for_aggregates(attrs)
expanded_attrs = attrs.dup
attr_enumeration_mapping_classes.each do |attr, klass|
if expanded_attrs[attr].is_a?(Symbol)
expanded_attrs[attr] = klass.from_sym(expanded_attrs[attr])
end
end
super(expanded_attrs)
end | ruby | def expand_hash_conditions_for_aggregates(attrs)
expanded_attrs = attrs.dup
attr_enumeration_mapping_classes.each do |attr, klass|
if expanded_attrs[attr].is_a?(Symbol)
expanded_attrs[attr] = klass.from_sym(expanded_attrs[attr])
end
end
super(expanded_attrs)
end | [
"def",
"expand_hash_conditions_for_aggregates",
"(",
"attrs",
")",
"expanded_attrs",
"=",
"attrs",
".",
"dup",
"attr_enumeration_mapping_classes",
".",
"each",
"do",
"|",
"attr",
",",
"klass",
"|",
"if",
"expanded_attrs",
"[",
"attr",
"]",
".",
"is_a?",
"(",
"Symbol",
")",
"expanded_attrs",
"[",
"attr",
"]",
"=",
"klass",
".",
"from_sym",
"(",
"expanded_attrs",
"[",
"attr",
"]",
")",
"end",
"end",
"super",
"(",
"expanded_attrs",
")",
"end"
] | Override the aggregate hash conditions behavior to coerce has_enumeration
attributes that show up in finder options as symbols into instances of
the aggregate class before hash expansion. | [
"Override",
"the",
"aggregate",
"hash",
"conditions",
"behavior",
"to",
"coerce",
"has_enumeration",
"attributes",
"that",
"show",
"up",
"in",
"finder",
"options",
"as",
"symbols",
"into",
"instances",
"of",
"the",
"aggregate",
"class",
"before",
"hash",
"expansion",
"."
] | 40487c5b4958364ca6acaab3f05561ae0dca073e | https://github.com/gregspurrier/has_enumeration/blob/40487c5b4958364ca6acaab3f05561ae0dca073e/lib/has_enumeration/aggregate_conditions_override.rb#L6-L14 | train |
Stex/petra | lib/petra/exceptions.rb | Petra.ValueComparisonError.ignore! | def ignore!(update_value: false)
Petra.current_transaction.current_section.log_read_integrity_override(object,
attribute: attribute,
external_value: external_value,
update_value: update_value)
end | ruby | def ignore!(update_value: false)
Petra.current_transaction.current_section.log_read_integrity_override(object,
attribute: attribute,
external_value: external_value,
update_value: update_value)
end | [
"def",
"ignore!",
"(",
"update_value",
":",
"false",
")",
"Petra",
".",
"current_transaction",
".",
"current_section",
".",
"log_read_integrity_override",
"(",
"object",
",",
"attribute",
":",
"attribute",
",",
"external_value",
":",
"external_value",
",",
"update_value",
":",
"update_value",
")",
"end"
] | The new external attribute value
Tells the current transaction to ignore further errors of this kind
until the attribute value is changed again externally.
@param [Boolean] update_value
If set to +true+, the read set entry for this attribute is updated with the
new external value. This means that the new value will be visible inside of
the transaction until it changes again.
Otherwise, the exception is completely ignored and will have no impact
on the values displayed inside the transaction. | [
"The",
"new",
"external",
"attribute",
"value"
] | 00e16e54c387289fd9049d6032dc0de79339ea16 | https://github.com/Stex/petra/blob/00e16e54c387289fd9049d6032dc0de79339ea16/lib/petra/exceptions.rb#L100-L105 | train |
Stex/petra | lib/petra/exceptions.rb | Petra.WriteClashError.undo_changes! | def undo_changes!
Petra.current_transaction.current_section.log_attribute_change_veto(object,
attribute: attribute,
external_value: external_value)
end | ruby | def undo_changes!
Petra.current_transaction.current_section.log_attribute_change_veto(object,
attribute: attribute,
external_value: external_value)
end | [
"def",
"undo_changes!",
"Petra",
".",
"current_transaction",
".",
"current_section",
".",
"log_attribute_change_veto",
"(",
"object",
",",
"attribute",
":",
"attribute",
",",
"external_value",
":",
"external_value",
")",
"end"
] | Tells the transaction to ignore all changes previously done to the current
attribute in the transaction. | [
"Tells",
"the",
"transaction",
"to",
"ignore",
"all",
"changes",
"previously",
"done",
"to",
"the",
"current",
"attribute",
"in",
"the",
"transaction",
"."
] | 00e16e54c387289fd9049d6032dc0de79339ea16 | https://github.com/Stex/petra/blob/00e16e54c387289fd9049d6032dc0de79339ea16/lib/petra/exceptions.rb#L127-L131 | train |
26fe/sem4r | lib/sem4r_cli/commands/cmd_report.rb | Sem4rCli.CommandReport.download | def download(args)
if args.length != 1
puts "missing report id for 'download' subcommand"
return false
end
report_id = args[0].to_i
report = @common_args.account.reports.find { |r| r.id == report_id }
if report.nil?
puts "report '#{report_id}' not found"
return false
end
if report.status != 'Completed'
puts "cannot download report with status '#{report.status}'"
return false
end
path_name = "test_report.xml"
puts "Download report #{report.id} in #{path_name}"
report.download(path_name)
true
end | ruby | def download(args)
if args.length != 1
puts "missing report id for 'download' subcommand"
return false
end
report_id = args[0].to_i
report = @common_args.account.reports.find { |r| r.id == report_id }
if report.nil?
puts "report '#{report_id}' not found"
return false
end
if report.status != 'Completed'
puts "cannot download report with status '#{report.status}'"
return false
end
path_name = "test_report.xml"
puts "Download report #{report.id} in #{path_name}"
report.download(path_name)
true
end | [
"def",
"download",
"(",
"args",
")",
"if",
"args",
".",
"length",
"!=",
"1",
"puts",
"\"missing report id for 'download' subcommand\"",
"return",
"false",
"end",
"report_id",
"=",
"args",
"[",
"0",
"]",
".",
"to_i",
"report",
"=",
"@common_args",
".",
"account",
".",
"reports",
".",
"find",
"{",
"|",
"r",
"|",
"r",
".",
"id",
"==",
"report_id",
"}",
"if",
"report",
".",
"nil?",
"puts",
"\"report '#{report_id}' not found\"",
"return",
"false",
"end",
"if",
"report",
".",
"status",
"!=",
"'Completed'",
"puts",
"\"cannot download report with status '#{report.status}'\"",
"return",
"false",
"end",
"path_name",
"=",
"\"test_report.xml\"",
"puts",
"\"Download report #{report.id} in #{path_name}\"",
"report",
".",
"download",
"(",
"path_name",
")",
"true",
"end"
] | download a v13 report | [
"download",
"a",
"v13",
"report"
] | 2326404f98b9c2833549fcfda078d39c9954a0fa | https://github.com/26fe/sem4r/blob/2326404f98b9c2833549fcfda078d39c9954a0fa/lib/sem4r_cli/commands/cmd_report.rb#L96-L118 | train |
26fe/sem4r | lib/sem4r_cli/commands/cmd_report.rb | Sem4rCli.CommandReport.schedule | def schedule(argv)
report = @account.report do
name 'boh'
type 'Url'
aggregation 'Daily'
cross_client true
zero_impression true
start_day '2010-01-01'
end_day '2010-01-30'
column "CustomerName"
column "ExternalCustomerId"
column "CampaignStatus"
column "Campaign"
column "CampaignId"
column "AdGroup"
column "AdGroupId"
column "AdGroupStatus"
column "QualityScore"
column "FirstPageCpc"
column "Keyword"
column "KeywordId"
column "KeywordTypeDisplay"
column "DestinationURL"
column "Impressions"
column "Clicks"
column "CTR"
column "CPC"
column "MaximumCPC"
column "Cost"
column "AveragePosition"
end
unless report.validate
puts "report not valid"
exit
end
puts "scheduled job"
job = report.schedule
job.wait(10) { |report, status| puts "status #{status}" }
report.download("test_report.xml")
true
end | ruby | def schedule(argv)
report = @account.report do
name 'boh'
type 'Url'
aggregation 'Daily'
cross_client true
zero_impression true
start_day '2010-01-01'
end_day '2010-01-30'
column "CustomerName"
column "ExternalCustomerId"
column "CampaignStatus"
column "Campaign"
column "CampaignId"
column "AdGroup"
column "AdGroupId"
column "AdGroupStatus"
column "QualityScore"
column "FirstPageCpc"
column "Keyword"
column "KeywordId"
column "KeywordTypeDisplay"
column "DestinationURL"
column "Impressions"
column "Clicks"
column "CTR"
column "CPC"
column "MaximumCPC"
column "Cost"
column "AveragePosition"
end
unless report.validate
puts "report not valid"
exit
end
puts "scheduled job"
job = report.schedule
job.wait(10) { |report, status| puts "status #{status}" }
report.download("test_report.xml")
true
end | [
"def",
"schedule",
"(",
"argv",
")",
"report",
"=",
"@account",
".",
"report",
"do",
"name",
"'boh'",
"type",
"'Url'",
"aggregation",
"'Daily'",
"cross_client",
"true",
"zero_impression",
"true",
"start_day",
"'2010-01-01'",
"end_day",
"'2010-01-30'",
"column",
"\"CustomerName\"",
"column",
"\"ExternalCustomerId\"",
"column",
"\"CampaignStatus\"",
"column",
"\"Campaign\"",
"column",
"\"CampaignId\"",
"column",
"\"AdGroup\"",
"column",
"\"AdGroupId\"",
"column",
"\"AdGroupStatus\"",
"column",
"\"QualityScore\"",
"column",
"\"FirstPageCpc\"",
"column",
"\"Keyword\"",
"column",
"\"KeywordId\"",
"column",
"\"KeywordTypeDisplay\"",
"column",
"\"DestinationURL\"",
"column",
"\"Impressions\"",
"column",
"\"Clicks\"",
"column",
"\"CTR\"",
"column",
"\"CPC\"",
"column",
"\"MaximumCPC\"",
"column",
"\"Cost\"",
"column",
"\"AveragePosition\"",
"end",
"unless",
"report",
".",
"validate",
"puts",
"\"report not valid\"",
"exit",
"end",
"puts",
"\"scheduled job\"",
"job",
"=",
"report",
".",
"schedule",
"job",
".",
"wait",
"(",
"10",
")",
"{",
"|",
"report",
",",
"status",
"|",
"puts",
"\"status #{status}\"",
"}",
"report",
".",
"download",
"(",
"\"test_report.xml\"",
")",
"true",
"end"
] | schedule and download a v13 report | [
"schedule",
"and",
"download",
"a",
"v13",
"report"
] | 2326404f98b9c2833549fcfda078d39c9954a0fa | https://github.com/26fe/sem4r/blob/2326404f98b9c2833549fcfda078d39c9954a0fa/lib/sem4r_cli/commands/cmd_report.rb#L123-L167 | train |
jmcaffee/tartancloth | spec/lib/matchers.rb | TartanCloth::Matchers.TransformMatcher.make_patch | def make_patch( expected, actual )
diffs = Diff::LCS.sdiff( expected.split("\n"), actual.split("\n"),
Diff::LCS::ContextDiffCallbacks )
maxcol = diffs.flatten.
collect {|d| [d.old_element.to_s.length, d.new_element.to_s.length ] }.
flatten.max || 0
maxcol += 4
patch = " %#{maxcol}s | %s\n" % [ "Expected", "Actual" ]
patch << diffs.collect do |changeset|
changeset.collect do |change|
"%s [%03d, %03d]: %#{maxcol}s | %-#{maxcol}s" % [
change.action,
change.old_position,
change.new_position,
change.old_element.inspect,
change.new_element.inspect,
]
end.join("\n")
end.join("\n---\n")
end | ruby | def make_patch( expected, actual )
diffs = Diff::LCS.sdiff( expected.split("\n"), actual.split("\n"),
Diff::LCS::ContextDiffCallbacks )
maxcol = diffs.flatten.
collect {|d| [d.old_element.to_s.length, d.new_element.to_s.length ] }.
flatten.max || 0
maxcol += 4
patch = " %#{maxcol}s | %s\n" % [ "Expected", "Actual" ]
patch << diffs.collect do |changeset|
changeset.collect do |change|
"%s [%03d, %03d]: %#{maxcol}s | %-#{maxcol}s" % [
change.action,
change.old_position,
change.new_position,
change.old_element.inspect,
change.new_element.inspect,
]
end.join("\n")
end.join("\n---\n")
end | [
"def",
"make_patch",
"(",
"expected",
",",
"actual",
")",
"diffs",
"=",
"Diff",
"::",
"LCS",
".",
"sdiff",
"(",
"expected",
".",
"split",
"(",
"\"\\n\"",
")",
",",
"actual",
".",
"split",
"(",
"\"\\n\"",
")",
",",
"Diff",
"::",
"LCS",
"::",
"ContextDiffCallbacks",
")",
"maxcol",
"=",
"diffs",
".",
"flatten",
".",
"collect",
"{",
"|",
"d",
"|",
"[",
"d",
".",
"old_element",
".",
"to_s",
".",
"length",
",",
"d",
".",
"new_element",
".",
"to_s",
".",
"length",
"]",
"}",
".",
"flatten",
".",
"max",
"||",
"0",
"maxcol",
"+=",
"4",
"patch",
"=",
"\" %#{maxcol}s | %s\\n\"",
"%",
"[",
"\"Expected\"",
",",
"\"Actual\"",
"]",
"patch",
"<<",
"diffs",
".",
"collect",
"do",
"|",
"changeset",
"|",
"changeset",
".",
"collect",
"do",
"|",
"change",
"|",
"\"%s [%03d, %03d]: %#{maxcol}s | %-#{maxcol}s\"",
"%",
"[",
"change",
".",
"action",
",",
"change",
".",
"old_position",
",",
"change",
".",
"new_position",
",",
"change",
".",
"old_element",
".",
"inspect",
",",
"change",
".",
"new_element",
".",
"inspect",
",",
"]",
"end",
".",
"join",
"(",
"\"\\n\"",
")",
"end",
".",
"join",
"(",
"\"\\n---\\n\"",
")",
"end"
] | Compute a patch between the given +expected+ output and the +actual+ output
and return it as a string. | [
"Compute",
"a",
"patch",
"between",
"the",
"given",
"+",
"expected",
"+",
"output",
"and",
"the",
"+",
"actual",
"+",
"output",
"and",
"return",
"it",
"as",
"a",
"string",
"."
] | ac4576613549c2389fa20b52046d9f5c89a6689a | https://github.com/jmcaffee/tartancloth/blob/ac4576613549c2389fa20b52046d9f5c89a6689a/spec/lib/matchers.rb#L48-L69 | train |
dpickett/polypaperclip | lib/polypaperclip.rb | Polypaperclip.ClassMethods.initialize_polypaperclip | def initialize_polypaperclip
if polypaperclip_definitions.nil?
after_save :save_attached_files
before_destroy :destroy_attached_files
has_many_attachments_association
write_inheritable_attribute(:polypaperclip_definitions, {})
#sequence is important here - we have to override some paperclip stuff
include Paperclip::InstanceMethods
include InstanceMethods
end
end | ruby | def initialize_polypaperclip
if polypaperclip_definitions.nil?
after_save :save_attached_files
before_destroy :destroy_attached_files
has_many_attachments_association
write_inheritable_attribute(:polypaperclip_definitions, {})
#sequence is important here - we have to override some paperclip stuff
include Paperclip::InstanceMethods
include InstanceMethods
end
end | [
"def",
"initialize_polypaperclip",
"if",
"polypaperclip_definitions",
".",
"nil?",
"after_save",
":save_attached_files",
"before_destroy",
":destroy_attached_files",
"has_many_attachments_association",
"write_inheritable_attribute",
"(",
":polypaperclip_definitions",
",",
"{",
"}",
")",
"include",
"Paperclip",
"::",
"InstanceMethods",
"include",
"InstanceMethods",
"end",
"end"
] | initialize a polypaperclip model if a configuration hasn't already been loaded | [
"initialize",
"a",
"polypaperclip",
"model",
"if",
"a",
"configuration",
"hasn",
"t",
"already",
"been",
"loaded"
] | 456c7004417c8fc2385be9c7feedce3b256a3382 | https://github.com/dpickett/polypaperclip/blob/456c7004417c8fc2385be9c7feedce3b256a3382/lib/polypaperclip.rb#L47-L60 | train |
marcinwyszynski/statefully | lib/statefully/state.rb | Statefully.State.method_missing | def method_missing(name, *args, &block)
sym_name = name.to_sym
return fetch(sym_name) if key?(sym_name)
str_name = name.to_s
modifier = str_name[-1]
return super unless %w[? !].include?(modifier)
base = str_name[0...-1].to_sym
known = key?(base)
return known if modifier == '?'
return fetch(base) if known
raise Errors::StateMissing, base
end | ruby | def method_missing(name, *args, &block)
sym_name = name.to_sym
return fetch(sym_name) if key?(sym_name)
str_name = name.to_s
modifier = str_name[-1]
return super unless %w[? !].include?(modifier)
base = str_name[0...-1].to_sym
known = key?(base)
return known if modifier == '?'
return fetch(base) if known
raise Errors::StateMissing, base
end | [
"def",
"method_missing",
"(",
"name",
",",
"*",
"args",
",",
"&",
"block",
")",
"sym_name",
"=",
"name",
".",
"to_sym",
"return",
"fetch",
"(",
"sym_name",
")",
"if",
"key?",
"(",
"sym_name",
")",
"str_name",
"=",
"name",
".",
"to_s",
"modifier",
"=",
"str_name",
"[",
"-",
"1",
"]",
"return",
"super",
"unless",
"%w[",
"?",
"!",
"]",
".",
"include?",
"(",
"modifier",
")",
"base",
"=",
"str_name",
"[",
"0",
"...",
"-",
"1",
"]",
".",
"to_sym",
"known",
"=",
"key?",
"(",
"base",
")",
"return",
"known",
"if",
"modifier",
"==",
"'?'",
"return",
"fetch",
"(",
"base",
")",
"if",
"known",
"raise",
"Errors",
"::",
"StateMissing",
",",
"base",
"end"
] | Dynamically pass unknown messages to the underlying state storage
State fields become accessible through readers, like in an
{http://ruby-doc.org/stdlib-2.0.0/libdoc/ostruct/rdoc/OpenStruct.html OpenStruct}.
A single state field can be questioned for existence by having its name
followed by a question mark - eg. bacon?.
A single state field can be force-accessed by having its name followed by
an exclamation mark - eg. bacon!.
This method reeks of :reek:TooManyStatements.
@param name [Symbol|String]
@param args [Array<Object>]
@param block [Proc]
@return [Object]
@raise [NoMethodError]
@raise [Errors::StateMissing]
@api private
@example
state = Statefully::State.create(bacon: 'tasty')
state.bacon
=> "tasty"
state.bacon?
=> true
state.bacon!
=> "tasty"
state.cabbage
NoMethodError: undefined method `cabbage' for #<Statefully::State::Success bacon="tasty">
[STACK TRACE]
state.cabbage?
=> false
state.cabbage!
Statefully::Errors::StateMissing: field 'cabbage' missing from state
[STACK TRACE] | [
"Dynamically",
"pass",
"unknown",
"messages",
"to",
"the",
"underlying",
"state",
"storage"
] | affca50625a26229e1af7ee30f2fe12bf9cddda9 | https://github.com/marcinwyszynski/statefully/blob/affca50625a26229e1af7ee30f2fe12bf9cddda9/lib/statefully/state.rb#L273-L284 | train |
marcinwyszynski/statefully | lib/statefully/state.rb | Statefully.State.respond_to_missing? | def respond_to_missing?(name, _include_private = false)
str_name = name.to_s
key?(name.to_sym) || %w[? !].any?(&str_name.method(:end_with?)) || super
end | ruby | def respond_to_missing?(name, _include_private = false)
str_name = name.to_s
key?(name.to_sym) || %w[? !].any?(&str_name.method(:end_with?)) || super
end | [
"def",
"respond_to_missing?",
"(",
"name",
",",
"_include_private",
"=",
"false",
")",
"str_name",
"=",
"name",
".",
"to_s",
"key?",
"(",
"name",
".",
"to_sym",
")",
"||",
"%w[",
"?",
"!",
"]",
".",
"any?",
"(",
"&",
"str_name",
".",
"method",
"(",
":end_with?",
")",
")",
"||",
"super",
"end"
] | Companion to `method_missing`
This method reeks of :reek:BooleanParameter.
@param name [Symbol|String]
@param _include_private [Boolean]
@return [Boolean]
@api private | [
"Companion",
"to",
"method_missing"
] | affca50625a26229e1af7ee30f2fe12bf9cddda9 | https://github.com/marcinwyszynski/statefully/blob/affca50625a26229e1af7ee30f2fe12bf9cddda9/lib/statefully/state.rb#L295-L298 | train |
anvil-src/anvil-core | lib/anvil/versioner.rb | Anvil.Versioner.bump! | def bump!(term)
fail NotSupportedTerm.new(term) unless TERMS.include?(term.to_sym)
new_version = clone
new_value = increment send(term)
new_version.send("#{term}=", new_value)
new_version.reset_terms_for(term)
end | ruby | def bump!(term)
fail NotSupportedTerm.new(term) unless TERMS.include?(term.to_sym)
new_version = clone
new_value = increment send(term)
new_version.send("#{term}=", new_value)
new_version.reset_terms_for(term)
end | [
"def",
"bump!",
"(",
"term",
")",
"fail",
"NotSupportedTerm",
".",
"new",
"(",
"term",
")",
"unless",
"TERMS",
".",
"include?",
"(",
"term",
".",
"to_sym",
")",
"new_version",
"=",
"clone",
"new_value",
"=",
"increment",
"send",
"(",
"term",
")",
"new_version",
".",
"send",
"(",
"\"#{term}=\"",
",",
"new_value",
")",
"new_version",
".",
"reset_terms_for",
"(",
"term",
")",
"end"
] | Bumps a version by incrementing one of its terms and reseting the others
according to semver specification.
@example
Versioner.new('1.2.3-alpha.1+build.2').bump(:major)
# => '2.0.0'
Versioner.new('1.2.3-alpha.1+build.2').bump(:minor)
# => '1.3.0'
Versioner.new('1.2.3-alpha.1+build.2').bump(:patch)
# => '1.2.4'
Versioner.new('1.2.3-alpha.1+build.2').bump(:pre)
# => '1.2.3-alpha.2'
Versioner.new('1.2.3-alpha.1+build.2').bump(:build)
# => '1.2.3-alpha.2+build.3'
@param term [Symbol] the term to increment
@raise [Anvil::Versioner::NotSuportedTerm] When the given term is invalid | [
"Bumps",
"a",
"version",
"by",
"incrementing",
"one",
"of",
"its",
"terms",
"and",
"reseting",
"the",
"others",
"according",
"to",
"semver",
"specification",
"."
] | 8322ebd6a2f002e4177b86e707d9c8d5c2a7233d | https://github.com/anvil-src/anvil-core/blob/8322ebd6a2f002e4177b86e707d9c8d5c2a7233d/lib/anvil/versioner.rb#L41-L49 | train |
anvil-src/anvil-core | lib/anvil/versioner.rb | Anvil.Versioner.reset_terms_for | def reset_terms_for(term)
self.minor = 0 if term == :major
self.patch = 0 if term == :major || term == :minor
self.pre = nil if [:major, :minor, :patch].include? term
self.build = nil if [:major, :minor, :patch, :pre].include? term
self
end | ruby | def reset_terms_for(term)
self.minor = 0 if term == :major
self.patch = 0 if term == :major || term == :minor
self.pre = nil if [:major, :minor, :patch].include? term
self.build = nil if [:major, :minor, :patch, :pre].include? term
self
end | [
"def",
"reset_terms_for",
"(",
"term",
")",
"self",
".",
"minor",
"=",
"0",
"if",
"term",
"==",
":major",
"self",
".",
"patch",
"=",
"0",
"if",
"term",
"==",
":major",
"||",
"term",
"==",
":minor",
"self",
".",
"pre",
"=",
"nil",
"if",
"[",
":major",
",",
":minor",
",",
":patch",
"]",
".",
"include?",
"term",
"self",
".",
"build",
"=",
"nil",
"if",
"[",
":major",
",",
":minor",
",",
":patch",
",",
":pre",
"]",
".",
"include?",
"term",
"self",
"end"
] | Resets all the terms which need to be reset after a bump
@param term [Symbol] The term which has been bumped
@return [Anvil::Versioner] A new version with the proper number
@todo we still need to reset pre-release and builds properly | [
"Resets",
"all",
"the",
"terms",
"which",
"need",
"to",
"be",
"reset",
"after",
"a",
"bump"
] | 8322ebd6a2f002e4177b86e707d9c8d5c2a7233d | https://github.com/anvil-src/anvil-core/blob/8322ebd6a2f002e4177b86e707d9c8d5c2a7233d/lib/anvil/versioner.rb#L69-L76 | train |
soccerbrain/telstra-sms | lib/telstra/sms.rb | Telstra.SMS.send_sms | def send_sms(to: sms_to, body: sms_body)
[to, body]
generate_token
options = { body: {
body: body,
to: to
}.to_json,
headers: { "Content-Type" => "application/json", "Authorization" => "Bearer #{@token}" }}
response = HTTParty.post("https://api.telstra.com/v1/sms/messages", options)
return JSON.parse(response.body)
end | ruby | def send_sms(to: sms_to, body: sms_body)
[to, body]
generate_token
options = { body: {
body: body,
to: to
}.to_json,
headers: { "Content-Type" => "application/json", "Authorization" => "Bearer #{@token}" }}
response = HTTParty.post("https://api.telstra.com/v1/sms/messages", options)
return JSON.parse(response.body)
end | [
"def",
"send_sms",
"(",
"to",
":",
"sms_to",
",",
"body",
":",
"sms_body",
")",
"[",
"to",
",",
"body",
"]",
"generate_token",
"options",
"=",
"{",
"body",
":",
"{",
"body",
":",
"body",
",",
"to",
":",
"to",
"}",
".",
"to_json",
",",
"headers",
":",
"{",
"\"Content-Type\"",
"=>",
"\"application/json\"",
",",
"\"Authorization\"",
"=>",
"\"Bearer #{@token}\"",
"}",
"}",
"response",
"=",
"HTTParty",
".",
"post",
"(",
"\"https://api.telstra.com/v1/sms/messages\"",
",",
"options",
")",
"return",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
")",
"end"
] | Receipient number should be in the format of 04xxxxxxxx where x is a digit.
Authorization header value should be in the format of "Bearer xxx" where xxx
is the access token returned from a token request. | [
"Receipient",
"number",
"should",
"be",
"in",
"the",
"format",
"of",
"04xxxxxxxx",
"where",
"x",
"is",
"a",
"digit",
".",
"Authorization",
"header",
"value",
"should",
"be",
"in",
"the",
"format",
"of",
"Bearer",
"xxx",
"where",
"xxx",
"is",
"the",
"access",
"token",
"returned",
"from",
"a",
"token",
"request",
"."
] | 32ce42a589b7b69405e5d81224deceae00334803 | https://github.com/soccerbrain/telstra-sms/blob/32ce42a589b7b69405e5d81224deceae00334803/lib/telstra/sms.rb#L25-L35 | train |
nickcharlton/atlas-ruby | lib/atlas/box_provider.rb | Atlas.BoxProvider.save | def save
body = { provider: to_hash }
begin
response = Atlas.client.put(url_builder.box_provider_url, body: body)
rescue Atlas::Errors::NotFoundError
response = Atlas.client.post("#{url_builder.box_version_url}/providers",
body: body)
end
update_with_response(response)
end | ruby | def save
body = { provider: to_hash }
begin
response = Atlas.client.put(url_builder.box_provider_url, body: body)
rescue Atlas::Errors::NotFoundError
response = Atlas.client.post("#{url_builder.box_version_url}/providers",
body: body)
end
update_with_response(response)
end | [
"def",
"save",
"body",
"=",
"{",
"provider",
":",
"to_hash",
"}",
"begin",
"response",
"=",
"Atlas",
".",
"client",
".",
"put",
"(",
"url_builder",
".",
"box_provider_url",
",",
"body",
":",
"body",
")",
"rescue",
"Atlas",
"::",
"Errors",
"::",
"NotFoundError",
"response",
"=",
"Atlas",
".",
"client",
".",
"post",
"(",
"\"#{url_builder.box_version_url}/providers\"",
",",
"body",
":",
"body",
")",
"end",
"update_with_response",
"(",
"response",
")",
"end"
] | Initialize a provider from a tag and object hash.
@param [String] tag the tag which represents the origin on the provider.
@param [Hash] hash the attributes for the box
@param hash [String] :name The name of the provider.
@param hash [String] :url An HTTP URL to the box file. Omit if uploading
with Atlas.
Save the provider.
@return [Hash] Atlas response object. | [
"Initialize",
"a",
"provider",
"from",
"a",
"tag",
"and",
"object",
"hash",
"."
] | 2170c04496682e0d8e7c959bd9f267f62fa84c1d | https://github.com/nickcharlton/atlas-ruby/blob/2170c04496682e0d8e7c959bd9f267f62fa84c1d/lib/atlas/box_provider.rb#L56-L67 | train |
nickcharlton/atlas-ruby | lib/atlas/box_provider.rb | Atlas.BoxProvider.upload | def upload(file)
# get the path for upload
response = Atlas.client.get("#{url_builder.box_provider_url}/upload")
# upload the file
upload_url = response['upload_path']
Excon.put(upload_url, body: file)
end | ruby | def upload(file)
# get the path for upload
response = Atlas.client.get("#{url_builder.box_provider_url}/upload")
# upload the file
upload_url = response['upload_path']
Excon.put(upload_url, body: file)
end | [
"def",
"upload",
"(",
"file",
")",
"response",
"=",
"Atlas",
".",
"client",
".",
"get",
"(",
"\"#{url_builder.box_provider_url}/upload\"",
")",
"upload_url",
"=",
"response",
"[",
"'upload_path'",
"]",
"Excon",
".",
"put",
"(",
"upload_url",
",",
"body",
":",
"file",
")",
"end"
] | Upload a .box file for this provider.
@param [File] file a File object for the file. | [
"Upload",
"a",
".",
"box",
"file",
"for",
"this",
"provider",
"."
] | 2170c04496682e0d8e7c959bd9f267f62fa84c1d | https://github.com/nickcharlton/atlas-ruby/blob/2170c04496682e0d8e7c959bd9f267f62fa84c1d/lib/atlas/box_provider.rb#L72-L79 | train |
danielbush/RubyCron | lib/CronR/CronJob.rb | CronR.CronJob.runnable? | def runnable? time
result = [:minute,:hour,:day,:dow,:month].map{|ct|
if self[ct] == true then
true
else
case ct
when :month,:day,:hour
val = time.send(ct)
when :dow
val = time.wday
when :minute
val = time.min
end
case self[ct]
when Numeric # Should be Fixnum
self[ct] == val
else # Assume array-like thing...
self[ct].include?(val)
end
end
}
# Everything should be true to make us eligible for running:
[result.inject(true){|s,v| s && v},result]
end | ruby | def runnable? time
result = [:minute,:hour,:day,:dow,:month].map{|ct|
if self[ct] == true then
true
else
case ct
when :month,:day,:hour
val = time.send(ct)
when :dow
val = time.wday
when :minute
val = time.min
end
case self[ct]
when Numeric # Should be Fixnum
self[ct] == val
else # Assume array-like thing...
self[ct].include?(val)
end
end
}
# Everything should be true to make us eligible for running:
[result.inject(true){|s,v| s && v},result]
end | [
"def",
"runnable?",
"time",
"result",
"=",
"[",
":minute",
",",
":hour",
",",
":day",
",",
":dow",
",",
":month",
"]",
".",
"map",
"{",
"|",
"ct",
"|",
"if",
"self",
"[",
"ct",
"]",
"==",
"true",
"then",
"true",
"else",
"case",
"ct",
"when",
":month",
",",
":day",
",",
":hour",
"val",
"=",
"time",
".",
"send",
"(",
"ct",
")",
"when",
":dow",
"val",
"=",
"time",
".",
"wday",
"when",
":minute",
"val",
"=",
"time",
".",
"min",
"end",
"case",
"self",
"[",
"ct",
"]",
"when",
"Numeric",
"self",
"[",
"ct",
"]",
"==",
"val",
"else",
"self",
"[",
"ct",
"]",
".",
"include?",
"(",
"val",
")",
"end",
"end",
"}",
"[",
"result",
".",
"inject",
"(",
"true",
")",
"{",
"|",
"s",
",",
"v",
"|",
"s",
"&&",
"v",
"}",
",",
"result",
"]",
"end"
] | Return true if job is runnable at the given time.
Note we expect an instance of Time.
ActiveSupport can be used to give us time zones in Time.
Example
ok,details = runnable?(Time.now) | [
"Return",
"true",
"if",
"job",
"is",
"runnable",
"at",
"the",
"given",
"time",
"."
] | 24a2f997b81663ded1ac1d01017e8d807d5caffd | https://github.com/danielbush/RubyCron/blob/24a2f997b81663ded1ac1d01017e8d807d5caffd/lib/CronR/CronJob.rb#L112-L136 | train |
dnd/permit | lib/permit/permit_rules.rb | Permit.PermitRules.allow | def allow(roles, options = {})
actions = options.delete(:to)
rule = PermitRule.new(roles, options)
index_rule_by_actions @action_allow_rules, actions, rule
return rule
end | ruby | def allow(roles, options = {})
actions = options.delete(:to)
rule = PermitRule.new(roles, options)
index_rule_by_actions @action_allow_rules, actions, rule
return rule
end | [
"def",
"allow",
"(",
"roles",
",",
"options",
"=",
"{",
"}",
")",
"actions",
"=",
"options",
".",
"delete",
"(",
":to",
")",
"rule",
"=",
"PermitRule",
".",
"new",
"(",
"roles",
",",
"options",
")",
"index_rule_by_actions",
"@action_allow_rules",
",",
"actions",
",",
"rule",
"return",
"rule",
"end"
] | Adds an allow rule for the given actions to the collection.
@example Allow a person that is a member of a team to show
allow :person, :who => :is_member, :of => :team, :to => :show
@example Allow a person that is a member of any of the teams to index.
allow :person, :who => :is_member, :of => [:team1, :team2], :to => :index
@example Allow a person with either of the named roles for a resource to perform any "write" operations.
allow [:project_admin, :project_manager], :of => :project, :to => :write
@example Allow a person with the viewer role of either of the projects to show.
allow :viewer, :of => [:project1, :project2], :to => :show
@param [Symbol, <Symbol>] roles the role(s) that the rule will apply to.
@param [Hash] options the options used to build the rule.
@option options [Symbol] :who the method to call on the target resource.
@option options [Symbol] :that alias for :who
@option options [Symbol, nil, :any, <Symbol, nil>] :of the name of the instance variable holding the target
resource. If set to +:any+ then the match will apply to a person that has
a matching role authorization for any resource. If not given, or set to
+nil+, then the match will apply to a person that has a matching role
authorization for a nil resource. +:any/nil+ functionality only applies
when using named roles. (see Permit::NamedRoles).
@option options [Symbol, nil, :any, <Symbol, nil>] :on alias for +:of+
@option options [Symbol, String, Proc] :if code to evaluate at the end of the
match if it is still valid. If it returns false, the rule will not
match. If a proc if given, it will be passed the current subject and
binding. A method will be called without any arguments.
@option options [Symbol, String, Proc] :unless code to evaluate at the end
of the match if it is still valid. If it returns true, the rule will not
match. If a proc if given, it will be passed the current subject and
binding. A method will be called without any arguments.
@option options [Symbol, <Symbol>] :to the action(s) to allow access to if this
rule matches. +:all+ may be given to indicate that access is given to all
actions if the rule matches. Actions will be expanded using the aliases
defined in {Permit::Config.action_aliases}. The expansion operation is
not recursive.
@return [PermitRule] the rule that was created for the parameters.
@raise [PermitConfigurationError] if +:to+ is not valid, or if the rule
cannot be created. | [
"Adds",
"an",
"allow",
"rule",
"for",
"the",
"given",
"actions",
"to",
"the",
"collection",
"."
] | 4bf41d5cc1fe1cbd100405bda773921e605f7a7a | https://github.com/dnd/permit/blob/4bf41d5cc1fe1cbd100405bda773921e605f7a7a/lib/permit/permit_rules.rb#L82-L87 | train |
dlangevin/tinia | lib/tinia.rb | Tinia.ActiveRecord.indexed_with_cloud_search | def indexed_with_cloud_search(&block)
mods = [
Tinia::Connection,
Tinia::Index,
Tinia::Search
]
mods.each do |mod|
unless self.included_modules.include?(mod)
self.send(:include, mod)
end
end
# config block
yield(self) if block_given?
# ensure config is all set
unless self.cloud_search_domain.present?
raise Tinia::MissingSearchDomain.new(self)
end
end | ruby | def indexed_with_cloud_search(&block)
mods = [
Tinia::Connection,
Tinia::Index,
Tinia::Search
]
mods.each do |mod|
unless self.included_modules.include?(mod)
self.send(:include, mod)
end
end
# config block
yield(self) if block_given?
# ensure config is all set
unless self.cloud_search_domain.present?
raise Tinia::MissingSearchDomain.new(self)
end
end | [
"def",
"indexed_with_cloud_search",
"(",
"&",
"block",
")",
"mods",
"=",
"[",
"Tinia",
"::",
"Connection",
",",
"Tinia",
"::",
"Index",
",",
"Tinia",
"::",
"Search",
"]",
"mods",
".",
"each",
"do",
"|",
"mod",
"|",
"unless",
"self",
".",
"included_modules",
".",
"include?",
"(",
"mod",
")",
"self",
".",
"send",
"(",
":include",
",",
"mod",
")",
"end",
"end",
"yield",
"(",
"self",
")",
"if",
"block_given?",
"unless",
"self",
".",
"cloud_search_domain",
".",
"present?",
"raise",
"Tinia",
"::",
"MissingSearchDomain",
".",
"new",
"(",
"self",
")",
"end",
"end"
] | activation method for an AR class | [
"activation",
"method",
"for",
"an",
"AR",
"class"
] | ad5f2aba55765dbd3f67dc79630d5686b2ce6894 | https://github.com/dlangevin/tinia/blob/ad5f2aba55765dbd3f67dc79630d5686b2ce6894/lib/tinia.rb#L22-L40 | train |
smsified/smsified-ruby | lib/smsified/subscriptions.rb | Smsified.Subscriptions.create_inbound_subscription | def create_inbound_subscription(destination_address, options)
query = options.merge({ :destination_address => destination_address })
Response.new self.class.post("/smsmessaging/inbound/subscriptions",
:basic_auth => @auth,
:body => camelcase_keys(query),
:headers => SMSIFIED_HTTP_HEADERS
)
end | ruby | def create_inbound_subscription(destination_address, options)
query = options.merge({ :destination_address => destination_address })
Response.new self.class.post("/smsmessaging/inbound/subscriptions",
:basic_auth => @auth,
:body => camelcase_keys(query),
:headers => SMSIFIED_HTTP_HEADERS
)
end | [
"def",
"create_inbound_subscription",
"(",
"destination_address",
",",
"options",
")",
"query",
"=",
"options",
".",
"merge",
"(",
"{",
":destination_address",
"=>",
"destination_address",
"}",
")",
"Response",
".",
"new",
"self",
".",
"class",
".",
"post",
"(",
"\"/smsmessaging/inbound/subscriptions\"",
",",
":basic_auth",
"=>",
"@auth",
",",
":body",
"=>",
"camelcase_keys",
"(",
"query",
")",
",",
":headers",
"=>",
"SMSIFIED_HTTP_HEADERS",
")",
"end"
] | Intantiate a new class to work with subscriptions
@param [required, Hash] params to create the user
@option params [required, String] :username username to authenticate with
@option params [required, String] :password to authenticate with
@option params [optional, String] :base_uri of an alternative location of SMSified
@option params [optional, String] :destination_address to use with subscriptions
@option params [optional, String] :sender_address to use with subscriptions
@option params [optional, Boolean] :debug to turn on the HTTparty debugging to stdout
@example
subscription = Subscription.new :username => 'user', :password => '123'
Creates an inbound subscription
@param [required, String] destination_address to subscribe to
@param [required, Hash] params to send an sms
@option params [optional, String] :notify_url to send callbacks to
@option params [optional, String] :client_correlator to update
@option params [optional, String] :callback_data to update
@return [Object] A Response Object with http and data instance methods
@param [required, String] notify_url to send callbacks to
@return [Object] A Response Object with http and data instance methods
@example
subscriptions.create_inbound_subscription('tel:+14155551212', :notify_url => 'http://foobar.com') | [
"Intantiate",
"a",
"new",
"class",
"to",
"work",
"with",
"subscriptions"
] | 1c7a0f445ffe7fe0fb035a1faf44ac55687a4488 | https://github.com/smsified/smsified-ruby/blob/1c7a0f445ffe7fe0fb035a1faf44ac55687a4488/lib/smsified/subscriptions.rb#L46-L55 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.