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 |
---|---|---|---|---|---|---|---|---|---|---|---|
gnumarcelo/campaigning | lib/campaigning/list.rb | Campaigning.List.get_all_active_subscribers | def get_all_active_subscribers
find_active_subscribers(DateTime.new(y=1911,m=1,d=01, h=01,min=00,s=00))
end | ruby | def get_all_active_subscribers
find_active_subscribers(DateTime.new(y=1911,m=1,d=01, h=01,min=00,s=00))
end | [
"def",
"get_all_active_subscribers",
"find_active_subscribers",
"(",
"DateTime",
".",
"new",
"(",
"y",
"=",
"1911",
",",
"m",
"=",
"1",
",",
"d",
"=",
"01",
",",
"h",
"=",
"01",
",",
"min",
"=",
"00",
",",
"s",
"=",
"00",
")",
")",
"end"
] | Gets a list of all active subscribers for a list.
*Return*:
*Success*: Upon a successful call, this method will return a collection of Campaigning::Subscriber objects.
*Error*: An Exception containing the cause of the error will be raised. | [
"Gets",
"a",
"list",
"of",
"all",
"active",
"subscribers",
"for",
"a",
"list",
"."
] | f3d7da053b65cfa376269533183919dc890964fd | https://github.com/gnumarcelo/campaigning/blob/f3d7da053b65cfa376269533183919dc890964fd/lib/campaigning/list.rb#L180-L182 | train |
r7kamura/plz | lib/plz/command_builder.rb | Plz.CommandBuilder.base_url_from_schema | def base_url_from_schema
json_schema.links.find do |link|
if link.href && link.rel == "self"
return link.href
end
end
end | ruby | def base_url_from_schema
json_schema.links.find do |link|
if link.href && link.rel == "self"
return link.href
end
end
end | [
"def",
"base_url_from_schema",
"json_schema",
".",
"links",
".",
"find",
"do",
"|",
"link",
"|",
"if",
"link",
".",
"href",
"&&",
"link",
".",
"rel",
"==",
"\"self\"",
"return",
"link",
".",
"href",
"end",
"end",
"end"
] | Extracts the base url of the API from JSON Schema
@return [String, nil]
@example
base_url_from_schema #=> "https://api.example.com/" | [
"Extracts",
"the",
"base",
"url",
"of",
"the",
"API",
"from",
"JSON",
"Schema"
] | 66aca9f864da21b561d558841ce4c17704eebbfc | https://github.com/r7kamura/plz/blob/66aca9f864da21b561d558841ce4c17704eebbfc/lib/plz/command_builder.rb#L206-L212 | train |
ViaQ/Relp | lib/relp/relp_protocol.rb | Relp.RelpProtocol.frame_read | def frame_read(socket)
begin
socket_content = socket.read_nonblock(4096)
frame = Hash.new
if match = socket_content.match(/(^[0-9]+) ([\S]*) (\d+)([\s\S]*)/)
frame[:txnr], frame[:command], frame[:data_length], frame[:message] = match.captures
# check_message_length(frame) - currently unstable, needs some more work
frame[:message].lstrip! #message could be empty
else
raise Relp::FrameReadException.new('Problem with reading RELP frame')
end
@logger.debug "Reading Frame #{frame.inspect}"
rescue IOError
@logger.error 'Problem with reading RELP frame'
raise Relp::FrameReadException.new 'Problem with reading RELP frame'
rescue Errno::ECONNRESET
@logger.error 'Connection reset'
raise Relp::ConnectionClosed.new 'Connection closed'
end
is_valid_command(frame[:command])
return frame
end | ruby | def frame_read(socket)
begin
socket_content = socket.read_nonblock(4096)
frame = Hash.new
if match = socket_content.match(/(^[0-9]+) ([\S]*) (\d+)([\s\S]*)/)
frame[:txnr], frame[:command], frame[:data_length], frame[:message] = match.captures
# check_message_length(frame) - currently unstable, needs some more work
frame[:message].lstrip! #message could be empty
else
raise Relp::FrameReadException.new('Problem with reading RELP frame')
end
@logger.debug "Reading Frame #{frame.inspect}"
rescue IOError
@logger.error 'Problem with reading RELP frame'
raise Relp::FrameReadException.new 'Problem with reading RELP frame'
rescue Errno::ECONNRESET
@logger.error 'Connection reset'
raise Relp::ConnectionClosed.new 'Connection closed'
end
is_valid_command(frame[:command])
return frame
end | [
"def",
"frame_read",
"(",
"socket",
")",
"begin",
"socket_content",
"=",
"socket",
".",
"read_nonblock",
"(",
"4096",
")",
"frame",
"=",
"Hash",
".",
"new",
"if",
"match",
"=",
"socket_content",
".",
"match",
"(",
"/",
"\\S",
"\\d",
"\\s",
"\\S",
"/",
")",
"frame",
"[",
":txnr",
"]",
",",
"frame",
"[",
":command",
"]",
",",
"frame",
"[",
":data_length",
"]",
",",
"frame",
"[",
":message",
"]",
"=",
"match",
".",
"captures",
"frame",
"[",
":message",
"]",
".",
"lstrip!",
"else",
"raise",
"Relp",
"::",
"FrameReadException",
".",
"new",
"(",
"'Problem with reading RELP frame'",
")",
"end",
"@logger",
".",
"debug",
"\"Reading Frame #{frame.inspect}\"",
"rescue",
"IOError",
"@logger",
".",
"error",
"'Problem with reading RELP frame'",
"raise",
"Relp",
"::",
"FrameReadException",
".",
"new",
"'Problem with reading RELP frame'",
"rescue",
"Errno",
"::",
"ECONNRESET",
"@logger",
".",
"error",
"'Connection reset'",
"raise",
"Relp",
"::",
"ConnectionClosed",
".",
"new",
"'Connection closed'",
"end",
"is_valid_command",
"(",
"frame",
"[",
":command",
"]",
")",
"return",
"frame",
"end"
] | Read socket and return Relp frame information in hash | [
"Read",
"socket",
"and",
"return",
"Relp",
"frame",
"information",
"in",
"hash"
] | 979bbb757274d84f84c3d00bc459f2b30146c4fe | https://github.com/ViaQ/Relp/blob/979bbb757274d84f84c3d00bc459f2b30146c4fe/lib/relp/relp_protocol.rb#L33-L55 | train |
ViaQ/Relp | lib/relp/relp_protocol.rb | Relp.RelpProtocol.is_valid_command | def is_valid_command(command)
valid_commands = ["open", "close", "rsp", "syslog"]
if !valid_commands.include?(command)
@logger.error 'Invalid RELP command'
raise Relp::InvalidCommand.new('Invalid command')
end
end | ruby | def is_valid_command(command)
valid_commands = ["open", "close", "rsp", "syslog"]
if !valid_commands.include?(command)
@logger.error 'Invalid RELP command'
raise Relp::InvalidCommand.new('Invalid command')
end
end | [
"def",
"is_valid_command",
"(",
"command",
")",
"valid_commands",
"=",
"[",
"\"open\"",
",",
"\"close\"",
",",
"\"rsp\"",
",",
"\"syslog\"",
"]",
"if",
"!",
"valid_commands",
".",
"include?",
"(",
"command",
")",
"@logger",
".",
"error",
"'Invalid RELP command'",
"raise",
"Relp",
"::",
"InvalidCommand",
".",
"new",
"(",
"'Invalid command'",
")",
"end",
"end"
] | Check if command is one of valid commands if not raise exception | [
"Check",
"if",
"command",
"is",
"one",
"of",
"valid",
"commands",
"if",
"not",
"raise",
"exception"
] | 979bbb757274d84f84c3d00bc459f2b30146c4fe | https://github.com/ViaQ/Relp/blob/979bbb757274d84f84c3d00bc459f2b30146c4fe/lib/relp/relp_protocol.rb#L59-L65 | train |
benbalter/squad_goals | lib/squad_goals/helpers.rb | SquadGoals.Helpers.client_call | def client_call(method, *args)
key = cache_key(method, args)
cached = dalli.get(key)
return cached if cached
response = client.send(method, *args)
dalli.set(key, response)
response
end | ruby | def client_call(method, *args)
key = cache_key(method, args)
cached = dalli.get(key)
return cached if cached
response = client.send(method, *args)
dalli.set(key, response)
response
end | [
"def",
"client_call",
"(",
"method",
",",
"*",
"args",
")",
"key",
"=",
"cache_key",
"(",
"method",
",",
"args",
")",
"cached",
"=",
"dalli",
".",
"get",
"(",
"key",
")",
"return",
"cached",
"if",
"cached",
"response",
"=",
"client",
".",
"send",
"(",
"method",
",",
"*",
"args",
")",
"dalli",
".",
"set",
"(",
"key",
",",
"response",
")",
"response",
"end"
] | Call octokit, using memcached response, when available | [
"Call",
"octokit",
"using",
"memcached",
"response",
"when",
"available"
] | f3c06e7e45980833ebccacd6b7aaca25c8a216cc | https://github.com/benbalter/squad_goals/blob/f3c06e7e45980833ebccacd6b7aaca25c8a216cc/lib/squad_goals/helpers.rb#L4-L11 | train |
xijo/helmsman | lib/helmsman/view_helper.rb | Helmsman.ViewHelper.current_state_by_controller | def current_state_by_controller(*given_controller_names, actions: [])
if given_controller_names.any? { |name| name == controller_name.to_sym }
if actions.present?
Array(actions).include?(action_name.to_sym)
else
true
end
end
end | ruby | def current_state_by_controller(*given_controller_names, actions: [])
if given_controller_names.any? { |name| name == controller_name.to_sym }
if actions.present?
Array(actions).include?(action_name.to_sym)
else
true
end
end
end | [
"def",
"current_state_by_controller",
"(",
"*",
"given_controller_names",
",",
"actions",
":",
"[",
"]",
")",
"if",
"given_controller_names",
".",
"any?",
"{",
"|",
"name",
"|",
"name",
"==",
"controller_name",
".",
"to_sym",
"}",
"if",
"actions",
".",
"present?",
"Array",
"(",
"actions",
")",
".",
"include?",
"(",
"action_name",
".",
"to_sym",
")",
"else",
"true",
"end",
"end",
"end"
] | Returns true if one of the given controllers match the actual one.
If actions are set they are taken into account. | [
"Returns",
"true",
"if",
"one",
"of",
"the",
"given",
"controllers",
"match",
"the",
"actual",
"one",
".",
"If",
"actions",
"are",
"set",
"they",
"are",
"taken",
"into",
"account",
"."
] | 0cf50f298e8fc3c2d90344bf27c007ae2227fa9c | https://github.com/xijo/helmsman/blob/0cf50f298e8fc3c2d90344bf27c007ae2227fa9c/lib/helmsman/view_helper.rb#L5-L13 | train |
mru2/salesforce_adapter | lib/salesforce_adapter.rb | SalesforceAdapter.Base.call_webservice | def call_webservice(method_name, arguments, schema_url, service_path)
# Perform the call to the webservice and returns the result
Operations::WebserviceCall.new(@rforce_binding, method_name, arguments, schema_url, service_path).run()
end | ruby | def call_webservice(method_name, arguments, schema_url, service_path)
# Perform the call to the webservice and returns the result
Operations::WebserviceCall.new(@rforce_binding, method_name, arguments, schema_url, service_path).run()
end | [
"def",
"call_webservice",
"(",
"method_name",
",",
"arguments",
",",
"schema_url",
",",
"service_path",
")",
"Operations",
"::",
"WebserviceCall",
".",
"new",
"(",
"@rforce_binding",
",",
"method_name",
",",
"arguments",
",",
"schema_url",
",",
"service_path",
")",
".",
"run",
"(",
")",
"end"
] | Queries a salesforce webservice | [
"Queries",
"a",
"salesforce",
"webservice"
] | 5f7ddd0cce6ee5bce5cd60482e5415a11d5593a4 | https://github.com/mru2/salesforce_adapter/blob/5f7ddd0cce6ee5bce5cd60482e5415a11d5593a4/lib/salesforce_adapter.rb#L66-L71 | train |
michaelachrisco/nasa-api-client | lib/nasa/client.rb | NASA.Client.neo_feed | def neo_feed(start_date = Time.now.strftime('%Y-%m-%d'),
end_date = (Time.now + 604800).strftime('%Y-%m-%d'))
request
.neo
.rest
.v1('feed')
.get(:params => { :api_key => @application_id.dup,
:start_date => start_date,
:end_date => end_date })
.to_h
end | ruby | def neo_feed(start_date = Time.now.strftime('%Y-%m-%d'),
end_date = (Time.now + 604800).strftime('%Y-%m-%d'))
request
.neo
.rest
.v1('feed')
.get(:params => { :api_key => @application_id.dup,
:start_date => start_date,
:end_date => end_date })
.to_h
end | [
"def",
"neo_feed",
"(",
"start_date",
"=",
"Time",
".",
"now",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
",",
"end_date",
"=",
"(",
"Time",
".",
"now",
"+",
"604800",
")",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
")",
"request",
".",
"neo",
".",
"rest",
".",
"v1",
"(",
"'feed'",
")",
".",
"get",
"(",
":params",
"=>",
"{",
":api_key",
"=>",
"@application_id",
".",
"dup",
",",
":start_date",
"=>",
"start_date",
",",
":end_date",
"=>",
"end_date",
"}",
")",
".",
"to_h",
"end"
] | end_date is 1 week in seconds | [
"end_date",
"is",
"1",
"week",
"in",
"seconds"
] | 768be8a6006207050deca1bc9b039b7349fc969e | https://github.com/michaelachrisco/nasa-api-client/blob/768be8a6006207050deca1bc9b039b7349fc969e/lib/nasa/client.rb#L27-L37 | train |
blackwinter/nuggets | lib/nuggets/ruby_mixin.rb | Nuggets.RubyMixin.ruby_executable | def ruby_executable
@ruby_executable ||= begin
dir, name, ext = CONFIG.values_at(*%w[bindir RUBY_INSTALL_NAME EXEEXT])
::File.join(dir, name + ext).sub(/.*\s.*/m, '"\&"')
end
end | ruby | def ruby_executable
@ruby_executable ||= begin
dir, name, ext = CONFIG.values_at(*%w[bindir RUBY_INSTALL_NAME EXEEXT])
::File.join(dir, name + ext).sub(/.*\s.*/m, '"\&"')
end
end | [
"def",
"ruby_executable",
"@ruby_executable",
"||=",
"begin",
"dir",
",",
"name",
",",
"ext",
"=",
"CONFIG",
".",
"values_at",
"(",
"*",
"%w[",
"bindir",
"RUBY_INSTALL_NAME",
"EXEEXT",
"]",
")",
"::",
"File",
".",
"join",
"(",
"dir",
",",
"name",
"+",
"ext",
")",
".",
"sub",
"(",
"/",
"\\s",
"/m",
",",
"'\"\\&\"'",
")",
"end",
"end"
] | Returns the full path to the current Ruby interpreter's executable file.
This might not be the actual correct command to use for invoking the Ruby
interpreter; use ruby_command instead. | [
"Returns",
"the",
"full",
"path",
"to",
"the",
"current",
"Ruby",
"interpreter",
"s",
"executable",
"file",
".",
"This",
"might",
"not",
"be",
"the",
"actual",
"correct",
"command",
"to",
"use",
"for",
"invoking",
"the",
"Ruby",
"interpreter",
";",
"use",
"ruby_command",
"instead",
"."
] | 2a1d0beb015077b2820851ab190e886d1ad588b8 | https://github.com/blackwinter/nuggets/blob/2a1d0beb015077b2820851ab190e886d1ad588b8/lib/nuggets/ruby_mixin.rb#L81-L86 | train |
blackwinter/nuggets | lib/nuggets/ruby_mixin.rb | Nuggets.RubyMixin.command_for_ruby_tool | def command_for_ruby_tool(name)
filename = respond_to?(name) ? send(name) : locate_ruby_tool(name)
shebang_command(filename) =~ /ruby/ ? "#{ruby_command} #{filename}" : filename
end | ruby | def command_for_ruby_tool(name)
filename = respond_to?(name) ? send(name) : locate_ruby_tool(name)
shebang_command(filename) =~ /ruby/ ? "#{ruby_command} #{filename}" : filename
end | [
"def",
"command_for_ruby_tool",
"(",
"name",
")",
"filename",
"=",
"respond_to?",
"(",
"name",
")",
"?",
"send",
"(",
"name",
")",
":",
"locate_ruby_tool",
"(",
"name",
")",
"shebang_command",
"(",
"filename",
")",
"=~",
"/",
"/",
"?",
"\"#{ruby_command} #{filename}\"",
":",
"filename",
"end"
] | Returns the correct command string for invoking the +name+ executable
that belongs to the current Ruby interpreter. Returns +nil+ if the
command is not found.
If the command executable is a Ruby program, then we need to run it
in the correct Ruby interpreter just in case the command doesn't
have the correct shebang line; we don't want a totally different
Ruby than the current one to be invoked. | [
"Returns",
"the",
"correct",
"command",
"string",
"for",
"invoking",
"the",
"+",
"name",
"+",
"executable",
"that",
"belongs",
"to",
"the",
"current",
"Ruby",
"interpreter",
".",
"Returns",
"+",
"nil",
"+",
"if",
"the",
"command",
"is",
"not",
"found",
"."
] | 2a1d0beb015077b2820851ab190e886d1ad588b8 | https://github.com/blackwinter/nuggets/blob/2a1d0beb015077b2820851ab190e886d1ad588b8/lib/nuggets/ruby_mixin.rb#L122-L125 | train |
rightscale/right_develop | lib/right_develop/ci/util.rb | RightDevelop::CI.Util.pseudo_java_class_name | def pseudo_java_class_name(name)
result = ''
name.each_char do |chr|
if chr =~ JAVA_CLASS_NAME
result << chr
elsif chr == JAVA_PACKAGE_SEPARATOR
result << JAVE_PACKAGE_SEPARATOR_HOMOGLYPH
else
chr = chr.unpack('U')[0].to_s(16)
result << "&#x#{chr};"
end
end
result
end | ruby | def pseudo_java_class_name(name)
result = ''
name.each_char do |chr|
if chr =~ JAVA_CLASS_NAME
result << chr
elsif chr == JAVA_PACKAGE_SEPARATOR
result << JAVE_PACKAGE_SEPARATOR_HOMOGLYPH
else
chr = chr.unpack('U')[0].to_s(16)
result << "&#x#{chr};"
end
end
result
end | [
"def",
"pseudo_java_class_name",
"(",
"name",
")",
"result",
"=",
"''",
"name",
".",
"each_char",
"do",
"|",
"chr",
"|",
"if",
"chr",
"=~",
"JAVA_CLASS_NAME",
"result",
"<<",
"chr",
"elsif",
"chr",
"==",
"JAVA_PACKAGE_SEPARATOR",
"result",
"<<",
"JAVE_PACKAGE_SEPARATOR_HOMOGLYPH",
"else",
"chr",
"=",
"chr",
".",
"unpack",
"(",
"'U'",
")",
"[",
"0",
"]",
".",
"to_s",
"(",
"16",
")",
"result",
"<<",
"\"&#x#{chr};\"",
"end",
"end",
"result",
"end"
] | Ruby 1.8-2.1 compatible
Make a string suitable for parsing by Jenkins JUnit display plugin by escaping any non-valid
Java class name characters as an XML entity. This prevents Jenkins from interpreting "hi1.2"
as a package-and-class name.
@param [String] name
@return [String] string with all non-alphanumerics replaced with an equivalent XML hex entity | [
"Ruby",
"1",
".",
"8",
"-",
"2",
".",
"1",
"compatible",
"Make",
"a",
"string",
"suitable",
"for",
"parsing",
"by",
"Jenkins",
"JUnit",
"display",
"plugin",
"by",
"escaping",
"any",
"non",
"-",
"valid",
"Java",
"class",
"name",
"characters",
"as",
"an",
"XML",
"entity",
".",
"This",
"prevents",
"Jenkins",
"from",
"interpreting",
"hi1",
".",
"2",
"as",
"a",
"package",
"-",
"and",
"-",
"class",
"name",
"."
] | 52527b3c32200b542ed590f6f9a275c76758df0e | https://github.com/rightscale/right_develop/blob/52527b3c32200b542ed590f6f9a275c76758df0e/lib/right_develop/ci/util.rb#L32-L47 | train |
rightscale/right_develop | lib/right_develop/ci/util.rb | RightDevelop::CI.Util.purify | def purify(untrusted)
# First pass: strip bad UTF-8 characters
if RUBY_VERSION =~ /^1\.8/
iconv = Iconv.new('UTF-8//IGNORE', 'UTF-8')
result = iconv.iconv(untrusted)
else
result = untrusted.force_encoding(Encoding::BINARY).encode('UTF-8', :undef=>:replace, :replace=>'')
end
# Second pass: entity escape characters that can't appear in XML CDATA.
result.gsub(INVALID_CDATA_CHARACTER) do |ch|
"&#x%s;" % [ch.unpack('H*').first]
end
end | ruby | def purify(untrusted)
# First pass: strip bad UTF-8 characters
if RUBY_VERSION =~ /^1\.8/
iconv = Iconv.new('UTF-8//IGNORE', 'UTF-8')
result = iconv.iconv(untrusted)
else
result = untrusted.force_encoding(Encoding::BINARY).encode('UTF-8', :undef=>:replace, :replace=>'')
end
# Second pass: entity escape characters that can't appear in XML CDATA.
result.gsub(INVALID_CDATA_CHARACTER) do |ch|
"&#x%s;" % [ch.unpack('H*').first]
end
end | [
"def",
"purify",
"(",
"untrusted",
")",
"if",
"RUBY_VERSION",
"=~",
"/",
"\\.",
"/",
"iconv",
"=",
"Iconv",
".",
"new",
"(",
"'UTF-8//IGNORE'",
",",
"'UTF-8'",
")",
"result",
"=",
"iconv",
".",
"iconv",
"(",
"untrusted",
")",
"else",
"result",
"=",
"untrusted",
".",
"force_encoding",
"(",
"Encoding",
"::",
"BINARY",
")",
".",
"encode",
"(",
"'UTF-8'",
",",
":undef",
"=>",
":replace",
",",
":replace",
"=>",
"''",
")",
"end",
"result",
".",
"gsub",
"(",
"INVALID_CDATA_CHARACTER",
")",
"do",
"|",
"ch",
"|",
"\"&#x%s;\"",
"%",
"[",
"ch",
".",
"unpack",
"(",
"'H*'",
")",
".",
"first",
"]",
"end",
"end"
] | Strip invalid UTF-8 sequences from a string and entity-escape any character that can't legally
appear inside XML CDATA. If test output contains weird data, we could end up generating
invalid JUnit XML which will choke Java. Preserve the purity of essence of our precious XML
fluids!
@return [String] the input with all invalid UTF-8 replaced by the empty string
@param [String] untrusted a string (of any encoding) that might contain invalid UTF-8 sequences | [
"Strip",
"invalid",
"UTF",
"-",
"8",
"sequences",
"from",
"a",
"string",
"and",
"entity",
"-",
"escape",
"any",
"character",
"that",
"can",
"t",
"legally",
"appear",
"inside",
"XML",
"CDATA",
".",
"If",
"test",
"output",
"contains",
"weird",
"data",
"we",
"could",
"end",
"up",
"generating",
"invalid",
"JUnit",
"XML",
"which",
"will",
"choke",
"Java",
".",
"Preserve",
"the",
"purity",
"of",
"essence",
"of",
"our",
"precious",
"XML",
"fluids!"
] | 52527b3c32200b542ed590f6f9a275c76758df0e | https://github.com/rightscale/right_develop/blob/52527b3c32200b542ed590f6f9a275c76758df0e/lib/right_develop/ci/util.rb#L56-L69 | train |
agoragames/oembedr | lib/oembedr/providers.rb | Oembedr.Providers.service_endpoint | def service_endpoint url
endpoint = LIST.find do |(pattern, endpoint)|
url =~ pattern
end
endpoint ? endpoint.last : false
end | ruby | def service_endpoint url
endpoint = LIST.find do |(pattern, endpoint)|
url =~ pattern
end
endpoint ? endpoint.last : false
end | [
"def",
"service_endpoint",
"url",
"endpoint",
"=",
"LIST",
".",
"find",
"do",
"|",
"(",
"pattern",
",",
"endpoint",
")",
"|",
"url",
"=~",
"pattern",
"end",
"endpoint",
"?",
"endpoint",
".",
"last",
":",
"false",
"end"
] | Locate the correct service endpoint for the given resource URL.
@param url [String] a fully-qualified URL to an oembeddable resource
@return the url, or false if no known endpoint. | [
"Locate",
"the",
"correct",
"service",
"endpoint",
"for",
"the",
"given",
"resource",
"URL",
"."
] | 9e453adceaa01c5b07db466e6429a4ebb8bcda03 | https://github.com/agoragames/oembedr/blob/9e453adceaa01c5b07db466e6429a4ebb8bcda03/lib/oembedr/providers.rb#L75-L80 | train |
af83/desi | lib/desi/index_manager.rb | Desi.IndexManager.delete! | def delete!(pattern)
warn "You must provide a pattern" and exit if pattern.nil?
@outputter.puts "The following indices from host #{@host} are now deleted" if @verbose
indices(Regexp.new(pattern)).each do |index|
@client.delete("/#{index}")
@outputter.puts " * #{index.inspect}" if @verbose
end
end | ruby | def delete!(pattern)
warn "You must provide a pattern" and exit if pattern.nil?
@outputter.puts "The following indices from host #{@host} are now deleted" if @verbose
indices(Regexp.new(pattern)).each do |index|
@client.delete("/#{index}")
@outputter.puts " * #{index.inspect}" if @verbose
end
end | [
"def",
"delete!",
"(",
"pattern",
")",
"warn",
"\"You must provide a pattern\"",
"and",
"exit",
"if",
"pattern",
".",
"nil?",
"@outputter",
".",
"puts",
"\"The following indices from host #{@host} are now deleted\"",
"if",
"@verbose",
"indices",
"(",
"Regexp",
".",
"new",
"(",
"pattern",
")",
")",
".",
"each",
"do",
"|",
"index",
"|",
"@client",
".",
"delete",
"(",
"\"/#{index}\"",
")",
"@outputter",
".",
"puts",
"\" * #{index.inspect}\"",
"if",
"@verbose",
"end",
"end"
] | Delete all indices matching the specified pattern
@param [#to_s] pattern Regexp pattern used to restrict the selection
@return [void]
@note No confirmation is needed, so beware!
@note This method will also output its result on STDOUT if +@verbose+ is
true
@example Delete all indices whose name begins with "test"
Desi::IndexManager.new.delete!('^test') #=> nil
@api public | [
"Delete",
"all",
"indices",
"matching",
"the",
"specified",
"pattern"
] | 30c51ce3b484765bd8911baf2fb83a85809cc81c | https://github.com/af83/desi/blob/30c51ce3b484765bd8911baf2fb83a85809cc81c/lib/desi/index_manager.rb#L124-L133 | train |
af83/desi | lib/desi/index_manager.rb | Desi.IndexManager.close! | def close!(pattern)
warn "You must provide a pattern" and exit if pattern.nil?
@outputter.puts "The following indices from host #{@host} are now closed" if @verbose
indices(Regexp.new(pattern)).each do |index|
@client.post("/#{index}/_close")
@outputter.puts " * #{index.inspect}" if @verbose
end
end | ruby | def close!(pattern)
warn "You must provide a pattern" and exit if pattern.nil?
@outputter.puts "The following indices from host #{@host} are now closed" if @verbose
indices(Regexp.new(pattern)).each do |index|
@client.post("/#{index}/_close")
@outputter.puts " * #{index.inspect}" if @verbose
end
end | [
"def",
"close!",
"(",
"pattern",
")",
"warn",
"\"You must provide a pattern\"",
"and",
"exit",
"if",
"pattern",
".",
"nil?",
"@outputter",
".",
"puts",
"\"The following indices from host #{@host} are now closed\"",
"if",
"@verbose",
"indices",
"(",
"Regexp",
".",
"new",
"(",
"pattern",
")",
")",
".",
"each",
"do",
"|",
"index",
"|",
"@client",
".",
"post",
"(",
"\"/#{index}/_close\"",
")",
"@outputter",
".",
"puts",
"\" * #{index.inspect}\"",
"if",
"@verbose",
"end",
"end"
] | Close all indices matching the specified pattern
@param [#to_s] pattern Regexp pattern used to restrict the selection
@return [void]
@note No confirmation is needed, so beware!
@note This method will also output its result on STDOUT if +@verbose+ is
true
@example Close all indices whose name begins with "test"
Desi::IndexManager.new.close!('^test') #=> nil
@api public | [
"Close",
"all",
"indices",
"matching",
"the",
"specified",
"pattern"
] | 30c51ce3b484765bd8911baf2fb83a85809cc81c | https://github.com/af83/desi/blob/30c51ce3b484765bd8911baf2fb83a85809cc81c/lib/desi/index_manager.rb#L149-L158 | train |
datacite/toccatore | lib/toccatore/usage_update.rb | Toccatore.UsageUpdate.push_data | def push_data(items, options={})
if items.empty?
puts "No works found in the Queue."
0
elsif options[:access_token].blank?
puts "An error occured: Access token missing."
options[:total]
else
error_total = 0
Array(items).each do |item|
puts item
puts "*************"
error_total += push_item(item, options)
end
error_total
end
end | ruby | def push_data(items, options={})
if items.empty?
puts "No works found in the Queue."
0
elsif options[:access_token].blank?
puts "An error occured: Access token missing."
options[:total]
else
error_total = 0
Array(items).each do |item|
puts item
puts "*************"
error_total += push_item(item, options)
end
error_total
end
end | [
"def",
"push_data",
"(",
"items",
",",
"options",
"=",
"{",
"}",
")",
"if",
"items",
".",
"empty?",
"puts",
"\"No works found in the Queue.\"",
"0",
"elsif",
"options",
"[",
":access_token",
"]",
".",
"blank?",
"puts",
"\"An error occured: Access token missing.\"",
"options",
"[",
":total",
"]",
"else",
"error_total",
"=",
"0",
"Array",
"(",
"items",
")",
".",
"each",
"do",
"|",
"item",
"|",
"puts",
"item",
"puts",
"\"*************\"",
"error_total",
"+=",
"push_item",
"(",
"item",
",",
"options",
")",
"end",
"error_total",
"end",
"end"
] | method returns number of errors | [
"method",
"returns",
"number",
"of",
"errors"
] | 2fe36304776d599700c568544982d83c6ad44eac | https://github.com/datacite/toccatore/blob/2fe36304776d599700c568544982d83c6ad44eac/lib/toccatore/usage_update.rb#L70-L86 | train |
rschultheis/hatt | lib/hatt/configuration.rb | Hatt.Configuration.init_config | def init_config
unless instance_variable_defined? :@hatt_configuration
@hatt_configuration = TCFG::Base.new
# build up some default configuration
@hatt_configuration.tcfg_set 'hatt_services', {}
@hatt_configuration.tcfg_set 'hatt_globs', DEFAULT_HATT_GLOBS
@hatt_configuration.tcfg_set_env_var_prefix 'HATT_'
end
if hatt_config_file_path
# if a config file was specified, we assume it exists
@hatt_configuration.tcfg_config_file hatt_config_file_path
else
Log.warn 'No configuration file specified or found. Make a hatt.yml file and point hatt at it.'
end
@hatt_configuration.tcfg_set 'hatt_config_file', hatt_config_file_path
normalize_services_config @hatt_configuration
nil
end | ruby | def init_config
unless instance_variable_defined? :@hatt_configuration
@hatt_configuration = TCFG::Base.new
# build up some default configuration
@hatt_configuration.tcfg_set 'hatt_services', {}
@hatt_configuration.tcfg_set 'hatt_globs', DEFAULT_HATT_GLOBS
@hatt_configuration.tcfg_set_env_var_prefix 'HATT_'
end
if hatt_config_file_path
# if a config file was specified, we assume it exists
@hatt_configuration.tcfg_config_file hatt_config_file_path
else
Log.warn 'No configuration file specified or found. Make a hatt.yml file and point hatt at it.'
end
@hatt_configuration.tcfg_set 'hatt_config_file', hatt_config_file_path
normalize_services_config @hatt_configuration
nil
end | [
"def",
"init_config",
"unless",
"instance_variable_defined?",
":@hatt_configuration",
"@hatt_configuration",
"=",
"TCFG",
"::",
"Base",
".",
"new",
"@hatt_configuration",
".",
"tcfg_set",
"'hatt_services'",
",",
"{",
"}",
"@hatt_configuration",
".",
"tcfg_set",
"'hatt_globs'",
",",
"DEFAULT_HATT_GLOBS",
"@hatt_configuration",
".",
"tcfg_set_env_var_prefix",
"'HATT_'",
"end",
"if",
"hatt_config_file_path",
"@hatt_configuration",
".",
"tcfg_config_file",
"hatt_config_file_path",
"else",
"Log",
".",
"warn",
"'No configuration file specified or found. Make a hatt.yml file and point hatt at it.'",
"end",
"@hatt_configuration",
".",
"tcfg_set",
"'hatt_config_file'",
",",
"hatt_config_file_path",
"normalize_services_config",
"@hatt_configuration",
"nil",
"end"
] | ensure the configuration is resolved and ready to use | [
"ensure",
"the",
"configuration",
"is",
"resolved",
"and",
"ready",
"to",
"use"
] | b1b5cddf2b52d8952e5607a2987d2efb648babaf | https://github.com/rschultheis/hatt/blob/b1b5cddf2b52d8952e5607a2987d2efb648babaf/lib/hatt/configuration.rb#L35-L57 | train |
birarda/logan | lib/logan/client.rb | Logan.Client.auth= | def auth=(auth_hash)
# symbolize the keys
new_auth_hash = {}
auth_hash.each {|k, v| new_auth_hash[k.to_sym] = v}
auth_hash = new_auth_hash
if auth_hash.has_key? :access_token
# clear the basic_auth, if it's set
self.class.default_options.reject!{ |k| k == :basic_auth }
# set the Authorization headers
self.class.headers.merge!("Authorization" => "Bearer #{auth_hash[:access_token]}")
elsif auth_hash.has_key?(:username) && auth_hash.has_key?(:password)
self.class.basic_auth auth_hash[:username], auth_hash[:password]
# remove the access_token from the headers, if it exists
self.class.headers.reject!{ |k, v| k == "Authorization" }
else
raise """
Incomplete authorization information passed in authorization hash.
You must have either an :access_token or a username password combination (:username, :password).
"""
end
end | ruby | def auth=(auth_hash)
# symbolize the keys
new_auth_hash = {}
auth_hash.each {|k, v| new_auth_hash[k.to_sym] = v}
auth_hash = new_auth_hash
if auth_hash.has_key? :access_token
# clear the basic_auth, if it's set
self.class.default_options.reject!{ |k| k == :basic_auth }
# set the Authorization headers
self.class.headers.merge!("Authorization" => "Bearer #{auth_hash[:access_token]}")
elsif auth_hash.has_key?(:username) && auth_hash.has_key?(:password)
self.class.basic_auth auth_hash[:username], auth_hash[:password]
# remove the access_token from the headers, if it exists
self.class.headers.reject!{ |k, v| k == "Authorization" }
else
raise """
Incomplete authorization information passed in authorization hash.
You must have either an :access_token or a username password combination (:username, :password).
"""
end
end | [
"def",
"auth",
"=",
"(",
"auth_hash",
")",
"new_auth_hash",
"=",
"{",
"}",
"auth_hash",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"new_auth_hash",
"[",
"k",
".",
"to_sym",
"]",
"=",
"v",
"}",
"auth_hash",
"=",
"new_auth_hash",
"if",
"auth_hash",
".",
"has_key?",
":access_token",
"self",
".",
"class",
".",
"default_options",
".",
"reject!",
"{",
"|",
"k",
"|",
"k",
"==",
":basic_auth",
"}",
"self",
".",
"class",
".",
"headers",
".",
"merge!",
"(",
"\"Authorization\"",
"=>",
"\"Bearer #{auth_hash[:access_token]}\"",
")",
"elsif",
"auth_hash",
".",
"has_key?",
"(",
":username",
")",
"&&",
"auth_hash",
".",
"has_key?",
"(",
":password",
")",
"self",
".",
"class",
".",
"basic_auth",
"auth_hash",
"[",
":username",
"]",
",",
"auth_hash",
"[",
":password",
"]",
"self",
".",
"class",
".",
"headers",
".",
"reject!",
"{",
"|",
"k",
",",
"v",
"|",
"k",
"==",
"\"Authorization\"",
"}",
"else",
"raise",
"\"\"",
"\" Incomplete authorization information passed in authorization hash. You must have either an :access_token or a username password combination (:username, :password). \"",
"\"\"",
"end",
"end"
] | Initializes the Logan shared client with information required to communicate with Basecamp
@param basecamp_id [String] the Basecamp company ID
@param auth_hash [Hash] authorization hash consisting of a username and password combination (:username, :password) or an access_token (:access_token)
@param user_agent [String] the user-agent string to include in header of requests
Updates authorization information for Logan shared client
@param auth_hash [Hash] authorization hash consisting of a username and password combination (:username, :password) or an access_token (:access_token) | [
"Initializes",
"the",
"Logan",
"shared",
"client",
"with",
"information",
"required",
"to",
"communicate",
"with",
"Basecamp"
] | c007081c7dbb5b98ef5312db78f84867c6075ab0 | https://github.com/birarda/logan/blob/c007081c7dbb5b98ef5312db78f84867c6075ab0/lib/logan/client.rb#L22-L45 | train |
birarda/logan | lib/logan/client.rb | Logan.Client.project_templates | def project_templates
response = self.class.get '/project_templates.json'
handle_response(response, Proc.new {|h| Logan::ProjectTemplate.new(h) })
end | ruby | def project_templates
response = self.class.get '/project_templates.json'
handle_response(response, Proc.new {|h| Logan::ProjectTemplate.new(h) })
end | [
"def",
"project_templates",
"response",
"=",
"self",
".",
"class",
".",
"get",
"'/project_templates.json'",
"handle_response",
"(",
"response",
",",
"Proc",
".",
"new",
"{",
"|",
"h",
"|",
"Logan",
"::",
"ProjectTemplate",
".",
"new",
"(",
"h",
")",
"}",
")",
"end"
] | get project templates from Basecamp API
@return [Array<Logan::ProjectTemplate>] array of {Logan::ProjectTemplate} instances | [
"get",
"project",
"templates",
"from",
"Basecamp",
"API"
] | c007081c7dbb5b98ef5312db78f84867c6075ab0 | https://github.com/birarda/logan/blob/c007081c7dbb5b98ef5312db78f84867c6075ab0/lib/logan/client.rb#L61-L64 | train |
birarda/logan | lib/logan/client.rb | Logan.Client.todolists | def todolists
response = self.class.get '/todolists.json'
handle_response(response,
Proc.new { |h|
list = Logan::TodoList.new(h)
# grab the project ID for this list from the url
list.project_id = list.url.scan( /projects\/(\d+)/).last.first
# return the list so this method returns an array of lists
list
}
)
end | ruby | def todolists
response = self.class.get '/todolists.json'
handle_response(response,
Proc.new { |h|
list = Logan::TodoList.new(h)
# grab the project ID for this list from the url
list.project_id = list.url.scan( /projects\/(\d+)/).last.first
# return the list so this method returns an array of lists
list
}
)
end | [
"def",
"todolists",
"response",
"=",
"self",
".",
"class",
".",
"get",
"'/todolists.json'",
"handle_response",
"(",
"response",
",",
"Proc",
".",
"new",
"{",
"|",
"h",
"|",
"list",
"=",
"Logan",
"::",
"TodoList",
".",
"new",
"(",
"h",
")",
"list",
".",
"project_id",
"=",
"list",
".",
"url",
".",
"scan",
"(",
"/",
"\\/",
"\\d",
"/",
")",
".",
"last",
".",
"first",
"list",
"}",
")",
"end"
] | get active Todo lists for all projects from Basecamp API
@return [Array<Logan::TodoList>] array of {Logan::TodoList} instances | [
"get",
"active",
"Todo",
"lists",
"for",
"all",
"projects",
"from",
"Basecamp",
"API"
] | c007081c7dbb5b98ef5312db78f84867c6075ab0 | https://github.com/birarda/logan/blob/c007081c7dbb5b98ef5312db78f84867c6075ab0/lib/logan/client.rb#L69-L82 | train |
nyk/catflap | lib/catflap/netfilter/writer.rb | NetfilterWriter.Rules.chain | def chain(cmd, chain, p = {})
cmds = {
new: '-N', rename: '-E', delete: '-X', flush: '-F',
list_rules: '-S', list: '-L', zero: '-Z', policy: '-P'
}
@buffer << [
'iptables',
option('-t', @table), cmds[cmd], option('-n', p[:numeric]), chain,
option(false, p[:rulenum]), option(false, p[:to])
].compact.join(' ') << "\n"
self
end | ruby | def chain(cmd, chain, p = {})
cmds = {
new: '-N', rename: '-E', delete: '-X', flush: '-F',
list_rules: '-S', list: '-L', zero: '-Z', policy: '-P'
}
@buffer << [
'iptables',
option('-t', @table), cmds[cmd], option('-n', p[:numeric]), chain,
option(false, p[:rulenum]), option(false, p[:to])
].compact.join(' ') << "\n"
self
end | [
"def",
"chain",
"(",
"cmd",
",",
"chain",
",",
"p",
"=",
"{",
"}",
")",
"cmds",
"=",
"{",
"new",
":",
"'-N'",
",",
"rename",
":",
"'-E'",
",",
"delete",
":",
"'-X'",
",",
"flush",
":",
"'-F'",
",",
"list_rules",
":",
"'-S'",
",",
"list",
":",
"'-L'",
",",
"zero",
":",
"'-Z'",
",",
"policy",
":",
"'-P'",
"}",
"@buffer",
"<<",
"[",
"'iptables'",
",",
"option",
"(",
"'-t'",
",",
"@table",
")",
",",
"cmds",
"[",
"cmd",
"]",
",",
"option",
"(",
"'-n'",
",",
"p",
"[",
":numeric",
"]",
")",
",",
"chain",
",",
"option",
"(",
"false",
",",
"p",
"[",
":rulenum",
"]",
")",
",",
"option",
"(",
"false",
",",
"p",
"[",
":to",
"]",
")",
"]",
".",
"compact",
".",
"join",
"(",
"' '",
")",
"<<",
"\"\\n\"",
"self",
"end"
] | Create, flush and delete chains and other iptable chain operations.
@param [Symbol] cmd the operation to perform (:new, :delete, :flush)
@param [String] chain name of the chain (e.g. INPUT, CATFLAP-DENY, etc.)
@param [Hash] p parameters for specific iptables features.
@return self
@example
Rules.new('nat').chain(:list, 'MY-CHAIN', numeric: true).flush
=> "iptables -t nat -n -L MY-CHAIN" | [
"Create",
"flush",
"and",
"delete",
"chains",
"and",
"other",
"iptable",
"chain",
"operations",
"."
] | e146e5df6d8d0085c127bf3ab77bfecfa9af78d9 | https://github.com/nyk/catflap/blob/e146e5df6d8d0085c127bf3ab77bfecfa9af78d9/lib/catflap/netfilter/writer.rb#L44-L57 | train |
bilus/akasha | lib/akasha/changeset.rb | Akasha.Changeset.append | def append(event_name, **data)
id = SecureRandom.uuid
event = Akasha::Event.new(event_name, id, { aggregate_id: aggregate_id }, **data)
@aggregate.apply_events([event])
@events << event
end | ruby | def append(event_name, **data)
id = SecureRandom.uuid
event = Akasha::Event.new(event_name, id, { aggregate_id: aggregate_id }, **data)
@aggregate.apply_events([event])
@events << event
end | [
"def",
"append",
"(",
"event_name",
",",
"**",
"data",
")",
"id",
"=",
"SecureRandom",
".",
"uuid",
"event",
"=",
"Akasha",
"::",
"Event",
".",
"new",
"(",
"event_name",
",",
"id",
",",
"{",
"aggregate_id",
":",
"aggregate_id",
"}",
",",
"**",
"data",
")",
"@aggregate",
".",
"apply_events",
"(",
"[",
"event",
"]",
")",
"@events",
"<<",
"event",
"end"
] | Adds an event to the changeset. | [
"Adds",
"an",
"event",
"to",
"the",
"changeset",
"."
] | 5fadefc249f520ae909b762956ac23a6f916b021 | https://github.com/bilus/akasha/blob/5fadefc249f520ae909b762956ac23a6f916b021/lib/akasha/changeset.rb#L17-L22 | train |
chetan/bixby-client | lib/bixby-client/client.rb | Bixby.Client.exec_api | def exec_api(json_req)
begin
req = sign_request(json_req)
return HttpChannel.new(api_uri).execute(req)
rescue Curl::Err::CurlError => ex
return JsonResponse.new("fail", ex.message)
end
end | ruby | def exec_api(json_req)
begin
req = sign_request(json_req)
return HttpChannel.new(api_uri).execute(req)
rescue Curl::Err::CurlError => ex
return JsonResponse.new("fail", ex.message)
end
end | [
"def",
"exec_api",
"(",
"json_req",
")",
"begin",
"req",
"=",
"sign_request",
"(",
"json_req",
")",
"return",
"HttpChannel",
".",
"new",
"(",
"api_uri",
")",
".",
"execute",
"(",
"req",
")",
"rescue",
"Curl",
"::",
"Err",
"::",
"CurlError",
"=>",
"ex",
"return",
"JsonResponse",
".",
"new",
"(",
"\"fail\"",
",",
"ex",
".",
"message",
")",
"end",
"end"
] | Execute the given API request on the manager
@param [JsonRequest] json_req
@return [JsonResponse] | [
"Execute",
"the",
"given",
"API",
"request",
"on",
"the",
"manager"
] | 5444c2fb154fddef53459dd5cebe08b3f091d252 | https://github.com/chetan/bixby-client/blob/5444c2fb154fddef53459dd5cebe08b3f091d252/lib/bixby-client/client.rb#L46-L53 | train |
asaaki/sjekksum | lib/sjekksum/luhn.rb | Sjekksum.Luhn.of | def of number
raise_on_type_mismatch number
digits = convert_number_to_digits(number)
sum = digits.reverse.map.with_index do |digit, idx|
idx.even? ? (digit * 2).divmod(10).reduce(&:+) : digit
end.reduce(&:+)
(10 - sum % 10) % 10
end | ruby | def of number
raise_on_type_mismatch number
digits = convert_number_to_digits(number)
sum = digits.reverse.map.with_index do |digit, idx|
idx.even? ? (digit * 2).divmod(10).reduce(&:+) : digit
end.reduce(&:+)
(10 - sum % 10) % 10
end | [
"def",
"of",
"number",
"raise_on_type_mismatch",
"number",
"digits",
"=",
"convert_number_to_digits",
"(",
"number",
")",
"sum",
"=",
"digits",
".",
"reverse",
".",
"map",
".",
"with_index",
"do",
"|",
"digit",
",",
"idx",
"|",
"idx",
".",
"even?",
"?",
"(",
"digit",
"*",
"2",
")",
".",
"divmod",
"(",
"10",
")",
".",
"reduce",
"(",
"&",
":+",
")",
":",
"digit",
"end",
".",
"reduce",
"(",
"&",
":+",
")",
"(",
"10",
"-",
"sum",
"%",
"10",
")",
"%",
"10",
"end"
] | Calculates Luhn checksum
@example
Sjekksum::Luhn.of(7992739871) #=> 3
@param number [Integer, String] number for which the checksum should be calculated
@return [Integer] calculated checksum | [
"Calculates",
"Luhn",
"checksum"
] | 47a21c19dcffc67a3bef11d4f2de7c167fd20087 | https://github.com/asaaki/sjekksum/blob/47a21c19dcffc67a3bef11d4f2de7c167fd20087/lib/sjekksum/luhn.rb#L20-L29 | train |
sgillesp/taxonomite | lib/taxonomite/taxonomy.rb | Taxonomite.Taxonomy.valid_parent_types | def valid_parent_types(child)
# could be a node object, or maybe a string
str = child.respond_to?(:entity_type) ? child.entity_type : child
self.up_taxonomy[str]
end | ruby | def valid_parent_types(child)
# could be a node object, or maybe a string
str = child.respond_to?(:entity_type) ? child.entity_type : child
self.up_taxonomy[str]
end | [
"def",
"valid_parent_types",
"(",
"child",
")",
"str",
"=",
"child",
".",
"respond_to?",
"(",
":entity_type",
")",
"?",
"child",
".",
"entity_type",
":",
"child",
"self",
".",
"up_taxonomy",
"[",
"str",
"]",
"end"
] | access the appropriate parent entity_types for a particular child or child entity_type
@param [Taxonomy::Node, String] child the child object or entity_type string
@return [Array] an array of strings which are the valid parent types for the child | [
"access",
"the",
"appropriate",
"parent",
"entity_types",
"for",
"a",
"particular",
"child",
"or",
"child",
"entity_type"
] | 731b42d0dfa1f52b39d050026f49b2d205407ff8 | https://github.com/sgillesp/taxonomite/blob/731b42d0dfa1f52b39d050026f49b2d205407ff8/lib/taxonomite/taxonomy.rb#L56-L60 | train |
sgillesp/taxonomite | lib/taxonomite/taxonomy.rb | Taxonomite.Taxonomy.valid_child_types | def valid_child_types(parent)
# could be a node object, or maybe a string
str = parent.respond_to?(:entity_type) ? parent.entity_type : child
self.down_taxonomy[str]
end | ruby | def valid_child_types(parent)
# could be a node object, or maybe a string
str = parent.respond_to?(:entity_type) ? parent.entity_type : child
self.down_taxonomy[str]
end | [
"def",
"valid_child_types",
"(",
"parent",
")",
"str",
"=",
"parent",
".",
"respond_to?",
"(",
":entity_type",
")",
"?",
"parent",
".",
"entity_type",
":",
"child",
"self",
".",
"down_taxonomy",
"[",
"str",
"]",
"end"
] | access the appropriate child entity_types for a particular parent or parent entity_type
@param [Taxonomy::Node, String] parent the parent object or entity_type string
@return [Array] an array of strings which are the valid child types for the child | [
"access",
"the",
"appropriate",
"child",
"entity_types",
"for",
"a",
"particular",
"parent",
"or",
"parent",
"entity_type"
] | 731b42d0dfa1f52b39d050026f49b2d205407ff8 | https://github.com/sgillesp/taxonomite/blob/731b42d0dfa1f52b39d050026f49b2d205407ff8/lib/taxonomite/taxonomy.rb#L66-L70 | train |
thumblemonks/riot-rails | lib/riot/action_controller/context_middleware.rb | RiotRails.ActionControllerMiddleware.nested_handle? | def nested_handle?(context)
(handle?(context.description) || nested_handle?(context.parent)) if context.respond_to?(:description)
end | ruby | def nested_handle?(context)
(handle?(context.description) || nested_handle?(context.parent)) if context.respond_to?(:description)
end | [
"def",
"nested_handle?",
"(",
"context",
")",
"(",
"handle?",
"(",
"context",
".",
"description",
")",
"||",
"nested_handle?",
"(",
"context",
".",
"parent",
")",
")",
"if",
"context",
".",
"respond_to?",
"(",
":description",
")",
"end"
] | Walking the description chain looking to see if any of them are serviceable
TODO: see if we can't define a method on the context to observe instead of calling
action_controller_description? each time | [
"Walking",
"the",
"description",
"chain",
"looking",
"to",
"see",
"if",
"any",
"of",
"them",
"are",
"serviceable"
] | 8bb2555d04f7fb67407f7224536e8b32349cede1 | https://github.com/thumblemonks/riot-rails/blob/8bb2555d04f7fb67407f7224536e8b32349cede1/lib/riot/action_controller/context_middleware.rb#L19-L21 | train |
dlangevin/gxapi_rails | lib/gxapi/base.rb | Gxapi.Base.get_variant | def get_variant(identifier, override = nil)
# identifier object to handle finding and caching the
# experiment
identifier = GxApi::ExperimentIdentifier.new(identifier)
Celluloid::Future.new do
# allows us to override and get back a variant
# easily that conforms to the api
if override.nil?
self.get_variant_value(identifier)
else
Ostruct.new(self.default_values.merge(name: override))
end
end
end | ruby | def get_variant(identifier, override = nil)
# identifier object to handle finding and caching the
# experiment
identifier = GxApi::ExperimentIdentifier.new(identifier)
Celluloid::Future.new do
# allows us to override and get back a variant
# easily that conforms to the api
if override.nil?
self.get_variant_value(identifier)
else
Ostruct.new(self.default_values.merge(name: override))
end
end
end | [
"def",
"get_variant",
"(",
"identifier",
",",
"override",
"=",
"nil",
")",
"identifier",
"=",
"GxApi",
"::",
"ExperimentIdentifier",
".",
"new",
"(",
"identifier",
")",
"Celluloid",
"::",
"Future",
".",
"new",
"do",
"if",
"override",
".",
"nil?",
"self",
".",
"get_variant_value",
"(",
"identifier",
")",
"else",
"Ostruct",
".",
"new",
"(",
"self",
".",
"default_values",
".",
"merge",
"(",
"name",
":",
"override",
")",
")",
"end",
"end",
"end"
] | return a variant value by name or id
@param identifier [String, Hash] The name of the experiment or a hash
with the id of the experiment
@param override [String] Override value returned from the experiment
@example
variant = @gxapi.get_variant("my_experiment")
variant.value =>
# Ostruct.new(experiment_id: "x", index: 1, name: "name")
@example
variant = @gxapi.get_variant(id: "x")
variant.value =>
# Ostruct.new(experiment_id: "x", index: 1, name: "name")
@return [Celluloid::Future] | [
"return",
"a",
"variant",
"value",
"by",
"name",
"or",
"id"
] | 21361227f0c70118b38f7fa372a18c0ae7aab810 | https://github.com/dlangevin/gxapi_rails/blob/21361227f0c70118b38f7fa372a18c0ae7aab810/lib/gxapi/base.rb#L55-L69 | train |
dlangevin/gxapi_rails | lib/gxapi/base.rb | Gxapi.Base.get_variant_value | def get_variant_value(identifier)
data = Gxapi.with_error_handling do
Timeout::timeout(2.0) do
Gxapi.cache.fetch(self.cache_key(identifier)) do
@interface.get_variant(identifier).to_hash
end
end
end
Ostruct.new(
data.is_a?(Hash) ? data : self.default_values
)
end | ruby | def get_variant_value(identifier)
data = Gxapi.with_error_handling do
Timeout::timeout(2.0) do
Gxapi.cache.fetch(self.cache_key(identifier)) do
@interface.get_variant(identifier).to_hash
end
end
end
Ostruct.new(
data.is_a?(Hash) ? data : self.default_values
)
end | [
"def",
"get_variant_value",
"(",
"identifier",
")",
"data",
"=",
"Gxapi",
".",
"with_error_handling",
"do",
"Timeout",
"::",
"timeout",
"(",
"2.0",
")",
"do",
"Gxapi",
".",
"cache",
".",
"fetch",
"(",
"self",
".",
"cache_key",
"(",
"identifier",
")",
")",
"do",
"@interface",
".",
"get_variant",
"(",
"identifier",
")",
".",
"to_hash",
"end",
"end",
"end",
"Ostruct",
".",
"new",
"(",
"data",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"data",
":",
"self",
".",
"default_values",
")",
"end"
] | protected method to make the actual calls to get values
from the cache or from Google
@param identifier [ExperimentIdentifier] Experiment to look for
@return [Gxapi::Ostruct] Experiment data | [
"protected",
"method",
"to",
"make",
"the",
"actual",
"calls",
"to",
"get",
"values",
"from",
"the",
"cache",
"or",
"from",
"Google"
] | 21361227f0c70118b38f7fa372a18c0ae7aab810 | https://github.com/dlangevin/gxapi_rails/blob/21361227f0c70118b38f7fa372a18c0ae7aab810/lib/gxapi/base.rb#L108-L119 | train |
thumblemonks/riot-rails | lib/riot/active_record/transactional_middleware.rb | RiotRails.TransactionalMiddleware.hijack_local_run | def hijack_local_run(context)
(class << context; self; end).class_eval do
alias_method :transactionless_local_run, :local_run
def local_run(*args)
::ActiveRecord::Base.transaction do
transactionless_local_run(*args)
raise ::ActiveRecord::Rollback
end
end # local_run
end # metaclass
end | ruby | def hijack_local_run(context)
(class << context; self; end).class_eval do
alias_method :transactionless_local_run, :local_run
def local_run(*args)
::ActiveRecord::Base.transaction do
transactionless_local_run(*args)
raise ::ActiveRecord::Rollback
end
end # local_run
end # metaclass
end | [
"def",
"hijack_local_run",
"(",
"context",
")",
"(",
"class",
"<<",
"context",
";",
"self",
";",
"end",
")",
".",
"class_eval",
"do",
"alias_method",
":transactionless_local_run",
",",
":local_run",
"def",
"local_run",
"(",
"*",
"args",
")",
"::",
"ActiveRecord",
"::",
"Base",
".",
"transaction",
"do",
"transactionless_local_run",
"(",
"*",
"args",
")",
"raise",
"::",
"ActiveRecord",
"::",
"Rollback",
"end",
"end",
"end",
"end"
] | Don't you just love mr. metaclass? | [
"Don",
"t",
"you",
"just",
"love",
"mr",
".",
"metaclass?"
] | 8bb2555d04f7fb67407f7224536e8b32349cede1 | https://github.com/thumblemonks/riot-rails/blob/8bb2555d04f7fb67407f7224536e8b32349cede1/lib/riot/active_record/transactional_middleware.rb#L15-L25 | train |
medcat/packed_struct | lib/packed_struct/directive.rb | PackedStruct.Directive.[] | def [](new_size)
if new_size.is_a? Directive
tags.merge! new_size.tags_for_sized_directive
else
tags[:size] = new_size
end
self
end | ruby | def [](new_size)
if new_size.is_a? Directive
tags.merge! new_size.tags_for_sized_directive
else
tags[:size] = new_size
end
self
end | [
"def",
"[]",
"(",
"new_size",
")",
"if",
"new_size",
".",
"is_a?",
"Directive",
"tags",
".",
"merge!",
"new_size",
".",
"tags_for_sized_directive",
"else",
"tags",
"[",
":size",
"]",
"=",
"new_size",
"end",
"self",
"end"
] | Changes the size of the directive to the given size. It is
possible for the given value to the a directive; if it is,
it just uses the name of the directive.
@param new_size [Numeric, Directive]
@return [self] | [
"Changes",
"the",
"size",
"of",
"the",
"directive",
"to",
"the",
"given",
"size",
".",
"It",
"is",
"possible",
"for",
"the",
"given",
"value",
"to",
"the",
"a",
"directive",
";",
"if",
"it",
"is",
"it",
"just",
"uses",
"the",
"name",
"of",
"the",
"directive",
"."
] | 4c32c17acbfbe8c1a1a27daafb04d2f6bee0347f | https://github.com/medcat/packed_struct/blob/4c32c17acbfbe8c1a1a27daafb04d2f6bee0347f/lib/packed_struct/directive.rb#L69-L77 | train |
medcat/packed_struct | lib/packed_struct/directive.rb | PackedStruct.Directive.finalize! | def finalize!
return if finalized?
modifiers.each do |modifier|
modifier.type.each_with_index do |type, i|
case type
when :endian, :signedness, :precision, :type, :string_type
tags[type] = modifier.value[i]
when :size
tags[:size] = modifier.value[i] unless tags[:size]
else
raise UnknownModifierError,
"Unknown modifier: #{type}"
end
end
end
@finalized = true
cache_string
end | ruby | def finalize!
return if finalized?
modifiers.each do |modifier|
modifier.type.each_with_index do |type, i|
case type
when :endian, :signedness, :precision, :type, :string_type
tags[type] = modifier.value[i]
when :size
tags[:size] = modifier.value[i] unless tags[:size]
else
raise UnknownModifierError,
"Unknown modifier: #{type}"
end
end
end
@finalized = true
cache_string
end | [
"def",
"finalize!",
"return",
"if",
"finalized?",
"modifiers",
".",
"each",
"do",
"|",
"modifier",
"|",
"modifier",
".",
"type",
".",
"each_with_index",
"do",
"|",
"type",
",",
"i",
"|",
"case",
"type",
"when",
":endian",
",",
":signedness",
",",
":precision",
",",
":type",
",",
":string_type",
"tags",
"[",
"type",
"]",
"=",
"modifier",
".",
"value",
"[",
"i",
"]",
"when",
":size",
"tags",
"[",
":size",
"]",
"=",
"modifier",
".",
"value",
"[",
"i",
"]",
"unless",
"tags",
"[",
":size",
"]",
"else",
"raise",
"UnknownModifierError",
",",
"\"Unknown modifier: #{type}\"",
"end",
"end",
"end",
"@finalized",
"=",
"true",
"cache_string",
"end"
] | Finalizes the directive.
@return [void] | [
"Finalizes",
"the",
"directive",
"."
] | 4c32c17acbfbe8c1a1a27daafb04d2f6bee0347f | https://github.com/medcat/packed_struct/blob/4c32c17acbfbe8c1a1a27daafb04d2f6bee0347f/lib/packed_struct/directive.rb#L144-L163 | train |
medcat/packed_struct | lib/packed_struct/directive.rb | PackedStruct.Directive.bytesize | def bytesize(data = {})
case tags[:type]
when nil
(size(data) || 8) / 8
when :short, :int, :long
BYTES_IN_STRING.fetch tags[:type]
when :float
if tags[:precision] == :double
BYTES_IN_STRING[:float_double]
else
BYTES_IN_STRING[:float_single]
end
when :null
size(data) || 1
when :string
size(data)
else
0
end
end | ruby | def bytesize(data = {})
case tags[:type]
when nil
(size(data) || 8) / 8
when :short, :int, :long
BYTES_IN_STRING.fetch tags[:type]
when :float
if tags[:precision] == :double
BYTES_IN_STRING[:float_double]
else
BYTES_IN_STRING[:float_single]
end
when :null
size(data) || 1
when :string
size(data)
else
0
end
end | [
"def",
"bytesize",
"(",
"data",
"=",
"{",
"}",
")",
"case",
"tags",
"[",
":type",
"]",
"when",
"nil",
"(",
"size",
"(",
"data",
")",
"||",
"8",
")",
"/",
"8",
"when",
":short",
",",
":int",
",",
":long",
"BYTES_IN_STRING",
".",
"fetch",
"tags",
"[",
":type",
"]",
"when",
":float",
"if",
"tags",
"[",
":precision",
"]",
"==",
":double",
"BYTES_IN_STRING",
"[",
":float_double",
"]",
"else",
"BYTES_IN_STRING",
"[",
":float_single",
"]",
"end",
"when",
":null",
"size",
"(",
"data",
")",
"||",
"1",
"when",
":string",
"size",
"(",
"data",
")",
"else",
"0",
"end",
"end"
] | The number of bytes this takes up in the resulting packed string.
@param (see #to_s)
@return [Numeric] | [
"The",
"number",
"of",
"bytes",
"this",
"takes",
"up",
"in",
"the",
"resulting",
"packed",
"string",
"."
] | 4c32c17acbfbe8c1a1a27daafb04d2f6bee0347f | https://github.com/medcat/packed_struct/blob/4c32c17acbfbe8c1a1a27daafb04d2f6bee0347f/lib/packed_struct/directive.rb#L223-L242 | train |
medcat/packed_struct | lib/packed_struct/directive.rb | PackedStruct.Directive.modify_if_needed | def modify_if_needed(str, include_endian = true)
base = if @tags[:signedness] == :signed
str.swapcase
else
str
end
if include_endian
modify_for_endianness(base)
else
base
end
end | ruby | def modify_if_needed(str, include_endian = true)
base = if @tags[:signedness] == :signed
str.swapcase
else
str
end
if include_endian
modify_for_endianness(base)
else
base
end
end | [
"def",
"modify_if_needed",
"(",
"str",
",",
"include_endian",
"=",
"true",
")",
"base",
"=",
"if",
"@tags",
"[",
":signedness",
"]",
"==",
":signed",
"str",
".",
"swapcase",
"else",
"str",
"end",
"if",
"include_endian",
"modify_for_endianness",
"(",
"base",
")",
"else",
"base",
"end",
"end"
] | Modifies the given string if it's needed, according to
signness and endianness. This assumes that a signed
directive should be in lowercase.
@param str [String] the string to modify.
@param include_endian [Boolean] whether or not to include the
endianness.
@return [String] | [
"Modifies",
"the",
"given",
"string",
"if",
"it",
"s",
"needed",
"according",
"to",
"signness",
"and",
"endianness",
".",
"This",
"assumes",
"that",
"a",
"signed",
"directive",
"should",
"be",
"in",
"lowercase",
"."
] | 4c32c17acbfbe8c1a1a27daafb04d2f6bee0347f | https://github.com/medcat/packed_struct/blob/4c32c17acbfbe8c1a1a27daafb04d2f6bee0347f/lib/packed_struct/directive.rb#L339-L350 | train |
medcat/packed_struct | lib/packed_struct/directive.rb | PackedStruct.Directive.modify_for_endianness | def modify_for_endianness(str, use_case = false)
case [tags[:endian], use_case]
when [:little, true]
str.swapcase
when [:little, false]
str + "<"
when [:big, true]
str
when [:big, false]
str + ">"
else
str
end
end | ruby | def modify_for_endianness(str, use_case = false)
case [tags[:endian], use_case]
when [:little, true]
str.swapcase
when [:little, false]
str + "<"
when [:big, true]
str
when [:big, false]
str + ">"
else
str
end
end | [
"def",
"modify_for_endianness",
"(",
"str",
",",
"use_case",
"=",
"false",
")",
"case",
"[",
"tags",
"[",
":endian",
"]",
",",
"use_case",
"]",
"when",
"[",
":little",
",",
"true",
"]",
"str",
".",
"swapcase",
"when",
"[",
":little",
",",
"false",
"]",
"str",
"+",
"\"<\"",
"when",
"[",
":big",
",",
"true",
"]",
"str",
"when",
"[",
":big",
",",
"false",
"]",
"str",
"+",
"\">\"",
"else",
"str",
"end",
"end"
] | Modifies the given string to account for endianness. If
+use_case+ is true, it modifies the case of the given string to
represent endianness; otherwise, it appends data to the string
to represent endianness.
@param str [String] the string to modify.
@param use_case [Boolean]
@return [String] | [
"Modifies",
"the",
"given",
"string",
"to",
"account",
"for",
"endianness",
".",
"If",
"+",
"use_case",
"+",
"is",
"true",
"it",
"modifies",
"the",
"case",
"of",
"the",
"given",
"string",
"to",
"represent",
"endianness",
";",
"otherwise",
"it",
"appends",
"data",
"to",
"the",
"string",
"to",
"represent",
"endianness",
"."
] | 4c32c17acbfbe8c1a1a27daafb04d2f6bee0347f | https://github.com/medcat/packed_struct/blob/4c32c17acbfbe8c1a1a27daafb04d2f6bee0347f/lib/packed_struct/directive.rb#L360-L373 | train |
bdurand/acts_as_trashable | lib/acts_as_trashable/trash_record.rb | ActsAsTrashable.TrashRecord.restore | def restore
restore_class = self.trashable_type.constantize
sti_type = self.trashable_attributes[restore_class.inheritance_column]
if sti_type
begin
if !restore_class.store_full_sti_class && !sti_type.start_with?("::")
sti_type = "#{restore_class.parent.name}::#{sti_type}"
end
restore_class = sti_type.constantize
rescue NameError => e
raise e
# Seems our assumption was wrong and we have no STI
end
end
attrs, association_attrs = attributes_and_associations(restore_class, self.trashable_attributes)
record = restore_class.new
attrs.each_pair do |key, value|
record.send("#{key}=", value)
end
association_attrs.each_pair do |association, attribute_values|
restore_association(record, association, attribute_values)
end
return record
end | ruby | def restore
restore_class = self.trashable_type.constantize
sti_type = self.trashable_attributes[restore_class.inheritance_column]
if sti_type
begin
if !restore_class.store_full_sti_class && !sti_type.start_with?("::")
sti_type = "#{restore_class.parent.name}::#{sti_type}"
end
restore_class = sti_type.constantize
rescue NameError => e
raise e
# Seems our assumption was wrong and we have no STI
end
end
attrs, association_attrs = attributes_and_associations(restore_class, self.trashable_attributes)
record = restore_class.new
attrs.each_pair do |key, value|
record.send("#{key}=", value)
end
association_attrs.each_pair do |association, attribute_values|
restore_association(record, association, attribute_values)
end
return record
end | [
"def",
"restore",
"restore_class",
"=",
"self",
".",
"trashable_type",
".",
"constantize",
"sti_type",
"=",
"self",
".",
"trashable_attributes",
"[",
"restore_class",
".",
"inheritance_column",
"]",
"if",
"sti_type",
"begin",
"if",
"!",
"restore_class",
".",
"store_full_sti_class",
"&&",
"!",
"sti_type",
".",
"start_with?",
"(",
"\"::\"",
")",
"sti_type",
"=",
"\"#{restore_class.parent.name}::#{sti_type}\"",
"end",
"restore_class",
"=",
"sti_type",
".",
"constantize",
"rescue",
"NameError",
"=>",
"e",
"raise",
"e",
"end",
"end",
"attrs",
",",
"association_attrs",
"=",
"attributes_and_associations",
"(",
"restore_class",
",",
"self",
".",
"trashable_attributes",
")",
"record",
"=",
"restore_class",
".",
"new",
"attrs",
".",
"each_pair",
"do",
"|",
"key",
",",
"value",
"|",
"record",
".",
"send",
"(",
"\"#{key}=\"",
",",
"value",
")",
"end",
"association_attrs",
".",
"each_pair",
"do",
"|",
"association",
",",
"attribute_values",
"|",
"restore_association",
"(",
"record",
",",
"association",
",",
"attribute_values",
")",
"end",
"return",
"record",
"end"
] | Create a new trash record for the provided record.
Restore a trashed record into an object. The record will not be saved. | [
"Create",
"a",
"new",
"trash",
"record",
"for",
"the",
"provided",
"record",
".",
"Restore",
"a",
"trashed",
"record",
"into",
"an",
"object",
".",
"The",
"record",
"will",
"not",
"be",
"saved",
"."
] | 8bb0e40d6b30dda9c5175a0deb28da1b067fff03 | https://github.com/bdurand/acts_as_trashable/blob/8bb0e40d6b30dda9c5175a0deb28da1b067fff03/lib/acts_as_trashable/trash_record.rb#L56-L84 | train |
bdurand/acts_as_trashable | lib/acts_as_trashable/trash_record.rb | ActsAsTrashable.TrashRecord.trashable_attributes | def trashable_attributes
return nil unless self.data
uncompressed = Zlib::Inflate.inflate(self.data) rescue uncompressed = self.data # backward compatibility with uncompressed data
Marshal.load(uncompressed)
end | ruby | def trashable_attributes
return nil unless self.data
uncompressed = Zlib::Inflate.inflate(self.data) rescue uncompressed = self.data # backward compatibility with uncompressed data
Marshal.load(uncompressed)
end | [
"def",
"trashable_attributes",
"return",
"nil",
"unless",
"self",
".",
"data",
"uncompressed",
"=",
"Zlib",
"::",
"Inflate",
".",
"inflate",
"(",
"self",
".",
"data",
")",
"rescue",
"uncompressed",
"=",
"self",
".",
"data",
"Marshal",
".",
"load",
"(",
"uncompressed",
")",
"end"
] | Attributes of the trashed record as a hash. | [
"Attributes",
"of",
"the",
"trashed",
"record",
"as",
"a",
"hash",
"."
] | 8bb0e40d6b30dda9c5175a0deb28da1b067fff03 | https://github.com/bdurand/acts_as_trashable/blob/8bb0e40d6b30dda9c5175a0deb28da1b067fff03/lib/acts_as_trashable/trash_record.rb#L95-L99 | train |
emancu/ork | lib/ork/model/document.rb | Ork.Document.save | def save
__robject.content_type = model.content_type
__robject.data = __persist_attributes
__check_unique_indices
__update_indices
__robject.store
@id = __robject.key
self
end | ruby | def save
__robject.content_type = model.content_type
__robject.data = __persist_attributes
__check_unique_indices
__update_indices
__robject.store
@id = __robject.key
self
end | [
"def",
"save",
"__robject",
".",
"content_type",
"=",
"model",
".",
"content_type",
"__robject",
".",
"data",
"=",
"__persist_attributes",
"__check_unique_indices",
"__update_indices",
"__robject",
".",
"store",
"@id",
"=",
"__robject",
".",
"key",
"self",
"end"
] | Persist the model attributes and update indices and unique
indices.
Example:
class User
include Ork::Document
attribute :name
end
u = User.new(:name => "John").save
# => #<User:6kS5VHNbaed9h7gFLnVg5lmO4U7 {:name=>"John"}> | [
"Persist",
"the",
"model",
"attributes",
"and",
"update",
"indices",
"and",
"unique",
"indices",
"."
] | 83b2deaef0e790d90f98c031f254b5f438b19edf | https://github.com/emancu/ork/blob/83b2deaef0e790d90f98c031f254b5f438b19edf/lib/ork/model/document.rb#L72-L83 | train |
emancu/ork | lib/ork/model/document.rb | Ork.Document.load! | def load!(id)
self.__robject.key = id
__load_robject! id, @__robject.reload(force: true)
end | ruby | def load!(id)
self.__robject.key = id
__load_robject! id, @__robject.reload(force: true)
end | [
"def",
"load!",
"(",
"id",
")",
"self",
".",
"__robject",
".",
"key",
"=",
"id",
"__load_robject!",
"id",
",",
"@__robject",
".",
"reload",
"(",
"force",
":",
"true",
")",
"end"
] | Overwrite attributes with the persisted attributes in Riak. | [
"Overwrite",
"attributes",
"with",
"the",
"persisted",
"attributes",
"in",
"Riak",
"."
] | 83b2deaef0e790d90f98c031f254b5f438b19edf | https://github.com/emancu/ork/blob/83b2deaef0e790d90f98c031f254b5f438b19edf/lib/ork/model/document.rb#L102-L105 | train |
emancu/ork | lib/ork/model/document.rb | Ork.Document.__update_indices | def __update_indices
model.indices.values.each do |index|
__robject.indexes[index.riak_name] = index.value_from(attributes)
end
end | ruby | def __update_indices
model.indices.values.each do |index|
__robject.indexes[index.riak_name] = index.value_from(attributes)
end
end | [
"def",
"__update_indices",
"model",
".",
"indices",
".",
"values",
".",
"each",
"do",
"|",
"index",
"|",
"__robject",
".",
"indexes",
"[",
"index",
".",
"riak_name",
"]",
"=",
"index",
".",
"value_from",
"(",
"attributes",
")",
"end",
"end"
] | Build the secondary indices of this object | [
"Build",
"the",
"secondary",
"indices",
"of",
"this",
"object"
] | 83b2deaef0e790d90f98c031f254b5f438b19edf | https://github.com/emancu/ork/blob/83b2deaef0e790d90f98c031f254b5f438b19edf/lib/ork/model/document.rb#L132-L136 | train |
emancu/ork | lib/ork/model/document.rb | Ork.Document.__check_unique_indices | def __check_unique_indices
model.uniques.each do |uniq|
if value = attributes[uniq]
index = model.indices[uniq]
records = model.bucket.get_index(index.riak_name, value)
unless records.empty? || records == [self.id]
raise Ork::UniqueIndexViolation, "#{uniq} is not unique"
end
end
end
end | ruby | def __check_unique_indices
model.uniques.each do |uniq|
if value = attributes[uniq]
index = model.indices[uniq]
records = model.bucket.get_index(index.riak_name, value)
unless records.empty? || records == [self.id]
raise Ork::UniqueIndexViolation, "#{uniq} is not unique"
end
end
end
end | [
"def",
"__check_unique_indices",
"model",
".",
"uniques",
".",
"each",
"do",
"|",
"uniq",
"|",
"if",
"value",
"=",
"attributes",
"[",
"uniq",
"]",
"index",
"=",
"model",
".",
"indices",
"[",
"uniq",
"]",
"records",
"=",
"model",
".",
"bucket",
".",
"get_index",
"(",
"index",
".",
"riak_name",
",",
"value",
")",
"unless",
"records",
".",
"empty?",
"||",
"records",
"==",
"[",
"self",
".",
"id",
"]",
"raise",
"Ork",
"::",
"UniqueIndexViolation",
",",
"\"#{uniq} is not unique\"",
"end",
"end",
"end",
"end"
] | Look up into Riak for repeated values on unique attributes | [
"Look",
"up",
"into",
"Riak",
"for",
"repeated",
"values",
"on",
"unique",
"attributes"
] | 83b2deaef0e790d90f98c031f254b5f438b19edf | https://github.com/emancu/ork/blob/83b2deaef0e790d90f98c031f254b5f438b19edf/lib/ork/model/document.rb#L139-L149 | train |
roja/words | lib/wordnet_connectors/tokyo_wordnet_connection.rb | Words.TokyoWordnetConnection.open! | def open!
unless connected?
if @data_path.exist?
@connection = Rufus::Tokyo::Table.new(@data_path.to_s, :mode => 'r')
@connected = true
else
@connected = false
raise BadWordnetDataset, "Failed to locate the tokyo words dataset at #{@data_path}. Please insure you have created it using the words gems provided 'build_wordnet' command."
end
end
return nil
end | ruby | def open!
unless connected?
if @data_path.exist?
@connection = Rufus::Tokyo::Table.new(@data_path.to_s, :mode => 'r')
@connected = true
else
@connected = false
raise BadWordnetDataset, "Failed to locate the tokyo words dataset at #{@data_path}. Please insure you have created it using the words gems provided 'build_wordnet' command."
end
end
return nil
end | [
"def",
"open!",
"unless",
"connected?",
"if",
"@data_path",
".",
"exist?",
"@connection",
"=",
"Rufus",
"::",
"Tokyo",
"::",
"Table",
".",
"new",
"(",
"@data_path",
".",
"to_s",
",",
":mode",
"=>",
"'r'",
")",
"@connected",
"=",
"true",
"else",
"@connected",
"=",
"false",
"raise",
"BadWordnetDataset",
",",
"\"Failed to locate the tokyo words dataset at #{@data_path}. Please insure you have created it using the words gems provided 'build_wordnet' command.\"",
"end",
"end",
"return",
"nil",
"end"
] | Constructs a new tokyo ruby connector for use with the words wordnet class.
@param [Pathname] data_path Specifies the directory within which constructed datasets can be found (tokyo index, evocations etc...)
@param [Pathname] wordnet_path Specifies the directory within which the wordnet dictionary can be found.
@return [PureWordnetConnection] A new wordnet connection.
@raise [BadWordnetConnector] If an invalid connector type is provided.
Causes the connection specified within the wordnet object to be reopened if currently closed.
@raise [BadWordnetConnector] If an invalid connector type is provided. | [
"Constructs",
"a",
"new",
"tokyo",
"ruby",
"connector",
"for",
"use",
"with",
"the",
"words",
"wordnet",
"class",
"."
] | 4d6302e7218533fcc2afb4cd993686dd56fe2cde | https://github.com/roja/words/blob/4d6302e7218533fcc2afb4cd993686dd56fe2cde/lib/wordnet_connectors/tokyo_wordnet_connection.rb#L57-L70 | train |
locks/halibut | lib/halibut/core/resource.rb | Halibut::Core.Resource.set_property | def set_property(property, value)
if property == '_links' || property == '_embedded'
raise ArgumentError, "Argument #{property} is a reserved property"
end
tap { @properties[property] = value }
end | ruby | def set_property(property, value)
if property == '_links' || property == '_embedded'
raise ArgumentError, "Argument #{property} is a reserved property"
end
tap { @properties[property] = value }
end | [
"def",
"set_property",
"(",
"property",
",",
"value",
")",
"if",
"property",
"==",
"'_links'",
"||",
"property",
"==",
"'_embedded'",
"raise",
"ArgumentError",
",",
"\"Argument #{property} is a reserved property\"",
"end",
"tap",
"{",
"@properties",
"[",
"property",
"]",
"=",
"value",
"}",
"end"
] | Sets a property in the resource.
@example
resource = Halibut::Core::Resource.new
resource.set_property :name, 'FooBar'
resource.property :name
# => "FooBar"
@param [Object] property the key
@param [Object] value the value | [
"Sets",
"a",
"property",
"in",
"the",
"resource",
"."
] | b8da6aa0796c9db317b9cd3d377915499a52383c | https://github.com/locks/halibut/blob/b8da6aa0796c9db317b9cd3d377915499a52383c/lib/halibut/core/resource.rb#L84-L90 | train |
locks/halibut | lib/halibut/core/resource.rb | Halibut::Core.Resource.add_link | def add_link(relation, href, opts={})
@links.add relation, Link.new(href, opts)
end | ruby | def add_link(relation, href, opts={})
@links.add relation, Link.new(href, opts)
end | [
"def",
"add_link",
"(",
"relation",
",",
"href",
",",
"opts",
"=",
"{",
"}",
")",
"@links",
".",
"add",
"relation",
",",
"Link",
".",
"new",
"(",
"href",
",",
"opts",
")",
"end"
] | Adds link to relation.
@example
resource = Halibut::Core::Resource.new
resource.add_link 'next', '/resource/2', name: 'Foo'
link = resource.links['next'].first
link.href
# => "/resource/2"
link.name
# => "Foo"
@param [String] relation relation
@param [String] href href
@param [Hash] opts options: templated, type, name, profile,
title, hreflang | [
"Adds",
"link",
"to",
"relation",
"."
] | b8da6aa0796c9db317b9cd3d377915499a52383c | https://github.com/locks/halibut/blob/b8da6aa0796c9db317b9cd3d377915499a52383c/lib/halibut/core/resource.rb#L132-L134 | train |
locks/halibut | lib/halibut/core/resource.rb | Halibut::Core.Resource.to_hash | def to_hash
{}.merge(@properties).tap do |h|
h['_links'] = {}.merge @links unless @links.empty?
combined_embedded = {}
combined_embedded.merge! @embedded unless @embedded.empty?
combined_embedded.merge! @embedded_arrays unless @embedded_arrays.empty?
h['_embedded'] = combined_embedded unless combined_embedded.empty?
end
end | ruby | def to_hash
{}.merge(@properties).tap do |h|
h['_links'] = {}.merge @links unless @links.empty?
combined_embedded = {}
combined_embedded.merge! @embedded unless @embedded.empty?
combined_embedded.merge! @embedded_arrays unless @embedded_arrays.empty?
h['_embedded'] = combined_embedded unless combined_embedded.empty?
end
end | [
"def",
"to_hash",
"{",
"}",
".",
"merge",
"(",
"@properties",
")",
".",
"tap",
"do",
"|",
"h",
"|",
"h",
"[",
"'_links'",
"]",
"=",
"{",
"}",
".",
"merge",
"@links",
"unless",
"@links",
".",
"empty?",
"combined_embedded",
"=",
"{",
"}",
"combined_embedded",
".",
"merge!",
"@embedded",
"unless",
"@embedded",
".",
"empty?",
"combined_embedded",
".",
"merge!",
"@embedded_arrays",
"unless",
"@embedded_arrays",
".",
"empty?",
"h",
"[",
"'_embedded'",
"]",
"=",
"combined_embedded",
"unless",
"combined_embedded",
".",
"empty?",
"end",
"end"
] | Hash representation of the resource.
Will ommit links and embedded keys if they're empty
@return [Hash] hash representation of the resource | [
"Hash",
"representation",
"of",
"the",
"resource",
".",
"Will",
"ommit",
"links",
"and",
"embedded",
"keys",
"if",
"they",
"re",
"empty"
] | b8da6aa0796c9db317b9cd3d377915499a52383c | https://github.com/locks/halibut/blob/b8da6aa0796c9db317b9cd3d377915499a52383c/lib/halibut/core/resource.rb#L161-L170 | train |
ombulabs/bitpagos | lib/bitpagos/client.rb | Bitpagos.Client.get_transaction_type_from_symbol | def get_transaction_type_from_symbol(transaction_type)
begin
target_type = transaction_type.to_s.upcase
return if target_type.empty?
self.class.const_get(target_type)
rescue NameError => error
raise Bitpagos::Errors::InvalidTransactionType.new(error.message)
end
end | ruby | def get_transaction_type_from_symbol(transaction_type)
begin
target_type = transaction_type.to_s.upcase
return if target_type.empty?
self.class.const_get(target_type)
rescue NameError => error
raise Bitpagos::Errors::InvalidTransactionType.new(error.message)
end
end | [
"def",
"get_transaction_type_from_symbol",
"(",
"transaction_type",
")",
"begin",
"target_type",
"=",
"transaction_type",
".",
"to_s",
".",
"upcase",
"return",
"if",
"target_type",
".",
"empty?",
"self",
".",
"class",
".",
"const_get",
"(",
"target_type",
")",
"rescue",
"NameError",
"=>",
"error",
"raise",
"Bitpagos",
"::",
"Errors",
"::",
"InvalidTransactionType",
".",
"new",
"(",
"error",
".",
"message",
")",
"end",
"end"
] | Takes a symbol and returns the proper transaction type.
@param [Symbol] Can be :pending, :waiting, :completed or :partially_paid
@return [String,nil] Returns the corresponding "PE", "WA", "CO" or "PP" | [
"Takes",
"a",
"symbol",
"and",
"returns",
"the",
"proper",
"transaction",
"type",
"."
] | 007fca57437f1e3fc3eff72f3d84f56f49cf64fc | https://github.com/ombulabs/bitpagos/blob/007fca57437f1e3fc3eff72f3d84f56f49cf64fc/lib/bitpagos/client.rb#L69-L77 | train |
ombulabs/bitpagos | lib/bitpagos/client.rb | Bitpagos.Client.retrieve_transactions | def retrieve_transactions(query = nil, transaction_id = nil)
headers.merge!(params: query) if query
url = "#{API_BASE}/transaction/#{transaction_id}"
begin
response = RestClient.get(url, headers)
JSON.parse(response)
rescue RestClient::Unauthorized => error
raise Bitpagos::Errors::Unauthorized.new(error.message)
end
end | ruby | def retrieve_transactions(query = nil, transaction_id = nil)
headers.merge!(params: query) if query
url = "#{API_BASE}/transaction/#{transaction_id}"
begin
response = RestClient.get(url, headers)
JSON.parse(response)
rescue RestClient::Unauthorized => error
raise Bitpagos::Errors::Unauthorized.new(error.message)
end
end | [
"def",
"retrieve_transactions",
"(",
"query",
"=",
"nil",
",",
"transaction_id",
"=",
"nil",
")",
"headers",
".",
"merge!",
"(",
"params",
":",
"query",
")",
"if",
"query",
"url",
"=",
"\"#{API_BASE}/transaction/#{transaction_id}\"",
"begin",
"response",
"=",
"RestClient",
".",
"get",
"(",
"url",
",",
"headers",
")",
"JSON",
".",
"parse",
"(",
"response",
")",
"rescue",
"RestClient",
"::",
"Unauthorized",
"=>",
"error",
"raise",
"Bitpagos",
"::",
"Errors",
"::",
"Unauthorized",
".",
"new",
"(",
"error",
".",
"message",
")",
"end",
"end"
] | Hits the Bitpagos transaction API, returns a hash with results
@param [String] State (Pending, Waiting, Completed, Partially Paid)
@param [String] Transaction ID
@return [Hash] | [
"Hits",
"the",
"Bitpagos",
"transaction",
"API",
"returns",
"a",
"hash",
"with",
"results"
] | 007fca57437f1e3fc3eff72f3d84f56f49cf64fc | https://github.com/ombulabs/bitpagos/blob/007fca57437f1e3fc3eff72f3d84f56f49cf64fc/lib/bitpagos/client.rb#L84-L93 | train |
nwops/retrospec | lib/retrospec/plugins.rb | Retrospec.Plugins.discover_plugin | def discover_plugin(module_path)
plugin = plugin_classes.find {|c| c.send(:valid_module_dir?, module_path) }
raise NoSuitablePluginFoundException unless plugin
plugin
end | ruby | def discover_plugin(module_path)
plugin = plugin_classes.find {|c| c.send(:valid_module_dir?, module_path) }
raise NoSuitablePluginFoundException unless plugin
plugin
end | [
"def",
"discover_plugin",
"(",
"module_path",
")",
"plugin",
"=",
"plugin_classes",
".",
"find",
"{",
"|",
"c",
"|",
"c",
".",
"send",
"(",
":valid_module_dir?",
",",
"module_path",
")",
"}",
"raise",
"NoSuitablePluginFoundException",
"unless",
"plugin",
"plugin",
"end"
] | returns the first plugin class that supports this module directory
not sure what to do when we find multiple plugins
would need additional criteria | [
"returns",
"the",
"first",
"plugin",
"class",
"that",
"supports",
"this",
"module",
"directory",
"not",
"sure",
"what",
"to",
"do",
"when",
"we",
"find",
"multiple",
"plugins",
"would",
"need",
"additional",
"criteria"
] | e61a8e8b86384c64a3ce9340d1342fa416740522 | https://github.com/nwops/retrospec/blob/e61a8e8b86384c64a3ce9340d1342fa416740522/lib/retrospec/plugins.rb#L38-L42 | train |
wilson/revenant | lib/revenant/task.rb | Revenant.Task.run | def run(&block)
unless @work = block
raise ArgumentError, "Usage: run { while_we_have_the_lock }"
end
@shutdown = false
@restart = false
install_plugins
startup # typically daemonizes the process, can have various implementations
on_load.call(self) if on_load
run_loop(&@work)
on_exit.call(self) if on_exit
shutdown
end | ruby | def run(&block)
unless @work = block
raise ArgumentError, "Usage: run { while_we_have_the_lock }"
end
@shutdown = false
@restart = false
install_plugins
startup # typically daemonizes the process, can have various implementations
on_load.call(self) if on_load
run_loop(&@work)
on_exit.call(self) if on_exit
shutdown
end | [
"def",
"run",
"(",
"&",
"block",
")",
"unless",
"@work",
"=",
"block",
"raise",
"ArgumentError",
",",
"\"Usage: run { while_we_have_the_lock }\"",
"end",
"@shutdown",
"=",
"false",
"@restart",
"=",
"false",
"install_plugins",
"startup",
"on_load",
".",
"call",
"(",
"self",
")",
"if",
"on_load",
"run_loop",
"(",
"&",
"@work",
")",
"on_exit",
".",
"call",
"(",
"self",
")",
"if",
"on_exit",
"shutdown",
"end"
] | Takes actual block of code that is to be guarded by
the lock. The +run_loop+ method does the actual work.
If 'daemon?' is true, your code (including +on_load+)
will execute after a fork.
Make sure you don't open files and sockets in the exiting
parent process by mistake. Open them in code that is called
via +on_load+. | [
"Takes",
"actual",
"block",
"of",
"code",
"that",
"is",
"to",
"be",
"guarded",
"by",
"the",
"lock",
".",
"The",
"+",
"run_loop",
"+",
"method",
"does",
"the",
"actual",
"work",
"."
] | 80fe65742de54ce0c5a8e6c56cea7003fe286746 | https://github.com/wilson/revenant/blob/80fe65742de54ce0c5a8e6c56cea7003fe286746/lib/revenant/task.rb#L48-L60 | train |
cloudspace/ruby-fleetctl | lib/fleet/cluster.rb | Fleet.Cluster.build_from | def build_from(*ip_addrs)
ip_addrs = [*ip_addrs].flatten.compact
begin
Fleetctl.logger.info 'building from hosts: ' + ip_addrs.inspect
built_from = ip_addrs.detect { |ip_addr| fetch_machines(ip_addr) }
Fleetctl.logger.info 'built successfully from host: ' + built_from.inspect if built_from
built_from
rescue => e
Fleetctl.logger.error 'ERROR building from hosts: ' + ip_addrs.inspect
Fleetctl.logger.error e.message
Fleetctl.logger.error e.backtrace.join("\n")
nil
end
end | ruby | def build_from(*ip_addrs)
ip_addrs = [*ip_addrs].flatten.compact
begin
Fleetctl.logger.info 'building from hosts: ' + ip_addrs.inspect
built_from = ip_addrs.detect { |ip_addr| fetch_machines(ip_addr) }
Fleetctl.logger.info 'built successfully from host: ' + built_from.inspect if built_from
built_from
rescue => e
Fleetctl.logger.error 'ERROR building from hosts: ' + ip_addrs.inspect
Fleetctl.logger.error e.message
Fleetctl.logger.error e.backtrace.join("\n")
nil
end
end | [
"def",
"build_from",
"(",
"*",
"ip_addrs",
")",
"ip_addrs",
"=",
"[",
"*",
"ip_addrs",
"]",
".",
"flatten",
".",
"compact",
"begin",
"Fleetctl",
".",
"logger",
".",
"info",
"'building from hosts: '",
"+",
"ip_addrs",
".",
"inspect",
"built_from",
"=",
"ip_addrs",
".",
"detect",
"{",
"|",
"ip_addr",
"|",
"fetch_machines",
"(",
"ip_addr",
")",
"}",
"Fleetctl",
".",
"logger",
".",
"info",
"'built successfully from host: '",
"+",
"built_from",
".",
"inspect",
"if",
"built_from",
"built_from",
"rescue",
"=>",
"e",
"Fleetctl",
".",
"logger",
".",
"error",
"'ERROR building from hosts: '",
"+",
"ip_addrs",
".",
"inspect",
"Fleetctl",
".",
"logger",
".",
"error",
"e",
".",
"message",
"Fleetctl",
".",
"logger",
".",
"error",
"e",
".",
"backtrace",
".",
"join",
"(",
"\"\\n\"",
")",
"nil",
"end",
"end"
] | attempts to rebuild the cluster from any of the hosts passed as arguments
returns the first ip that worked, else nil | [
"attempts",
"to",
"rebuild",
"the",
"cluster",
"from",
"any",
"of",
"the",
"hosts",
"passed",
"as",
"arguments",
"returns",
"the",
"first",
"ip",
"that",
"worked",
"else",
"nil"
] | 23c9a71f733d43275fbfaf35c568d4b284f715ab | https://github.com/cloudspace/ruby-fleetctl/blob/23c9a71f733d43275fbfaf35c568d4b284f715ab/lib/fleet/cluster.rb#L25-L38 | train |
cloudspace/ruby-fleetctl | lib/fleet/cluster.rb | Fleet.Cluster.fetch_machines | def fetch_machines(host)
Fleetctl.logger.info 'Fetching machines from host: '+host.inspect
clear
Fleetctl::Command.new('list-machines', '-l') do |runner|
runner.run(host: host)
new_machines = parse_machines(runner.output)
if runner.exit_code == 0
return true
else
return false
end
end
end | ruby | def fetch_machines(host)
Fleetctl.logger.info 'Fetching machines from host: '+host.inspect
clear
Fleetctl::Command.new('list-machines', '-l') do |runner|
runner.run(host: host)
new_machines = parse_machines(runner.output)
if runner.exit_code == 0
return true
else
return false
end
end
end | [
"def",
"fetch_machines",
"(",
"host",
")",
"Fleetctl",
".",
"logger",
".",
"info",
"'Fetching machines from host: '",
"+",
"host",
".",
"inspect",
"clear",
"Fleetctl",
"::",
"Command",
".",
"new",
"(",
"'list-machines'",
",",
"'-l'",
")",
"do",
"|",
"runner",
"|",
"runner",
".",
"run",
"(",
"host",
":",
"host",
")",
"new_machines",
"=",
"parse_machines",
"(",
"runner",
".",
"output",
")",
"if",
"runner",
".",
"exit_code",
"==",
"0",
"return",
"true",
"else",
"return",
"false",
"end",
"end",
"end"
] | attempts a list-machines action on the given host.
returns true if successful, else false | [
"attempts",
"a",
"list",
"-",
"machines",
"action",
"on",
"the",
"given",
"host",
".",
"returns",
"true",
"if",
"successful",
"else",
"false"
] | 23c9a71f733d43275fbfaf35c568d4b284f715ab | https://github.com/cloudspace/ruby-fleetctl/blob/23c9a71f733d43275fbfaf35c568d4b284f715ab/lib/fleet/cluster.rb#L42-L54 | train |
cloudspace/ruby-fleetctl | lib/fleet/cluster.rb | Fleet.Cluster.discover! | def discover!
known_hosts = [Fleetctl.options.fleet_host] | fleet_hosts.to_a
clear
success_host = build_from(known_hosts) || build_from(Fleet::Discovery.hosts)
if success_host
Fleetctl.logger.info 'Successfully recovered from host: ' + success_host.inspect
else
Fleetctl.logger.info 'Unable to recover!'
end
end | ruby | def discover!
known_hosts = [Fleetctl.options.fleet_host] | fleet_hosts.to_a
clear
success_host = build_from(known_hosts) || build_from(Fleet::Discovery.hosts)
if success_host
Fleetctl.logger.info 'Successfully recovered from host: ' + success_host.inspect
else
Fleetctl.logger.info 'Unable to recover!'
end
end | [
"def",
"discover!",
"known_hosts",
"=",
"[",
"Fleetctl",
".",
"options",
".",
"fleet_host",
"]",
"|",
"fleet_hosts",
".",
"to_a",
"clear",
"success_host",
"=",
"build_from",
"(",
"known_hosts",
")",
"||",
"build_from",
"(",
"Fleet",
"::",
"Discovery",
".",
"hosts",
")",
"if",
"success_host",
"Fleetctl",
".",
"logger",
".",
"info",
"'Successfully recovered from host: '",
"+",
"success_host",
".",
"inspect",
"else",
"Fleetctl",
".",
"logger",
".",
"info",
"'Unable to recover!'",
"end",
"end"
] | attempts to rebuild the cluster by the specified fleet host, then hosts that it
has built previously, and finally by using the discovery url | [
"attempts",
"to",
"rebuild",
"the",
"cluster",
"by",
"the",
"specified",
"fleet",
"host",
"then",
"hosts",
"that",
"it",
"has",
"built",
"previously",
"and",
"finally",
"by",
"using",
"the",
"discovery",
"url"
] | 23c9a71f733d43275fbfaf35c568d4b284f715ab | https://github.com/cloudspace/ruby-fleetctl/blob/23c9a71f733d43275fbfaf35c568d4b284f715ab/lib/fleet/cluster.rb#L67-L76 | train |
jarhart/rattler | lib/rattler/parsers/token.rb | Rattler::Parsers.Token.parse | def parse(scanner, rules, scope = ParserScope.empty)
p = scanner.pos
child.parse(scanner, rules, scope) && scanner.string[p...(scanner.pos)]
end | ruby | def parse(scanner, rules, scope = ParserScope.empty)
p = scanner.pos
child.parse(scanner, rules, scope) && scanner.string[p...(scanner.pos)]
end | [
"def",
"parse",
"(",
"scanner",
",",
"rules",
",",
"scope",
"=",
"ParserScope",
".",
"empty",
")",
"p",
"=",
"scanner",
".",
"pos",
"child",
".",
"parse",
"(",
"scanner",
",",
"rules",
",",
"scope",
")",
"&&",
"scanner",
".",
"string",
"[",
"p",
"...",
"(",
"scanner",
".",
"pos",
")",
"]",
"end"
] | If the decorated parser matches return the entire matched string,
otherwise return a false value.
@param (see Match#parse)
@return (see Match#parse) | [
"If",
"the",
"decorated",
"parser",
"matches",
"return",
"the",
"entire",
"matched",
"string",
"otherwise",
"return",
"a",
"false",
"value",
"."
] | 8b4efde2a05e9e790955bb635d4a1a9615893719 | https://github.com/jarhart/rattler/blob/8b4efde2a05e9e790955bb635d4a1a9615893719/lib/rattler/parsers/token.rb#L15-L18 | train |
postmodern/rprogram | lib/rprogram/option_list.rb | RProgram.OptionList.method_missing | def method_missing(sym,*args,&block)
name = sym.to_s
unless block
if (name =~ /=$/ && args.length == 1)
return self[name.chop.to_sym] = args.first
elsif args.empty?
return self[sym]
end
end
return super(sym,*args,&block)
end | ruby | def method_missing(sym,*args,&block)
name = sym.to_s
unless block
if (name =~ /=$/ && args.length == 1)
return self[name.chop.to_sym] = args.first
elsif args.empty?
return self[sym]
end
end
return super(sym,*args,&block)
end | [
"def",
"method_missing",
"(",
"sym",
",",
"*",
"args",
",",
"&",
"block",
")",
"name",
"=",
"sym",
".",
"to_s",
"unless",
"block",
"if",
"(",
"name",
"=~",
"/",
"/",
"&&",
"args",
".",
"length",
"==",
"1",
")",
"return",
"self",
"[",
"name",
".",
"chop",
".",
"to_sym",
"]",
"=",
"args",
".",
"first",
"elsif",
"args",
".",
"empty?",
"return",
"self",
"[",
"sym",
"]",
"end",
"end",
"return",
"super",
"(",
"sym",
",",
"*",
"args",
",",
"&",
"block",
")",
"end"
] | Provides transparent access to the options within the option list.
@example
opt_list = OptionList.new(:name => 'test')
opt_list.name
# => "test" | [
"Provides",
"transparent",
"access",
"to",
"the",
"options",
"within",
"the",
"option",
"list",
"."
] | 94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be | https://github.com/postmodern/rprogram/blob/94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be/lib/rprogram/option_list.rb#L24-L36 | train |
alihuber/http_archive | lib/http_archive/archive.rb | HttpArchive.Archive.get_total_data | def get_total_data
size = calc_total_size.to_s
load_time = (@pages.first.on_load / 1000.0).to_s
[@pages.first.title, @entries.size.to_s, size, load_time]
end | ruby | def get_total_data
size = calc_total_size.to_s
load_time = (@pages.first.on_load / 1000.0).to_s
[@pages.first.title, @entries.size.to_s, size, load_time]
end | [
"def",
"get_total_data",
"size",
"=",
"calc_total_size",
".",
"to_s",
"load_time",
"=",
"(",
"@pages",
".",
"first",
".",
"on_load",
"/",
"1000.0",
")",
".",
"to_s",
"[",
"@pages",
".",
"first",
".",
"title",
",",
"@entries",
".",
"size",
".",
"to_s",
",",
"size",
",",
"load_time",
"]",
"end"
] | Gets the common data for a page.
Convenience method that can be used for bulk reading of page data.
@return [Array<page_title, ressource_count, total_download_size, overall_load_time>] An array with page data
@example Example of returned Array
["Software is hard", "26", "0.36", "6.745"] | [
"Gets",
"the",
"common",
"data",
"for",
"a",
"page",
".",
"Convenience",
"method",
"that",
"can",
"be",
"used",
"for",
"bulk",
"reading",
"of",
"page",
"data",
"."
] | 3fc1e1f4e206ea6b4a68b75199bdda662a4e153a | https://github.com/alihuber/http_archive/blob/3fc1e1f4e206ea6b4a68b75199bdda662a4e153a/lib/http_archive/archive.rb#L70-L75 | train |
alihuber/http_archive | lib/http_archive/archive.rb | HttpArchive.Archive.get_row_data | def get_row_data
rows = []
@entries.each do |entry|
method = entry.request.http_method
# get part after .com/ if any
url = entry.request.url
if url.end_with?("/")
ressource = entry.request.url
else
r = url.rindex("/")
ressource = url[r..-1]
end
# first 30 characters of the ressource name
ressource = ressource[0, 30]
status = entry.response.status.to_s
code = entry.response.status_text
size = (entry.response.content['size'] / 1000.0).round(2).to_s
duration = (entry.time / 1000.0).to_s
rows << [method, ressource, status, code, size, duration]
end
rows
end | ruby | def get_row_data
rows = []
@entries.each do |entry|
method = entry.request.http_method
# get part after .com/ if any
url = entry.request.url
if url.end_with?("/")
ressource = entry.request.url
else
r = url.rindex("/")
ressource = url[r..-1]
end
# first 30 characters of the ressource name
ressource = ressource[0, 30]
status = entry.response.status.to_s
code = entry.response.status_text
size = (entry.response.content['size'] / 1000.0).round(2).to_s
duration = (entry.time / 1000.0).to_s
rows << [method, ressource, status, code, size, duration]
end
rows
end | [
"def",
"get_row_data",
"rows",
"=",
"[",
"]",
"@entries",
".",
"each",
"do",
"|",
"entry",
"|",
"method",
"=",
"entry",
".",
"request",
".",
"http_method",
"url",
"=",
"entry",
".",
"request",
".",
"url",
"if",
"url",
".",
"end_with?",
"(",
"\"/\"",
")",
"ressource",
"=",
"entry",
".",
"request",
".",
"url",
"else",
"r",
"=",
"url",
".",
"rindex",
"(",
"\"/\"",
")",
"ressource",
"=",
"url",
"[",
"r",
"..",
"-",
"1",
"]",
"end",
"ressource",
"=",
"ressource",
"[",
"0",
",",
"30",
"]",
"status",
"=",
"entry",
".",
"response",
".",
"status",
".",
"to_s",
"code",
"=",
"entry",
".",
"response",
".",
"status_text",
"size",
"=",
"(",
"entry",
".",
"response",
".",
"content",
"[",
"'size'",
"]",
"/",
"1000.0",
")",
".",
"round",
"(",
"2",
")",
".",
"to_s",
"duration",
"=",
"(",
"entry",
".",
"time",
"/",
"1000.0",
")",
".",
"to_s",
"rows",
"<<",
"[",
"method",
",",
"ressource",
",",
"status",
",",
"code",
",",
"size",
",",
"duration",
"]",
"end",
"rows",
"end"
] | Gets the data for a row for all entries.
Convenience method that can be used for bulk reading of entry data.
@return [Array<Array<html_method, ressource_name, status_name, status_code, ressource_size, load_duration>>] An array with row data
@example Example of returned Array
[["GET", "/prototype.js?ver=1.6.1", "200", "OK", "139.85", "1.06"], ... ] | [
"Gets",
"the",
"data",
"for",
"a",
"row",
"for",
"all",
"entries",
".",
"Convenience",
"method",
"that",
"can",
"be",
"used",
"for",
"bulk",
"reading",
"of",
"entry",
"data",
"."
] | 3fc1e1f4e206ea6b4a68b75199bdda662a4e153a | https://github.com/alihuber/http_archive/blob/3fc1e1f4e206ea6b4a68b75199bdda662a4e153a/lib/http_archive/archive.rb#L83-L105 | train |
jemmyw/bisques | lib/bisques/aws_request.rb | Bisques.AwsRequest.make_request | def make_request
create_authorization
options = {}
options[:header] = authorization.headers.merge(
'Authorization' => authorization.authorization_header
)
options[:query] = query if query.any?
options[:body] = form_body if body
http_response = @httpclient.request(method, url, options)
@response = AwsResponse.new(self, http_response)
freeze
@response
end | ruby | def make_request
create_authorization
options = {}
options[:header] = authorization.headers.merge(
'Authorization' => authorization.authorization_header
)
options[:query] = query if query.any?
options[:body] = form_body if body
http_response = @httpclient.request(method, url, options)
@response = AwsResponse.new(self, http_response)
freeze
@response
end | [
"def",
"make_request",
"create_authorization",
"options",
"=",
"{",
"}",
"options",
"[",
":header",
"]",
"=",
"authorization",
".",
"headers",
".",
"merge",
"(",
"'Authorization'",
"=>",
"authorization",
".",
"authorization_header",
")",
"options",
"[",
":query",
"]",
"=",
"query",
"if",
"query",
".",
"any?",
"options",
"[",
":body",
"]",
"=",
"form_body",
"if",
"body",
"http_response",
"=",
"@httpclient",
".",
"request",
"(",
"method",
",",
"url",
",",
"options",
")",
"@response",
"=",
"AwsResponse",
".",
"new",
"(",
"self",
",",
"http_response",
")",
"freeze",
"@response",
"end"
] | Send the HTTP request and get a response. Returns an AwsResponse object.
The instance is frozen once this method is called and cannot be used
again. | [
"Send",
"the",
"HTTP",
"request",
"and",
"get",
"a",
"response",
".",
"Returns",
"an",
"AwsResponse",
"object",
".",
"The",
"instance",
"is",
"frozen",
"once",
"this",
"method",
"is",
"called",
"and",
"cannot",
"be",
"used",
"again",
"."
] | c48ab555f07664752bcbf9e8deb99bd75cbdc41b | https://github.com/jemmyw/bisques/blob/c48ab555f07664752bcbf9e8deb99bd75cbdc41b/lib/bisques/aws_request.rb#L77-L93 | train |
jemmyw/bisques | lib/bisques/aws_request.rb | Bisques.AwsRequest.form_body | def form_body
if body.is_a?(Hash)
body.map do |k,v|
[AwsRequest.aws_encode(k), AwsRequest.aws_encode(v)].join("=")
end.join("&")
else
body
end
end | ruby | def form_body
if body.is_a?(Hash)
body.map do |k,v|
[AwsRequest.aws_encode(k), AwsRequest.aws_encode(v)].join("=")
end.join("&")
else
body
end
end | [
"def",
"form_body",
"if",
"body",
".",
"is_a?",
"(",
"Hash",
")",
"body",
".",
"map",
"do",
"|",
"k",
",",
"v",
"|",
"[",
"AwsRequest",
".",
"aws_encode",
"(",
"k",
")",
",",
"AwsRequest",
".",
"aws_encode",
"(",
"v",
")",
"]",
".",
"join",
"(",
"\"=\"",
")",
"end",
".",
"join",
"(",
"\"&\"",
")",
"else",
"body",
"end",
"end"
] | Encode the form params if the body is given as a Hash. | [
"Encode",
"the",
"form",
"params",
"if",
"the",
"body",
"is",
"given",
"as",
"a",
"Hash",
"."
] | c48ab555f07664752bcbf9e8deb99bd75cbdc41b | https://github.com/jemmyw/bisques/blob/c48ab555f07664752bcbf9e8deb99bd75cbdc41b/lib/bisques/aws_request.rb#L98-L106 | train |
jemmyw/bisques | lib/bisques/aws_request.rb | Bisques.AwsRequest.create_authorization | def create_authorization
@authorization = AwsRequestAuthorization.new.tap do |authorization|
authorization.url = url
authorization.method = method
authorization.query = query
authorization.body = form_body
authorization.region = region
authorization.service = service
authorization.credentials = credentials
authorization.headers = headers
end
end | ruby | def create_authorization
@authorization = AwsRequestAuthorization.new.tap do |authorization|
authorization.url = url
authorization.method = method
authorization.query = query
authorization.body = form_body
authorization.region = region
authorization.service = service
authorization.credentials = credentials
authorization.headers = headers
end
end | [
"def",
"create_authorization",
"@authorization",
"=",
"AwsRequestAuthorization",
".",
"new",
".",
"tap",
"do",
"|",
"authorization",
"|",
"authorization",
".",
"url",
"=",
"url",
"authorization",
".",
"method",
"=",
"method",
"authorization",
".",
"query",
"=",
"query",
"authorization",
".",
"body",
"=",
"form_body",
"authorization",
".",
"region",
"=",
"region",
"authorization",
".",
"service",
"=",
"service",
"authorization",
".",
"credentials",
"=",
"credentials",
"authorization",
".",
"headers",
"=",
"headers",
"end",
"end"
] | Create the AwsRequestAuthorization object for the request. | [
"Create",
"the",
"AwsRequestAuthorization",
"object",
"for",
"the",
"request",
"."
] | c48ab555f07664752bcbf9e8deb99bd75cbdc41b | https://github.com/jemmyw/bisques/blob/c48ab555f07664752bcbf9e8deb99bd75cbdc41b/lib/bisques/aws_request.rb#L109-L120 | train |
jemmyw/bisques | lib/bisques/queue.rb | Bisques.Queue.retrieve | def retrieve(poll_time = 1)
response = client.receive_message(url, {"WaitTimeSeconds" => poll_time, "MaxNumberOfMessages" => 1})
raise QueueNotFound.new(self, "not found at #{url}") if response.http_response.status == 404
response.doc.xpath("//Message").map do |element|
attributes = Hash[*element.xpath("Attribute").map do |attr_element|
[attr_element.xpath("Name").text, attr_element.xpath("Value").text]
end.flatten]
Message.new(self, element.xpath("MessageId").text,
element.xpath("ReceiptHandle").text,
element.xpath("Body").text,
attributes
)
end.first
end | ruby | def retrieve(poll_time = 1)
response = client.receive_message(url, {"WaitTimeSeconds" => poll_time, "MaxNumberOfMessages" => 1})
raise QueueNotFound.new(self, "not found at #{url}") if response.http_response.status == 404
response.doc.xpath("//Message").map do |element|
attributes = Hash[*element.xpath("Attribute").map do |attr_element|
[attr_element.xpath("Name").text, attr_element.xpath("Value").text]
end.flatten]
Message.new(self, element.xpath("MessageId").text,
element.xpath("ReceiptHandle").text,
element.xpath("Body").text,
attributes
)
end.first
end | [
"def",
"retrieve",
"(",
"poll_time",
"=",
"1",
")",
"response",
"=",
"client",
".",
"receive_message",
"(",
"url",
",",
"{",
"\"WaitTimeSeconds\"",
"=>",
"poll_time",
",",
"\"MaxNumberOfMessages\"",
"=>",
"1",
"}",
")",
"raise",
"QueueNotFound",
".",
"new",
"(",
"self",
",",
"\"not found at #{url}\"",
")",
"if",
"response",
".",
"http_response",
".",
"status",
"==",
"404",
"response",
".",
"doc",
".",
"xpath",
"(",
"\"//Message\"",
")",
".",
"map",
"do",
"|",
"element",
"|",
"attributes",
"=",
"Hash",
"[",
"*",
"element",
".",
"xpath",
"(",
"\"Attribute\"",
")",
".",
"map",
"do",
"|",
"attr_element",
"|",
"[",
"attr_element",
".",
"xpath",
"(",
"\"Name\"",
")",
".",
"text",
",",
"attr_element",
".",
"xpath",
"(",
"\"Value\"",
")",
".",
"text",
"]",
"end",
".",
"flatten",
"]",
"Message",
".",
"new",
"(",
"self",
",",
"element",
".",
"xpath",
"(",
"\"MessageId\"",
")",
".",
"text",
",",
"element",
".",
"xpath",
"(",
"\"ReceiptHandle\"",
")",
".",
"text",
",",
"element",
".",
"xpath",
"(",
"\"Body\"",
")",
".",
"text",
",",
"attributes",
")",
"end",
".",
"first",
"end"
] | Retrieve a message from the queue. Returns nil if no message is waiting
in the given poll time. Otherwise it returns a Message.
@param [Fixnum] poll_time
@return [Message,nil]
@raise [AwsActionError] | [
"Retrieve",
"a",
"message",
"from",
"the",
"queue",
".",
"Returns",
"nil",
"if",
"no",
"message",
"is",
"waiting",
"in",
"the",
"given",
"poll",
"time",
".",
"Otherwise",
"it",
"returns",
"a",
"Message",
"."
] | c48ab555f07664752bcbf9e8deb99bd75cbdc41b | https://github.com/jemmyw/bisques/blob/c48ab555f07664752bcbf9e8deb99bd75cbdc41b/lib/bisques/queue.rb#L142-L157 | train |
NullVoxPopuli/authorizable | lib/authorizable/proxy.rb | Authorizable.Proxy.process_permission | def process_permission(permission, *args)
cached = value_from_cache(permission, *args)
if cached.nil?
evaluate_permission(permission, *args)
else
cached
end
end | ruby | def process_permission(permission, *args)
cached = value_from_cache(permission, *args)
if cached.nil?
evaluate_permission(permission, *args)
else
cached
end
end | [
"def",
"process_permission",
"(",
"permission",
",",
"*",
"args",
")",
"cached",
"=",
"value_from_cache",
"(",
"permission",
",",
"*",
"args",
")",
"if",
"cached",
".",
"nil?",
"evaluate_permission",
"(",
"permission",
",",
"*",
"args",
")",
"else",
"cached",
"end",
"end"
] | checks if the permission has already been calculated
otherwise the permission needs to be evaluated | [
"checks",
"if",
"the",
"permission",
"has",
"already",
"been",
"calculated",
"otherwise",
"the",
"permission",
"needs",
"to",
"be",
"evaluated"
] | 6a4ef94848861bb79b0ab1454264366aed4e2db8 | https://github.com/NullVoxPopuli/authorizable/blob/6a4ef94848861bb79b0ab1454264366aed4e2db8/lib/authorizable/proxy.rb#L55-L63 | train |
NullVoxPopuli/authorizable | lib/authorizable/proxy.rb | Authorizable.Proxy.value_from_cache | def value_from_cache(permission, *args)
# object; Event, Discount, etc
o = args[0]
role = get_role_of(o)
# don't perform the permission evaluation, if we have already computed it
cache.get_for_role(permission, role)
end | ruby | def value_from_cache(permission, *args)
# object; Event, Discount, etc
o = args[0]
role = get_role_of(o)
# don't perform the permission evaluation, if we have already computed it
cache.get_for_role(permission, role)
end | [
"def",
"value_from_cache",
"(",
"permission",
",",
"*",
"args",
")",
"o",
"=",
"args",
"[",
"0",
"]",
"role",
"=",
"get_role_of",
"(",
"o",
")",
"cache",
".",
"get_for_role",
"(",
"permission",
",",
"role",
")",
"end"
] | checks the cache if we have calculated this permission before
@return [Boolean|NilClass] | [
"checks",
"the",
"cache",
"if",
"we",
"have",
"calculated",
"this",
"permission",
"before"
] | 6a4ef94848861bb79b0ab1454264366aed4e2db8 | https://github.com/NullVoxPopuli/authorizable/blob/6a4ef94848861bb79b0ab1454264366aed4e2db8/lib/authorizable/proxy.rb#L67-L74 | train |
NullVoxPopuli/authorizable | lib/authorizable/proxy.rb | Authorizable.Proxy.evaluate_permission | def evaluate_permission(permission, *args)
# object; Event, Discount, etc
o = args[0]
# default to allow
result = true
role = get_role_of(o)
# evaluate procs
if (proc = PermissionUtilities.has_procs?(permission))
result &= proc.call(o, self)
end
# Here is where the addition of adding collaborations may reside
# finally, determine if the user (self) can do the requested action
result &= allowed_to_perform?(permission, role)
# so we don't need to do everything again
cache.set_for_role(
name: permission,
value: result,
role: role
)
result
end | ruby | def evaluate_permission(permission, *args)
# object; Event, Discount, etc
o = args[0]
# default to allow
result = true
role = get_role_of(o)
# evaluate procs
if (proc = PermissionUtilities.has_procs?(permission))
result &= proc.call(o, self)
end
# Here is where the addition of adding collaborations may reside
# finally, determine if the user (self) can do the requested action
result &= allowed_to_perform?(permission, role)
# so we don't need to do everything again
cache.set_for_role(
name: permission,
value: result,
role: role
)
result
end | [
"def",
"evaluate_permission",
"(",
"permission",
",",
"*",
"args",
")",
"o",
"=",
"args",
"[",
"0",
"]",
"result",
"=",
"true",
"role",
"=",
"get_role_of",
"(",
"o",
")",
"if",
"(",
"proc",
"=",
"PermissionUtilities",
".",
"has_procs?",
"(",
"permission",
")",
")",
"result",
"&=",
"proc",
".",
"call",
"(",
"o",
",",
"self",
")",
"end",
"result",
"&=",
"allowed_to_perform?",
"(",
"permission",
",",
"role",
")",
"cache",
".",
"set_for_role",
"(",
"name",
":",
"permission",
",",
"value",
":",
"result",
",",
"role",
":",
"role",
")",
"result",
"end"
] | performs a full evaluation of the permission
@return [Boolean] | [
"performs",
"a",
"full",
"evaluation",
"of",
"the",
"permission"
] | 6a4ef94848861bb79b0ab1454264366aed4e2db8 | https://github.com/NullVoxPopuli/authorizable/blob/6a4ef94848861bb79b0ab1454264366aed4e2db8/lib/authorizable/proxy.rb#L78-L104 | train |
NullVoxPopuli/authorizable | lib/authorizable/proxy.rb | Authorizable.Proxy.has_role_with | def has_role_with(object)
if object.respond_to?(:user_id)
if object.user_id == actor.id
return IS_OWNER
else
return IS_UNRELATED
end
end
# hopefully the object passed always responds to user_id
IS_UNRELATED
end | ruby | def has_role_with(object)
if object.respond_to?(:user_id)
if object.user_id == actor.id
return IS_OWNER
else
return IS_UNRELATED
end
end
# hopefully the object passed always responds to user_id
IS_UNRELATED
end | [
"def",
"has_role_with",
"(",
"object",
")",
"if",
"object",
".",
"respond_to?",
"(",
":user_id",
")",
"if",
"object",
".",
"user_id",
"==",
"actor",
".",
"id",
"return",
"IS_OWNER",
"else",
"return",
"IS_UNRELATED",
"end",
"end",
"IS_UNRELATED",
"end"
] | This method can also be overridden if one desires to have multiple types of
ownership, such as a collaborator-type relationship
@param [ActiveRecord::Base] object should be the object that is being tested
if the user can perform the action on
@return [Number] true if self owns object | [
"This",
"method",
"can",
"also",
"be",
"overridden",
"if",
"one",
"desires",
"to",
"have",
"multiple",
"types",
"of",
"ownership",
"such",
"as",
"a",
"collaborator",
"-",
"type",
"relationship"
] | 6a4ef94848861bb79b0ab1454264366aed4e2db8 | https://github.com/NullVoxPopuli/authorizable/blob/6a4ef94848861bb79b0ab1454264366aed4e2db8/lib/authorizable/proxy.rb#L144-L154 | train |
nanodeath/threadz | lib/threadz/thread_pool.rb | Threadz.ThreadPool.spawn_thread | def spawn_thread
Thread.new do
while true
x = @queue.shift
if x == Directive::SUICIDE_PILL
@worker_threads_count.decrement
Thread.current.terminate
end
Thread.pass
begin
x.job.call(x)
rescue StandardError => e
$stderr.puts "Threadz: Error in thread, but restarting with next job: #{e.inspect}\n#{e.backtrace.join("\n")}"
end
end
end
@worker_threads_count.increment
end | ruby | def spawn_thread
Thread.new do
while true
x = @queue.shift
if x == Directive::SUICIDE_PILL
@worker_threads_count.decrement
Thread.current.terminate
end
Thread.pass
begin
x.job.call(x)
rescue StandardError => e
$stderr.puts "Threadz: Error in thread, but restarting with next job: #{e.inspect}\n#{e.backtrace.join("\n")}"
end
end
end
@worker_threads_count.increment
end | [
"def",
"spawn_thread",
"Thread",
".",
"new",
"do",
"while",
"true",
"x",
"=",
"@queue",
".",
"shift",
"if",
"x",
"==",
"Directive",
"::",
"SUICIDE_PILL",
"@worker_threads_count",
".",
"decrement",
"Thread",
".",
"current",
".",
"terminate",
"end",
"Thread",
".",
"pass",
"begin",
"x",
".",
"job",
".",
"call",
"(",
"x",
")",
"rescue",
"StandardError",
"=>",
"e",
"$stderr",
".",
"puts",
"\"Threadz: Error in thread, but restarting with next job: #{e.inspect}\\n#{e.backtrace.join(\"\\n\")}\"",
"end",
"end",
"end",
"@worker_threads_count",
".",
"increment",
"end"
] | Spin up a new thread | [
"Spin",
"up",
"a",
"new",
"thread"
] | 5d96e052567076d5e86690f3d3703f1082330dd5 | https://github.com/nanodeath/threadz/blob/5d96e052567076d5e86690f3d3703f1082330dd5/lib/threadz/thread_pool.rb#L77-L94 | train |
nanodeath/threadz | lib/threadz/thread_pool.rb | Threadz.ThreadPool.spawn_watch_thread | def spawn_watch_thread
@watch_thread = Thread.new do
while true
# If there are idle threads and we're above minimum
if @queue.num_waiting > 0 && @worker_threads_count.value > @min_size # documented
@killscore += THREADS_IDLE_SCORE * @queue.num_waiting
# If there are no threads idle and we have room for more
elsif(@queue.num_waiting == 0 && @worker_threads_count.value < @max_size) # documented
@killscore -= THREADS_BUSY_SCORE * @queue.length
else
# Decay
if @killscore != 0 # documented
@killscore *= 0.9
end
if @killscore.abs < 1
@killscore = 0
end
end
if @killscore.abs >= @killthreshold
@killscore > 0 ? kill_thread : spawn_thread
@killscore = 0
end
Threadz.dputs "killscore: #{@killscore}. waiting: #{@queue.num_waiting}. threads length: #{@worker_threads_count.value}. min/max: [#{@min_size}, #{@max_size}]"
sleep 0.1
end
end
end | ruby | def spawn_watch_thread
@watch_thread = Thread.new do
while true
# If there are idle threads and we're above minimum
if @queue.num_waiting > 0 && @worker_threads_count.value > @min_size # documented
@killscore += THREADS_IDLE_SCORE * @queue.num_waiting
# If there are no threads idle and we have room for more
elsif(@queue.num_waiting == 0 && @worker_threads_count.value < @max_size) # documented
@killscore -= THREADS_BUSY_SCORE * @queue.length
else
# Decay
if @killscore != 0 # documented
@killscore *= 0.9
end
if @killscore.abs < 1
@killscore = 0
end
end
if @killscore.abs >= @killthreshold
@killscore > 0 ? kill_thread : spawn_thread
@killscore = 0
end
Threadz.dputs "killscore: #{@killscore}. waiting: #{@queue.num_waiting}. threads length: #{@worker_threads_count.value}. min/max: [#{@min_size}, #{@max_size}]"
sleep 0.1
end
end
end | [
"def",
"spawn_watch_thread",
"@watch_thread",
"=",
"Thread",
".",
"new",
"do",
"while",
"true",
"if",
"@queue",
".",
"num_waiting",
">",
"0",
"&&",
"@worker_threads_count",
".",
"value",
">",
"@min_size",
"@killscore",
"+=",
"THREADS_IDLE_SCORE",
"*",
"@queue",
".",
"num_waiting",
"elsif",
"(",
"@queue",
".",
"num_waiting",
"==",
"0",
"&&",
"@worker_threads_count",
".",
"value",
"<",
"@max_size",
")",
"@killscore",
"-=",
"THREADS_BUSY_SCORE",
"*",
"@queue",
".",
"length",
"else",
"if",
"@killscore",
"!=",
"0",
"@killscore",
"*=",
"0.9",
"end",
"if",
"@killscore",
".",
"abs",
"<",
"1",
"@killscore",
"=",
"0",
"end",
"end",
"if",
"@killscore",
".",
"abs",
">=",
"@killthreshold",
"@killscore",
">",
"0",
"?",
"kill_thread",
":",
"spawn_thread",
"@killscore",
"=",
"0",
"end",
"Threadz",
".",
"dputs",
"\"killscore: #{@killscore}. waiting: #{@queue.num_waiting}. threads length: #{@worker_threads_count.value}. min/max: [#{@min_size}, #{@max_size}]\"",
"sleep",
"0.1",
"end",
"end",
"end"
] | This thread watches over the pool and allocated and deallocates threads
as necessary | [
"This",
"thread",
"watches",
"over",
"the",
"pool",
"and",
"allocated",
"and",
"deallocates",
"threads",
"as",
"necessary"
] | 5d96e052567076d5e86690f3d3703f1082330dd5 | https://github.com/nanodeath/threadz/blob/5d96e052567076d5e86690f3d3703f1082330dd5/lib/threadz/thread_pool.rb#L106-L134 | train |
jduckett/duck_map | lib/duck_map/array_helper.rb | DuckMap.ArrayHelper.convert_to | def convert_to(values, type)
buffer = []
if values.kind_of?(Array)
values.each do |value|
begin
if type == :string
buffer.push(value.to_s)
elsif type == :symbol
buffer.push(value.to_sym)
end
rescue Exception => e
end
end
else
buffer = values
end
return buffer
end | ruby | def convert_to(values, type)
buffer = []
if values.kind_of?(Array)
values.each do |value|
begin
if type == :string
buffer.push(value.to_s)
elsif type == :symbol
buffer.push(value.to_sym)
end
rescue Exception => e
end
end
else
buffer = values
end
return buffer
end | [
"def",
"convert_to",
"(",
"values",
",",
"type",
")",
"buffer",
"=",
"[",
"]",
"if",
"values",
".",
"kind_of?",
"(",
"Array",
")",
"values",
".",
"each",
"do",
"|",
"value",
"|",
"begin",
"if",
"type",
"==",
":string",
"buffer",
".",
"push",
"(",
"value",
".",
"to_s",
")",
"elsif",
"type",
"==",
":symbol",
"buffer",
".",
"push",
"(",
"value",
".",
"to_sym",
")",
"end",
"rescue",
"Exception",
"=>",
"e",
"end",
"end",
"else",
"buffer",
"=",
"values",
"end",
"return",
"buffer",
"end"
] | Ensures all values in an Array are of a certain type. This is meant to be used internally
by DuckMap modules and classes.
values = ["new_book", "edit_book", "create_book", "destroy_book"]
values = obj.convert_to(values, :symbol)
puts values #=> [:new_book, :edit_book, :create_book, :destroy_book]
@param [Array] values The Array to inspect and convert.
@param [Symbol] type Valid values are :string and :symbol.
- :string converts all values to a String.
- :symbol converts all values to a Symbol.
@return [Array] | [
"Ensures",
"all",
"values",
"in",
"an",
"Array",
"are",
"of",
"a",
"certain",
"type",
".",
"This",
"is",
"meant",
"to",
"be",
"used",
"internally",
"by",
"DuckMap",
"modules",
"and",
"classes",
"."
] | c510acfa95e8ad4afb1501366058ae88a73704df | https://github.com/jduckett/duck_map/blob/c510acfa95e8ad4afb1501366058ae88a73704df/lib/duck_map/array_helper.rb#L19-L46 | train |
kwatch/baby_erubis | lib/baby_erubis.rb | BabyErubis.Template.from_file | def from_file(filename, encoding='utf-8')
mode = "rb:#{encoding}"
mode = "rb" if RUBY_VERSION < '1.9'
input = File.open(filename, mode) {|f| f.read() }
compile(parse(input), filename, 1)
return self
end | ruby | def from_file(filename, encoding='utf-8')
mode = "rb:#{encoding}"
mode = "rb" if RUBY_VERSION < '1.9'
input = File.open(filename, mode) {|f| f.read() }
compile(parse(input), filename, 1)
return self
end | [
"def",
"from_file",
"(",
"filename",
",",
"encoding",
"=",
"'utf-8'",
")",
"mode",
"=",
"\"rb:#{encoding}\"",
"mode",
"=",
"\"rb\"",
"if",
"RUBY_VERSION",
"<",
"'1.9'",
"input",
"=",
"File",
".",
"open",
"(",
"filename",
",",
"mode",
")",
"{",
"|",
"f",
"|",
"f",
".",
"read",
"(",
")",
"}",
"compile",
"(",
"parse",
"(",
"input",
")",
",",
"filename",
",",
"1",
")",
"return",
"self",
"end"
] | Ruby 2.1 feature | [
"Ruby",
"2",
".",
"1",
"feature"
] | 247e105643094942572bb20f517423122fcb5eab | https://github.com/kwatch/baby_erubis/blob/247e105643094942572bb20f517423122fcb5eab/lib/baby_erubis.rb#L46-L52 | train |
kostyantyn/school_friend | lib/school_friend/session.rb | SchoolFriend.Session.additional_params | def additional_params
@additional_params ||= if session_scope?
if oauth2_session?
{application_key: application_key}
else
{application_key: application_key, session_key: options[:session_key]}
end
else
{application_key: application_key}
end
end | ruby | def additional_params
@additional_params ||= if session_scope?
if oauth2_session?
{application_key: application_key}
else
{application_key: application_key, session_key: options[:session_key]}
end
else
{application_key: application_key}
end
end | [
"def",
"additional_params",
"@additional_params",
"||=",
"if",
"session_scope?",
"if",
"oauth2_session?",
"{",
"application_key",
":",
"application_key",
"}",
"else",
"{",
"application_key",
":",
"application_key",
",",
"session_key",
":",
"options",
"[",
":session_key",
"]",
"}",
"end",
"else",
"{",
"application_key",
":",
"application_key",
"}",
"end",
"end"
] | Returns additional params which are required for all requests.
Depends on request scope.
@return [Hash] | [
"Returns",
"additional",
"params",
"which",
"are",
"required",
"for",
"all",
"requests",
".",
"Depends",
"on",
"request",
"scope",
"."
] | 4cfd829bc6ba4b6a9148e6565e5328d5f2ba91e9 | https://github.com/kostyantyn/school_friend/blob/4cfd829bc6ba4b6a9148e6565e5328d5f2ba91e9/lib/school_friend/session.rb#L164-L174 | train |
kostyantyn/school_friend | lib/school_friend/session.rb | SchoolFriend.Session.api_call | def api_call(method, params = {}, force_session_call = false)
raise RequireSessionScopeError.new('This API call requires session scope') if force_session_call and application_scope?
uri = build_uri(method, params)
Net::HTTP.get_response(uri)
end | ruby | def api_call(method, params = {}, force_session_call = false)
raise RequireSessionScopeError.new('This API call requires session scope') if force_session_call and application_scope?
uri = build_uri(method, params)
Net::HTTP.get_response(uri)
end | [
"def",
"api_call",
"(",
"method",
",",
"params",
"=",
"{",
"}",
",",
"force_session_call",
"=",
"false",
")",
"raise",
"RequireSessionScopeError",
".",
"new",
"(",
"'This API call requires session scope'",
")",
"if",
"force_session_call",
"and",
"application_scope?",
"uri",
"=",
"build_uri",
"(",
"method",
",",
"params",
")",
"Net",
"::",
"HTTP",
".",
"get_response",
"(",
"uri",
")",
"end"
] | Performs API call to Odnoklassniki
@example Performs API call in current scope
school_friend = SchoolFriend::Session.new
school_friend.api_call('widget.getWidgets', wids: 'mobile-header,mobile-footer') # Net::HTTPResponse
@example Force performs API call in session scope
school_friend = SchoolFriend::Session.new
school_friend.api_call('widget.getWidgets', {wids: 'mobile-header,mobile-footer'}, true) # SchoolFriend::Session::RequireSessionScopeError
@param [String] method API method
@param [Hash] params params which should be sent to portal
@param [FalseClass, TrueClass] force_session_call says if this call should be performed in session scope
@return [Net::HTTPResponse] | [
"Performs",
"API",
"call",
"to",
"Odnoklassniki"
] | 4cfd829bc6ba4b6a9148e6565e5328d5f2ba91e9 | https://github.com/kostyantyn/school_friend/blob/4cfd829bc6ba4b6a9148e6565e5328d5f2ba91e9/lib/school_friend/session.rb#L191-L196 | train |
kostyantyn/school_friend | lib/school_friend/session.rb | SchoolFriend.Session.build_uri | def build_uri(method, params = {})
uri = URI(api_server)
uri.path = '/api/' + method.sub('.', '/')
uri.query = URI.encode_www_form(sign(params))
SchoolFriend.logger.debug "API Request: #{uri}"
uri
end | ruby | def build_uri(method, params = {})
uri = URI(api_server)
uri.path = '/api/' + method.sub('.', '/')
uri.query = URI.encode_www_form(sign(params))
SchoolFriend.logger.debug "API Request: #{uri}"
uri
end | [
"def",
"build_uri",
"(",
"method",
",",
"params",
"=",
"{",
"}",
")",
"uri",
"=",
"URI",
"(",
"api_server",
")",
"uri",
".",
"path",
"=",
"'/api/'",
"+",
"method",
".",
"sub",
"(",
"'.'",
",",
"'/'",
")",
"uri",
".",
"query",
"=",
"URI",
".",
"encode_www_form",
"(",
"sign",
"(",
"params",
")",
")",
"SchoolFriend",
".",
"logger",
".",
"debug",
"\"API Request: #{uri}\"",
"uri",
"end"
] | Builds URI object
@param [String] method request method
@param [Hash] params request params
@return [URI::HTTP] | [
"Builds",
"URI",
"object"
] | 4cfd829bc6ba4b6a9148e6565e5328d5f2ba91e9 | https://github.com/kostyantyn/school_friend/blob/4cfd829bc6ba4b6a9148e6565e5328d5f2ba91e9/lib/school_friend/session.rb#L203-L211 | train |
NullVoxPopuli/lazy_crud | lib/lazy_crud/instance_methods.rb | LazyCrud.InstanceMethods.undestroy | def undestroy
@resource = resource_proxy(true).find(params[:id])
set_resource_instance
@resource.deleted_at = nil
@resource.save
respond_with(@resource, location: { action: :index })
# flash[:notice] = "#{resource_name} has been undeleted"
# redirect_to action: :index
end | ruby | def undestroy
@resource = resource_proxy(true).find(params[:id])
set_resource_instance
@resource.deleted_at = nil
@resource.save
respond_with(@resource, location: { action: :index })
# flash[:notice] = "#{resource_name} has been undeleted"
# redirect_to action: :index
end | [
"def",
"undestroy",
"@resource",
"=",
"resource_proxy",
"(",
"true",
")",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"set_resource_instance",
"@resource",
".",
"deleted_at",
"=",
"nil",
"@resource",
".",
"save",
"respond_with",
"(",
"@resource",
",",
"location",
":",
"{",
"action",
":",
":index",
"}",
")",
"end"
] | only works if deleting of resources occurs by setting
the deleted_at field | [
"only",
"works",
"if",
"deleting",
"of",
"resources",
"occurs",
"by",
"setting",
"the",
"deleted_at",
"field"
] | 80997de5de9eba4f96121c2bdb11fc4e4b8b754a | https://github.com/NullVoxPopuli/lazy_crud/blob/80997de5de9eba4f96121c2bdb11fc4e4b8b754a/lib/lazy_crud/instance_methods.rb#L64-L75 | train |
NullVoxPopuli/lazy_crud | lib/lazy_crud/instance_methods.rb | LazyCrud.InstanceMethods.resource_proxy | def resource_proxy(with_deleted = false)
proxy = if parent_instance.present?
parent_instance.send(resource_plural_name)
else
self.class.resource_class
end
if with_deleted and proxy.respond_to?(:with_deleted)
proxy = proxy.with_deleted
end
proxy
end | ruby | def resource_proxy(with_deleted = false)
proxy = if parent_instance.present?
parent_instance.send(resource_plural_name)
else
self.class.resource_class
end
if with_deleted and proxy.respond_to?(:with_deleted)
proxy = proxy.with_deleted
end
proxy
end | [
"def",
"resource_proxy",
"(",
"with_deleted",
"=",
"false",
")",
"proxy",
"=",
"if",
"parent_instance",
".",
"present?",
"parent_instance",
".",
"send",
"(",
"resource_plural_name",
")",
"else",
"self",
".",
"class",
".",
"resource_class",
"end",
"if",
"with_deleted",
"and",
"proxy",
".",
"respond_to?",
"(",
":with_deleted",
")",
"proxy",
"=",
"proxy",
".",
"with_deleted",
"end",
"proxy",
"end"
] | determines if we want to use the parent class if available or
if we just use the resource class | [
"determines",
"if",
"we",
"want",
"to",
"use",
"the",
"parent",
"class",
"if",
"available",
"or",
"if",
"we",
"just",
"use",
"the",
"resource",
"class"
] | 80997de5de9eba4f96121c2bdb11fc4e4b8b754a | https://github.com/NullVoxPopuli/lazy_crud/blob/80997de5de9eba4f96121c2bdb11fc4e4b8b754a/lib/lazy_crud/instance_methods.rb#L95-L107 | train |
m-31/puppetdb_query | lib/puppetdb_query/parser.rb | PuppetDBQuery.Parser.read_maximal_term | def read_maximal_term(priority)
return nil if empty?
logger.debug "read maximal term (#{priority})"
first = read_minimal_term
term = add_next_infix_terms(priority, first)
logger.debug "read maximal term: #{term}"
term
end | ruby | def read_maximal_term(priority)
return nil if empty?
logger.debug "read maximal term (#{priority})"
first = read_minimal_term
term = add_next_infix_terms(priority, first)
logger.debug "read maximal term: #{term}"
term
end | [
"def",
"read_maximal_term",
"(",
"priority",
")",
"return",
"nil",
"if",
"empty?",
"logger",
".",
"debug",
"\"read maximal term (#{priority})\"",
"first",
"=",
"read_minimal_term",
"term",
"=",
"add_next_infix_terms",
"(",
"priority",
",",
"first",
")",
"logger",
".",
"debug",
"\"read maximal term: #{term}\"",
"term",
"end"
] | Reads next maximal term. The following input doesn't make the term more complete.
Respects the priority of operators by comparing it to the given value. | [
"Reads",
"next",
"maximal",
"term",
".",
"The",
"following",
"input",
"doesn",
"t",
"make",
"the",
"term",
"more",
"complete",
".",
"Respects",
"the",
"priority",
"of",
"operators",
"by",
"comparing",
"it",
"to",
"the",
"given",
"value",
"."
] | 58103c91f291de8ce28d679256e50ae391b93ecb | https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/parser.rb#L63-L70 | train |
innku/kublog | app/helpers/kublog/application_helper.rb | Kublog.ApplicationHelper.error_messages_for | def error_messages_for(*objects)
options = objects.extract_options!
options[:header_message] ||= I18n.t(:"activerecord.errors.header", :default => "Invalid Fields")
options[:message] ||= I18n.t(:"activerecord.errors.message", :default => "Correct the following errors and try again.")
messages = objects.compact.map { |o| o.errors.full_messages }.flatten
unless messages.empty?
content_tag(:div, :class => "error_messages") do
list_items = messages.map { |msg| content_tag(:li, msg) }
content_tag(:h2, options[:header_message]) + content_tag(:p, options[:message]) + content_tag(:ul, list_items.join.html_safe)
end
end
end | ruby | def error_messages_for(*objects)
options = objects.extract_options!
options[:header_message] ||= I18n.t(:"activerecord.errors.header", :default => "Invalid Fields")
options[:message] ||= I18n.t(:"activerecord.errors.message", :default => "Correct the following errors and try again.")
messages = objects.compact.map { |o| o.errors.full_messages }.flatten
unless messages.empty?
content_tag(:div, :class => "error_messages") do
list_items = messages.map { |msg| content_tag(:li, msg) }
content_tag(:h2, options[:header_message]) + content_tag(:p, options[:message]) + content_tag(:ul, list_items.join.html_safe)
end
end
end | [
"def",
"error_messages_for",
"(",
"*",
"objects",
")",
"options",
"=",
"objects",
".",
"extract_options!",
"options",
"[",
":header_message",
"]",
"||=",
"I18n",
".",
"t",
"(",
":\"",
"\"",
",",
":default",
"=>",
"\"Invalid Fields\"",
")",
"options",
"[",
":message",
"]",
"||=",
"I18n",
".",
"t",
"(",
":\"",
"\"",
",",
":default",
"=>",
"\"Correct the following errors and try again.\"",
")",
"messages",
"=",
"objects",
".",
"compact",
".",
"map",
"{",
"|",
"o",
"|",
"o",
".",
"errors",
".",
"full_messages",
"}",
".",
"flatten",
"unless",
"messages",
".",
"empty?",
"content_tag",
"(",
":div",
",",
":class",
"=>",
"\"error_messages\"",
")",
"do",
"list_items",
"=",
"messages",
".",
"map",
"{",
"|",
"msg",
"|",
"content_tag",
"(",
":li",
",",
"msg",
")",
"}",
"content_tag",
"(",
":h2",
",",
"options",
"[",
":header_message",
"]",
")",
"+",
"content_tag",
"(",
":p",
",",
"options",
"[",
":message",
"]",
")",
"+",
"content_tag",
"(",
":ul",
",",
"list_items",
".",
"join",
".",
"html_safe",
")",
"end",
"end",
"end"
] | Nifty generators errors helper code | [
"Nifty",
"generators",
"errors",
"helper",
"code"
] | 51b53cc3e1dd742053aed0b13bab915016d9a768 | https://github.com/innku/kublog/blob/51b53cc3e1dd742053aed0b13bab915016d9a768/app/helpers/kublog/application_helper.rb#L5-L16 | train |
rob-lane/shiny_themes | lib/shiny_themes/renders_theme.rb | ShinyThemes.RendersTheme.update_current_theme | def update_current_theme(name, options = {})
self.class.renders_theme(name, options)
Rails.application.config.theme.name = current_theme_name
Rails.application.config.theme.layout = current_theme_layout
ShinyThemes::Engine.theme_config.save unless options[:dont_save]
self.class.theme # return current theme object
end | ruby | def update_current_theme(name, options = {})
self.class.renders_theme(name, options)
Rails.application.config.theme.name = current_theme_name
Rails.application.config.theme.layout = current_theme_layout
ShinyThemes::Engine.theme_config.save unless options[:dont_save]
self.class.theme # return current theme object
end | [
"def",
"update_current_theme",
"(",
"name",
",",
"options",
"=",
"{",
"}",
")",
"self",
".",
"class",
".",
"renders_theme",
"(",
"name",
",",
"options",
")",
"Rails",
".",
"application",
".",
"config",
".",
"theme",
".",
"name",
"=",
"current_theme_name",
"Rails",
".",
"application",
".",
"config",
".",
"theme",
".",
"layout",
"=",
"current_theme_layout",
"ShinyThemes",
"::",
"Engine",
".",
"theme_config",
".",
"save",
"unless",
"options",
"[",
":dont_save",
"]",
"self",
".",
"class",
".",
"theme",
"end"
] | Update the current theme for the controller and optionally save
@param name [String] The name of the new theme
@param options [Hash] Options hash
@option options [String] :layout ('application') Default layout for theme
@option options [Boolean] :dont_save (false) Dont save the update to the theme.yml config
@return (Theme) the theme for the controller | [
"Update",
"the",
"current",
"theme",
"for",
"the",
"controller",
"and",
"optionally",
"save"
] | 8c9e9d6bab1db4c63ddcbeb52b6f4577f4680699 | https://github.com/rob-lane/shiny_themes/blob/8c9e9d6bab1db4c63ddcbeb52b6f4577f4680699/lib/shiny_themes/renders_theme.rb#L34-L40 | train |
wilson/revenant | lib/locks/mysql.rb | Revenant.MySQL.acquire_lock | def acquire_lock(lock_name)
begin
acquired = false
sql = lock_query(lock_name)
connection.query(sql) do |result|
acquired = result.fetch_row.first == "1"
end
acquired
rescue ::Exception
false
end
end | ruby | def acquire_lock(lock_name)
begin
acquired = false
sql = lock_query(lock_name)
connection.query(sql) do |result|
acquired = result.fetch_row.first == "1"
end
acquired
rescue ::Exception
false
end
end | [
"def",
"acquire_lock",
"(",
"lock_name",
")",
"begin",
"acquired",
"=",
"false",
"sql",
"=",
"lock_query",
"(",
"lock_name",
")",
"connection",
".",
"query",
"(",
"sql",
")",
"do",
"|",
"result",
"|",
"acquired",
"=",
"result",
".",
"fetch_row",
".",
"first",
"==",
"\"1\"",
"end",
"acquired",
"rescue",
"::",
"Exception",
"false",
"end",
"end"
] | Expects the connection to behave like an instance of +Mysql+
If you need something else, replace +acquire_lock+ with your own code.
Or define your own lock_function while configuring a new Revenant task. | [
"Expects",
"the",
"connection",
"to",
"behave",
"like",
"an",
"instance",
"of",
"+",
"Mysql",
"+",
"If",
"you",
"need",
"something",
"else",
"replace",
"+",
"acquire_lock",
"+",
"with",
"your",
"own",
"code",
".",
"Or",
"define",
"your",
"own",
"lock_function",
"while",
"configuring",
"a",
"new",
"Revenant",
"task",
"."
] | 80fe65742de54ce0c5a8e6c56cea7003fe286746 | https://github.com/wilson/revenant/blob/80fe65742de54ce0c5a8e6c56cea7003fe286746/lib/locks/mysql.rb#L21-L32 | train |
rob-lane/shiny_themes | lib/shiny_themes/theme_config.rb | ShinyThemes.ThemeConfig.load | def load
new_config = full_config[Rails.env].try(:deep_symbolize_keys!) || {}
# Honor values in config file over defaults
@defaults.reject! { |k, _| new_config.keys.include?(k) }
Rails.application.config.theme.merge!(@defaults.merge(new_config))
end | ruby | def load
new_config = full_config[Rails.env].try(:deep_symbolize_keys!) || {}
# Honor values in config file over defaults
@defaults.reject! { |k, _| new_config.keys.include?(k) }
Rails.application.config.theme.merge!(@defaults.merge(new_config))
end | [
"def",
"load",
"new_config",
"=",
"full_config",
"[",
"Rails",
".",
"env",
"]",
".",
"try",
"(",
":deep_symbolize_keys!",
")",
"||",
"{",
"}",
"@defaults",
".",
"reject!",
"{",
"|",
"k",
",",
"_",
"|",
"new_config",
".",
"keys",
".",
"include?",
"(",
"k",
")",
"}",
"Rails",
".",
"application",
".",
"config",
".",
"theme",
".",
"merge!",
"(",
"@defaults",
".",
"merge",
"(",
"new_config",
")",
")",
"end"
] | Create the ordered options, populate with provided hash and load YAML file
options.
@param default_options [Hash] (Hash.new) - Options to populate the theme
config with.
@options default_options [String] :path The path relative to the rails root
where templates are installed
@options default_options [Array(String)] :asset_directories Names of
directories containing assets for the theme relative to the 'assets'
directory.
Load the theme.yml file and merge it with the theme configuration | [
"Create",
"the",
"ordered",
"options",
"populate",
"with",
"provided",
"hash",
"and",
"load",
"YAML",
"file",
"options",
"."
] | 8c9e9d6bab1db4c63ddcbeb52b6f4577f4680699 | https://github.com/rob-lane/shiny_themes/blob/8c9e9d6bab1db4c63ddcbeb52b6f4577f4680699/lib/shiny_themes/theme_config.rb#L21-L26 | train |
rob-lane/shiny_themes | lib/shiny_themes/theme_config.rb | ShinyThemes.ThemeConfig.save | def save
# Don't save default values
save_config = Rails.application.config.theme.reject { |k, _| @defaults.keys.include?(k) }
full_config[Rails.env].merge!(save_config)
File.open(config_pathname, 'w') { |f| f << full_config.to_yaml }
end | ruby | def save
# Don't save default values
save_config = Rails.application.config.theme.reject { |k, _| @defaults.keys.include?(k) }
full_config[Rails.env].merge!(save_config)
File.open(config_pathname, 'w') { |f| f << full_config.to_yaml }
end | [
"def",
"save",
"save_config",
"=",
"Rails",
".",
"application",
".",
"config",
".",
"theme",
".",
"reject",
"{",
"|",
"k",
",",
"_",
"|",
"@defaults",
".",
"keys",
".",
"include?",
"(",
"k",
")",
"}",
"full_config",
"[",
"Rails",
".",
"env",
"]",
".",
"merge!",
"(",
"save_config",
")",
"File",
".",
"open",
"(",
"config_pathname",
",",
"'w'",
")",
"{",
"|",
"f",
"|",
"f",
"<<",
"full_config",
".",
"to_yaml",
"}",
"end"
] | Save the current state of the theme config to the theme.yml file | [
"Save",
"the",
"current",
"state",
"of",
"the",
"theme",
"config",
"to",
"the",
"theme",
".",
"yml",
"file"
] | 8c9e9d6bab1db4c63ddcbeb52b6f4577f4680699 | https://github.com/rob-lane/shiny_themes/blob/8c9e9d6bab1db4c63ddcbeb52b6f4577f4680699/lib/shiny_themes/theme_config.rb#L29-L34 | train |
jarhart/rattler | lib/rattler/parsers/super.rb | Rattler::Parsers.Super.parse | def parse(scanner, rules, scope = ParserScope.empty)
rules.inherited_rule(rule_name).parse(scanner, rules, scope)
end | ruby | def parse(scanner, rules, scope = ParserScope.empty)
rules.inherited_rule(rule_name).parse(scanner, rules, scope)
end | [
"def",
"parse",
"(",
"scanner",
",",
"rules",
",",
"scope",
"=",
"ParserScope",
".",
"empty",
")",
"rules",
".",
"inherited_rule",
"(",
"rule_name",
")",
".",
"parse",
"(",
"scanner",
",",
"rules",
",",
"scope",
")",
"end"
] | Apply the parse rule of the same name inherited from a super-grammar.
@param (see Match#parse)
@return the result of applying parse rule of the same name inherited from
a super-grammar | [
"Apply",
"the",
"parse",
"rule",
"of",
"the",
"same",
"name",
"inherited",
"from",
"a",
"super",
"-",
"grammar",
"."
] | 8b4efde2a05e9e790955bb635d4a1a9615893719 | https://github.com/jarhart/rattler/blob/8b4efde2a05e9e790955bb635d4a1a9615893719/lib/rattler/parsers/super.rb#L23-L25 | train |
jrochkind/borrow_direct | lib/borrow_direct/find_item.rb | BorrowDirect.FindItem.exact_search_request_hash | def exact_search_request_hash(type, value)
# turn it into an array if it's not one already
values = Array(value)
hash = {
"PartnershipId" => Defaults.partnership_id,
"ExactSearch" => []
}
values.each do |value|
hash["ExactSearch"] << {
"Type" => type.to_s.upcase,
"Value" => value
}
end
return hash
end | ruby | def exact_search_request_hash(type, value)
# turn it into an array if it's not one already
values = Array(value)
hash = {
"PartnershipId" => Defaults.partnership_id,
"ExactSearch" => []
}
values.each do |value|
hash["ExactSearch"] << {
"Type" => type.to_s.upcase,
"Value" => value
}
end
return hash
end | [
"def",
"exact_search_request_hash",
"(",
"type",
",",
"value",
")",
"values",
"=",
"Array",
"(",
"value",
")",
"hash",
"=",
"{",
"\"PartnershipId\"",
"=>",
"Defaults",
".",
"partnership_id",
",",
"\"ExactSearch\"",
"=>",
"[",
"]",
"}",
"values",
".",
"each",
"do",
"|",
"value",
"|",
"hash",
"[",
"\"ExactSearch\"",
"]",
"<<",
"{",
"\"Type\"",
"=>",
"type",
".",
"to_s",
".",
"upcase",
",",
"\"Value\"",
"=>",
"value",
"}",
"end",
"return",
"hash",
"end"
] | Produce BD request hash for exact search of type eg "ISBN"
value can be a singel value, or an array of values. For array,
BD will "OR" them. | [
"Produce",
"BD",
"request",
"hash",
"for",
"exact",
"search",
"of",
"type",
"eg",
"ISBN",
"value",
"can",
"be",
"a",
"singel",
"value",
"or",
"an",
"array",
"of",
"values",
".",
"For",
"array",
"BD",
"will",
"OR",
"them",
"."
] | f2f53760e15d742a5c5584dd641f20dea315f99f | https://github.com/jrochkind/borrow_direct/blob/f2f53760e15d742a5c5584dd641f20dea315f99f/lib/borrow_direct/find_item.rb#L78-L95 | train |
atomicobject/hardmock | lib/hardmock/expectation.rb | Hardmock.Expectation.raises | def raises(err=nil)
case err
when Exception
@options[:raises] = err
when String
@options[:raises] = RuntimeError.new(err)
else
@options[:raises] = RuntimeError.new("An Error")
end
self
end | ruby | def raises(err=nil)
case err
when Exception
@options[:raises] = err
when String
@options[:raises] = RuntimeError.new(err)
else
@options[:raises] = RuntimeError.new("An Error")
end
self
end | [
"def",
"raises",
"(",
"err",
"=",
"nil",
")",
"case",
"err",
"when",
"Exception",
"@options",
"[",
":raises",
"]",
"=",
"err",
"when",
"String",
"@options",
"[",
":raises",
"]",
"=",
"RuntimeError",
".",
"new",
"(",
"err",
")",
"else",
"@options",
"[",
":raises",
"]",
"=",
"RuntimeError",
".",
"new",
"(",
"\"An Error\"",
")",
"end",
"self",
"end"
] | Rig an expected method to raise an exception when the mock is invoked.
Eg,
@cash_machine.expects.withdraw(20,:dollars).raises "Insufficient funds"
The argument can be:
* an Exception -- will be used directly
* a String -- will be used as the message for a RuntimeError
* nothing -- RuntimeError.new("An Error") will be raised | [
"Rig",
"an",
"expected",
"method",
"to",
"raise",
"an",
"exception",
"when",
"the",
"mock",
"is",
"invoked",
"."
] | a2c01c2cbd28f56a71cc824f04b40ea1d14be367 | https://github.com/atomicobject/hardmock/blob/a2c01c2cbd28f56a71cc824f04b40ea1d14be367/lib/hardmock/expectation.rb#L86-L96 | train |
atomicobject/hardmock | lib/hardmock/expectation.rb | Hardmock.Expectation.yields | def yields(*items)
@options[:suppress_arguments_to_block] = true
if items.empty?
# Yield once
@options[:block] = lambda do |block|
if block.arity != 0 and block.arity != -1
raise ExpectationError.new("The given block was expected to have no parameter count; instead, got #{block.arity} to <#{to_s}>")
end
block.call
end
else
# Yield one or more specific items
@options[:block] = lambda do |block|
items.each do |item|
if item.kind_of?(Array)
if block.arity == item.size
# Unfold the array into the block's arguments:
block.call *item
elsif block.arity == 1
# Just pass the array in
block.call item
else
# Size mismatch
raise ExpectationError.new("Can't pass #{item.inspect} to block with arity #{block.arity} to <#{to_s}>")
end
else
if block.arity != 1
# Size mismatch
raise ExpectationError.new("Can't pass #{item.inspect} to block with arity #{block.arity} to <#{to_s}>")
end
block.call item
end
end
end
end
self
end | ruby | def yields(*items)
@options[:suppress_arguments_to_block] = true
if items.empty?
# Yield once
@options[:block] = lambda do |block|
if block.arity != 0 and block.arity != -1
raise ExpectationError.new("The given block was expected to have no parameter count; instead, got #{block.arity} to <#{to_s}>")
end
block.call
end
else
# Yield one or more specific items
@options[:block] = lambda do |block|
items.each do |item|
if item.kind_of?(Array)
if block.arity == item.size
# Unfold the array into the block's arguments:
block.call *item
elsif block.arity == 1
# Just pass the array in
block.call item
else
# Size mismatch
raise ExpectationError.new("Can't pass #{item.inspect} to block with arity #{block.arity} to <#{to_s}>")
end
else
if block.arity != 1
# Size mismatch
raise ExpectationError.new("Can't pass #{item.inspect} to block with arity #{block.arity} to <#{to_s}>")
end
block.call item
end
end
end
end
self
end | [
"def",
"yields",
"(",
"*",
"items",
")",
"@options",
"[",
":suppress_arguments_to_block",
"]",
"=",
"true",
"if",
"items",
".",
"empty?",
"@options",
"[",
":block",
"]",
"=",
"lambda",
"do",
"|",
"block",
"|",
"if",
"block",
".",
"arity",
"!=",
"0",
"and",
"block",
".",
"arity",
"!=",
"-",
"1",
"raise",
"ExpectationError",
".",
"new",
"(",
"\"The given block was expected to have no parameter count; instead, got #{block.arity} to <#{to_s}>\"",
")",
"end",
"block",
".",
"call",
"end",
"else",
"@options",
"[",
":block",
"]",
"=",
"lambda",
"do",
"|",
"block",
"|",
"items",
".",
"each",
"do",
"|",
"item",
"|",
"if",
"item",
".",
"kind_of?",
"(",
"Array",
")",
"if",
"block",
".",
"arity",
"==",
"item",
".",
"size",
"block",
".",
"call",
"*",
"item",
"elsif",
"block",
".",
"arity",
"==",
"1",
"block",
".",
"call",
"item",
"else",
"raise",
"ExpectationError",
".",
"new",
"(",
"\"Can't pass #{item.inspect} to block with arity #{block.arity} to <#{to_s}>\"",
")",
"end",
"else",
"if",
"block",
".",
"arity",
"!=",
"1",
"raise",
"ExpectationError",
".",
"new",
"(",
"\"Can't pass #{item.inspect} to block with arity #{block.arity} to <#{to_s}>\"",
")",
"end",
"block",
".",
"call",
"item",
"end",
"end",
"end",
"end",
"self",
"end"
] | Used when an expected method accepts a block at runtime.
When the expected method is invoked, the block passed to
that method will be invoked as well.
NOTE: ExpectationError will be thrown upon running the expected method
if the arguments you set up in +yields+ do not properly match up with
the actual block that ends up getting passed.
== Examples
<b>Single invocation</b>: The block passed to +lock_down+ gets invoked
once with no arguments:
@safe_zone.expects.lock_down.yields
# (works on code that looks like:)
@safe_zone.lock_down do
# ... this block invoked once
end
<b>Multi-parameter blocks:</b> The block passed to +each_item+ gets
invoked twice, with <tt>:item1</tt> the first time, and with
<tt>:item2</tt> the second time:
@fruit_basket.expects.each_with_index.yields [:apple,1], [:orange,2]
# (works on code that looks like:)
@fruit_basket.each_with_index do |fruit,index|
# ... this block invoked with fruit=:apple, index=1,
# ... and then with fruit=:orange, index=2
end
<b>Arrays can be passed as arguments too</b>... if the block
takes a single argument and you want to pass a series of arrays into it,
that will work as well:
@list_provider.expects.each_list.yields [1,2,3], [4,5,6]
# (works on code that looks like:)
@list_provider.each_list do |list|
# ... list is [1,2,3] the first time
# ... list is [4,5,6] the second time
end
<b>Return value</b>: You can set the return value for the method that
accepts the block like so:
@cruncher.expects.do_things.yields(:bean1,:bean2).returns("The Results")
<b>Raising errors</b>: You can set the raised exception for the method that
accepts the block. NOTE: the error will be raised _after_ the block has
been invoked.
# :bean1 and :bean2 will be passed to the block, then an error is raised:
@cruncher.expects.do_things.yields(:bean1,:bean2).raises("Too crunchy") | [
"Used",
"when",
"an",
"expected",
"method",
"accepts",
"a",
"block",
"at",
"runtime",
".",
"When",
"the",
"expected",
"method",
"is",
"invoked",
"the",
"block",
"passed",
"to",
"that",
"method",
"will",
"be",
"invoked",
"as",
"well",
"."
] | a2c01c2cbd28f56a71cc824f04b40ea1d14be367 | https://github.com/atomicobject/hardmock/blob/a2c01c2cbd28f56a71cc824f04b40ea1d14be367/lib/hardmock/expectation.rb#L182-L218 | train |
roja/words | lib/words.rb | Words.Wordnet.find | def find(term)
raise NoWordnetConnection, "There is presently no connection to wordnet. To attempt to reistablish a connection you should use the 'open!' command on the Wordnet object." unless connected?
homographs = @wordnet_connection.homographs(term)
Homographs.new(homographs, @wordnet_connection) unless homographs.nil?
end | ruby | def find(term)
raise NoWordnetConnection, "There is presently no connection to wordnet. To attempt to reistablish a connection you should use the 'open!' command on the Wordnet object." unless connected?
homographs = @wordnet_connection.homographs(term)
Homographs.new(homographs, @wordnet_connection) unless homographs.nil?
end | [
"def",
"find",
"(",
"term",
")",
"raise",
"NoWordnetConnection",
",",
"\"There is presently no connection to wordnet. To attempt to reistablish a connection you should use the 'open!' command on the Wordnet object.\"",
"unless",
"connected?",
"homographs",
"=",
"@wordnet_connection",
".",
"homographs",
"(",
"term",
")",
"Homographs",
".",
"new",
"(",
"homographs",
",",
"@wordnet_connection",
")",
"unless",
"homographs",
".",
"nil?",
"end"
] | Constructs a new wordnet connection object.
@param [Symbol] connector_type Specifies the connector type or mode desired. Current supported connectors are :pure and :tokyo.
@param [String, Symbol] wordnet_path Specifies the directory within which the wordnet dictionary can be found. It can be set to :search to attempt to locate wordnet automatically.
@param [String, Symbol] data_path Specifies the directory within which constructed datasets can be found (tokyo index, evocations etc...) It can be set to :default to use the standard location inside the gem directory.
@return [Wordnet] The wordnet connection object.
@raise [BadWordnetConnector] If an invalid connector type is provided.
Locates the set of homographs within wordnet specific to the term entered.
@param [String] term The specific term that is desired from within wordnet. This is caps insensative & we do a small amount of cleanup.
@return [Homographs] An object encaptulating the homographs of the desired term. If the term cannot be located within wordnet then nil is returned.
@raise [NoWordnetConnection] If there is currently no wordnet connection. | [
"Constructs",
"a",
"new",
"wordnet",
"connection",
"object",
"."
] | 4d6302e7218533fcc2afb4cd993686dd56fe2cde | https://github.com/roja/words/blob/4d6302e7218533fcc2afb4cd993686dd56fe2cde/lib/words.rb#L65-L71 | train |
bjh/griddle | lib/griddle/point.rb | Griddle.Point.to_rectangle | def to_rectangle(point)
d = delta(point)
Rectangle.new(
row,
col,
d.col + 1,
d.row + 1
)
end | ruby | def to_rectangle(point)
d = delta(point)
Rectangle.new(
row,
col,
d.col + 1,
d.row + 1
)
end | [
"def",
"to_rectangle",
"(",
"point",
")",
"d",
"=",
"delta",
"(",
"point",
")",
"Rectangle",
".",
"new",
"(",
"row",
",",
"col",
",",
"d",
".",
"col",
"+",
"1",
",",
"d",
".",
"row",
"+",
"1",
")",
"end"
] | `point` is used to calculate the width and height
of the new rectangle | [
"point",
"is",
"used",
"to",
"calculate",
"the",
"width",
"and",
"height",
"of",
"the",
"new",
"rectangle"
] | c924bcb56172c282cfa246560d8b2051d48e8884 | https://github.com/bjh/griddle/blob/c924bcb56172c282cfa246560d8b2051d48e8884/lib/griddle/point.rb#L34-L43 | train |
medihack/make_voteable | lib/make_voteable/voter.rb | MakeVoteable.Voter.up_vote | def up_vote(voteable)
check_voteable(voteable)
voting = fetch_voting(voteable)
if voting
if voting.up_vote
raise Exceptions::AlreadyVotedError.new(true)
else
voting.up_vote = true
voteable.down_votes -= 1
self.down_votes -= 1 if has_attribute?(:down_votes)
end
else
voting = Voting.create(:voteable => voteable, :voter_id => self.id, :voter_type => self.class.to_s, :up_vote => true)
end
voteable.up_votes += 1
self.up_votes += 1 if has_attribute?(:up_votes)
Voting.transaction do
save
voteable.save
voting.save
end
true
end | ruby | def up_vote(voteable)
check_voteable(voteable)
voting = fetch_voting(voteable)
if voting
if voting.up_vote
raise Exceptions::AlreadyVotedError.new(true)
else
voting.up_vote = true
voteable.down_votes -= 1
self.down_votes -= 1 if has_attribute?(:down_votes)
end
else
voting = Voting.create(:voteable => voteable, :voter_id => self.id, :voter_type => self.class.to_s, :up_vote => true)
end
voteable.up_votes += 1
self.up_votes += 1 if has_attribute?(:up_votes)
Voting.transaction do
save
voteable.save
voting.save
end
true
end | [
"def",
"up_vote",
"(",
"voteable",
")",
"check_voteable",
"(",
"voteable",
")",
"voting",
"=",
"fetch_voting",
"(",
"voteable",
")",
"if",
"voting",
"if",
"voting",
".",
"up_vote",
"raise",
"Exceptions",
"::",
"AlreadyVotedError",
".",
"new",
"(",
"true",
")",
"else",
"voting",
".",
"up_vote",
"=",
"true",
"voteable",
".",
"down_votes",
"-=",
"1",
"self",
".",
"down_votes",
"-=",
"1",
"if",
"has_attribute?",
"(",
":down_votes",
")",
"end",
"else",
"voting",
"=",
"Voting",
".",
"create",
"(",
":voteable",
"=>",
"voteable",
",",
":voter_id",
"=>",
"self",
".",
"id",
",",
":voter_type",
"=>",
"self",
".",
"class",
".",
"to_s",
",",
":up_vote",
"=>",
"true",
")",
"end",
"voteable",
".",
"up_votes",
"+=",
"1",
"self",
".",
"up_votes",
"+=",
"1",
"if",
"has_attribute?",
"(",
":up_votes",
")",
"Voting",
".",
"transaction",
"do",
"save",
"voteable",
".",
"save",
"voting",
".",
"save",
"end",
"true",
"end"
] | Up vote a +voteable+.
Raises an AlreadyVotedError if the voter already up voted the voteable.
Changes a down vote to an up vote if the the voter already down voted the voteable. | [
"Up",
"vote",
"a",
"+",
"voteable",
"+",
".",
"Raises",
"an",
"AlreadyVotedError",
"if",
"the",
"voter",
"already",
"up",
"voted",
"the",
"voteable",
".",
"Changes",
"a",
"down",
"vote",
"to",
"an",
"up",
"vote",
"if",
"the",
"the",
"voter",
"already",
"down",
"voted",
"the",
"voteable",
"."
] | 3cf3f7ca1c8db075a6a51e101c1b38ef724facd2 | https://github.com/medihack/make_voteable/blob/3cf3f7ca1c8db075a6a51e101c1b38ef724facd2/lib/make_voteable/voter.rb#L18-L45 | train |
medihack/make_voteable | lib/make_voteable/voter.rb | MakeVoteable.Voter.up_vote! | def up_vote!(voteable)
begin
up_vote(voteable)
success = true
rescue Exceptions::AlreadyVotedError
success = false
end
success
end | ruby | def up_vote!(voteable)
begin
up_vote(voteable)
success = true
rescue Exceptions::AlreadyVotedError
success = false
end
success
end | [
"def",
"up_vote!",
"(",
"voteable",
")",
"begin",
"up_vote",
"(",
"voteable",
")",
"success",
"=",
"true",
"rescue",
"Exceptions",
"::",
"AlreadyVotedError",
"success",
"=",
"false",
"end",
"success",
"end"
] | Up votes the +voteable+, but doesn't raise an error if the votelable was already up voted.
The vote is simply ignored then. | [
"Up",
"votes",
"the",
"+",
"voteable",
"+",
"but",
"doesn",
"t",
"raise",
"an",
"error",
"if",
"the",
"votelable",
"was",
"already",
"up",
"voted",
".",
"The",
"vote",
"is",
"simply",
"ignored",
"then",
"."
] | 3cf3f7ca1c8db075a6a51e101c1b38ef724facd2 | https://github.com/medihack/make_voteable/blob/3cf3f7ca1c8db075a6a51e101c1b38ef724facd2/lib/make_voteable/voter.rb#L49-L57 | train |
medihack/make_voteable | lib/make_voteable/voter.rb | MakeVoteable.Voter.down_vote! | def down_vote!(voteable)
begin
down_vote(voteable)
success = true
rescue Exceptions::AlreadyVotedError
success = false
end
success
end | ruby | def down_vote!(voteable)
begin
down_vote(voteable)
success = true
rescue Exceptions::AlreadyVotedError
success = false
end
success
end | [
"def",
"down_vote!",
"(",
"voteable",
")",
"begin",
"down_vote",
"(",
"voteable",
")",
"success",
"=",
"true",
"rescue",
"Exceptions",
"::",
"AlreadyVotedError",
"success",
"=",
"false",
"end",
"success",
"end"
] | Down votes the +voteable+, but doesn't raise an error if the votelable was already down voted.
The vote is simply ignored then. | [
"Down",
"votes",
"the",
"+",
"voteable",
"+",
"but",
"doesn",
"t",
"raise",
"an",
"error",
"if",
"the",
"votelable",
"was",
"already",
"down",
"voted",
".",
"The",
"vote",
"is",
"simply",
"ignored",
"then",
"."
] | 3cf3f7ca1c8db075a6a51e101c1b38ef724facd2 | https://github.com/medihack/make_voteable/blob/3cf3f7ca1c8db075a6a51e101c1b38ef724facd2/lib/make_voteable/voter.rb#L93-L101 | train |
medihack/make_voteable | lib/make_voteable/voter.rb | MakeVoteable.Voter.unvote | def unvote(voteable)
check_voteable(voteable)
voting = fetch_voting(voteable)
raise Exceptions::NotVotedError unless voting
if voting.up_vote
voteable.up_votes -= 1
self.up_votes -= 1 if has_attribute?(:up_votes)
else
voteable.down_votes -= 1
self.down_votes -= 1 if has_attribute?(:down_votes)
end
Voting.transaction do
save
voteable.save
voting.destroy
end
true
end | ruby | def unvote(voteable)
check_voteable(voteable)
voting = fetch_voting(voteable)
raise Exceptions::NotVotedError unless voting
if voting.up_vote
voteable.up_votes -= 1
self.up_votes -= 1 if has_attribute?(:up_votes)
else
voteable.down_votes -= 1
self.down_votes -= 1 if has_attribute?(:down_votes)
end
Voting.transaction do
save
voteable.save
voting.destroy
end
true
end | [
"def",
"unvote",
"(",
"voteable",
")",
"check_voteable",
"(",
"voteable",
")",
"voting",
"=",
"fetch_voting",
"(",
"voteable",
")",
"raise",
"Exceptions",
"::",
"NotVotedError",
"unless",
"voting",
"if",
"voting",
".",
"up_vote",
"voteable",
".",
"up_votes",
"-=",
"1",
"self",
".",
"up_votes",
"-=",
"1",
"if",
"has_attribute?",
"(",
":up_votes",
")",
"else",
"voteable",
".",
"down_votes",
"-=",
"1",
"self",
".",
"down_votes",
"-=",
"1",
"if",
"has_attribute?",
"(",
":down_votes",
")",
"end",
"Voting",
".",
"transaction",
"do",
"save",
"voteable",
".",
"save",
"voting",
".",
"destroy",
"end",
"true",
"end"
] | Clears an already done vote on a +voteable+.
Raises a NotVotedError if the voter didn't voted for the voteable. | [
"Clears",
"an",
"already",
"done",
"vote",
"on",
"a",
"+",
"voteable",
"+",
".",
"Raises",
"a",
"NotVotedError",
"if",
"the",
"voter",
"didn",
"t",
"voted",
"for",
"the",
"voteable",
"."
] | 3cf3f7ca1c8db075a6a51e101c1b38ef724facd2 | https://github.com/medihack/make_voteable/blob/3cf3f7ca1c8db075a6a51e101c1b38ef724facd2/lib/make_voteable/voter.rb#L105-L127 | train |
medihack/make_voteable | lib/make_voteable/voter.rb | MakeVoteable.Voter.unvote! | def unvote!(voteable)
begin
unvote(voteable)
success = true
rescue Exceptions::NotVotedError
success = false
end
success
end | ruby | def unvote!(voteable)
begin
unvote(voteable)
success = true
rescue Exceptions::NotVotedError
success = false
end
success
end | [
"def",
"unvote!",
"(",
"voteable",
")",
"begin",
"unvote",
"(",
"voteable",
")",
"success",
"=",
"true",
"rescue",
"Exceptions",
"::",
"NotVotedError",
"success",
"=",
"false",
"end",
"success",
"end"
] | Clears an already done vote on a +voteable+, but doesn't raise an error if
the voteable was not voted. It ignores the unvote then. | [
"Clears",
"an",
"already",
"done",
"vote",
"on",
"a",
"+",
"voteable",
"+",
"but",
"doesn",
"t",
"raise",
"an",
"error",
"if",
"the",
"voteable",
"was",
"not",
"voted",
".",
"It",
"ignores",
"the",
"unvote",
"then",
"."
] | 3cf3f7ca1c8db075a6a51e101c1b38ef724facd2 | https://github.com/medihack/make_voteable/blob/3cf3f7ca1c8db075a6a51e101c1b38ef724facd2/lib/make_voteable/voter.rb#L131-L139 | train |
medihack/make_voteable | lib/make_voteable/voter.rb | MakeVoteable.Voter.down_voted? | def down_voted?(voteable)
check_voteable(voteable)
voting = fetch_voting(voteable)
return false if voting.nil?
return true if voting.has_attribute?(:up_vote) && !voting.up_vote
false
end | ruby | def down_voted?(voteable)
check_voteable(voteable)
voting = fetch_voting(voteable)
return false if voting.nil?
return true if voting.has_attribute?(:up_vote) && !voting.up_vote
false
end | [
"def",
"down_voted?",
"(",
"voteable",
")",
"check_voteable",
"(",
"voteable",
")",
"voting",
"=",
"fetch_voting",
"(",
"voteable",
")",
"return",
"false",
"if",
"voting",
".",
"nil?",
"return",
"true",
"if",
"voting",
".",
"has_attribute?",
"(",
":up_vote",
")",
"&&",
"!",
"voting",
".",
"up_vote",
"false",
"end"
] | Returns true if the voter down voted the +voteable+. | [
"Returns",
"true",
"if",
"the",
"voter",
"down",
"voted",
"the",
"+",
"voteable",
"+",
"."
] | 3cf3f7ca1c8db075a6a51e101c1b38ef724facd2 | https://github.com/medihack/make_voteable/blob/3cf3f7ca1c8db075a6a51e101c1b38ef724facd2/lib/make_voteable/voter.rb#L158-L164 | train |
mkfs/mindset | lib/mindset/connection.rb | Mindset.LoopbackConnection.read_packet_buffer | def read_packet_buffer
packets = @data[:wave][@wave_idx, 64].map { |val|
Packet.factory(:wave, val) }
@wave_idx += 64
@wave_idx = 0 if @wave_idx >= @data[:wave].count
if @counter == 7
packets << Packet.factory(:delta, @data[:delta][@esense_idx])
packets << Packet.factory(:theta, @data[:theta][@esense_idx])
packets << Packet.factory(:lo_alpha, @data[:lo_alpha][@esense_idx])
packets << Packet.factory(:hi_alpha, @data[:hi_alpha][@esense_idx])
packets << Packet.factory(:lo_beta, @data[:lo_beta][@esense_idx])
packets << Packet.factory(:hi_beta, @data[:hi_beta][@esense_idx])
packets << Packet.factory(:lo_gamma, @data[:lo_gamma][@esense_idx])
packets << Packet.factory(:mid_gamma, @data[:mid_gamma][@esense_idx])
packets << Packet.factory(:signal_quality,
@data[:signal_quality][@esense_idx])
packets << Packet.factory(:attention, @data[:attention][@esense_idx])
packets << Packet.factory(:meditation, @data[:meditation][@esense_idx])
packets << Packet.factory(:blink, @data[:blink][@esense_idx])
@esense_idx += 1
@esense_idx = 0 if @esense_idx >= @data[:delta].count
end
@counter = (@counter + 1) % 8
packets
end | ruby | def read_packet_buffer
packets = @data[:wave][@wave_idx, 64].map { |val|
Packet.factory(:wave, val) }
@wave_idx += 64
@wave_idx = 0 if @wave_idx >= @data[:wave].count
if @counter == 7
packets << Packet.factory(:delta, @data[:delta][@esense_idx])
packets << Packet.factory(:theta, @data[:theta][@esense_idx])
packets << Packet.factory(:lo_alpha, @data[:lo_alpha][@esense_idx])
packets << Packet.factory(:hi_alpha, @data[:hi_alpha][@esense_idx])
packets << Packet.factory(:lo_beta, @data[:lo_beta][@esense_idx])
packets << Packet.factory(:hi_beta, @data[:hi_beta][@esense_idx])
packets << Packet.factory(:lo_gamma, @data[:lo_gamma][@esense_idx])
packets << Packet.factory(:mid_gamma, @data[:mid_gamma][@esense_idx])
packets << Packet.factory(:signal_quality,
@data[:signal_quality][@esense_idx])
packets << Packet.factory(:attention, @data[:attention][@esense_idx])
packets << Packet.factory(:meditation, @data[:meditation][@esense_idx])
packets << Packet.factory(:blink, @data[:blink][@esense_idx])
@esense_idx += 1
@esense_idx = 0 if @esense_idx >= @data[:delta].count
end
@counter = (@counter + 1) % 8
packets
end | [
"def",
"read_packet_buffer",
"packets",
"=",
"@data",
"[",
":wave",
"]",
"[",
"@wave_idx",
",",
"64",
"]",
".",
"map",
"{",
"|",
"val",
"|",
"Packet",
".",
"factory",
"(",
":wave",
",",
"val",
")",
"}",
"@wave_idx",
"+=",
"64",
"@wave_idx",
"=",
"0",
"if",
"@wave_idx",
">=",
"@data",
"[",
":wave",
"]",
".",
"count",
"if",
"@counter",
"==",
"7",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":delta",
",",
"@data",
"[",
":delta",
"]",
"[",
"@esense_idx",
"]",
")",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":theta",
",",
"@data",
"[",
":theta",
"]",
"[",
"@esense_idx",
"]",
")",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":lo_alpha",
",",
"@data",
"[",
":lo_alpha",
"]",
"[",
"@esense_idx",
"]",
")",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":hi_alpha",
",",
"@data",
"[",
":hi_alpha",
"]",
"[",
"@esense_idx",
"]",
")",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":lo_beta",
",",
"@data",
"[",
":lo_beta",
"]",
"[",
"@esense_idx",
"]",
")",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":hi_beta",
",",
"@data",
"[",
":hi_beta",
"]",
"[",
"@esense_idx",
"]",
")",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":lo_gamma",
",",
"@data",
"[",
":lo_gamma",
"]",
"[",
"@esense_idx",
"]",
")",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":mid_gamma",
",",
"@data",
"[",
":mid_gamma",
"]",
"[",
"@esense_idx",
"]",
")",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":signal_quality",
",",
"@data",
"[",
":signal_quality",
"]",
"[",
"@esense_idx",
"]",
")",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":attention",
",",
"@data",
"[",
":attention",
"]",
"[",
"@esense_idx",
"]",
")",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":meditation",
",",
"@data",
"[",
":meditation",
"]",
"[",
"@esense_idx",
"]",
")",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":blink",
",",
"@data",
"[",
":blink",
"]",
"[",
"@esense_idx",
"]",
")",
"@esense_idx",
"+=",
"1",
"@esense_idx",
"=",
"0",
"if",
"@esense_idx",
">=",
"@data",
"[",
":delta",
"]",
".",
"count",
"end",
"@counter",
"=",
"(",
"@counter",
"+",
"1",
")",
"%",
"8",
"packets",
"end"
] | =begin rdoc
Simulate a read of the Mindset device by returning an Array of Packet objects.
This assumes it will be called 8 times a second.
According to the MDT, Mindset packets are sent at the following intervals:
1 packet per second: eSense, ASIC EEG, POOR_SIGNAL
512 packets per second: RAW
Each read will therefore return 64 RAW packets. Every eighth read will also
return 1 eSense, ASIC_EEG, and POOR_SIGNAL packet.
=end | [
"=",
"begin",
"rdoc",
"Simulate",
"a",
"read",
"of",
"the",
"Mindset",
"device",
"by",
"returning",
"an",
"Array",
"of",
"Packet",
"objects",
".",
"This",
"assumes",
"it",
"will",
"be",
"called",
"8",
"times",
"a",
"second",
"."
] | 1b8a6b9c1773290828ba126065c1327ffdffabf1 | https://github.com/mkfs/mindset/blob/1b8a6b9c1773290828ba126065c1327ffdffabf1/lib/mindset/connection.rb#L193-L219 | train |
notjosh/danger-package_json_lockdown | lib/package_json_lockdown/plugin.rb | Danger.DangerPackageJsonLockdown.verify | def verify(package_json)
inspect(package_json).each do |suspicious|
warn(
"`#{suspicious[:package]}` doesn't specify fixed version number",
file: package_json,
line: suspicious[:line]
)
end
end | ruby | def verify(package_json)
inspect(package_json).each do |suspicious|
warn(
"`#{suspicious[:package]}` doesn't specify fixed version number",
file: package_json,
line: suspicious[:line]
)
end
end | [
"def",
"verify",
"(",
"package_json",
")",
"inspect",
"(",
"package_json",
")",
".",
"each",
"do",
"|",
"suspicious",
"|",
"warn",
"(",
"\"`#{suspicious[:package]}` doesn't specify fixed version number\"",
",",
"file",
":",
"package_json",
",",
"line",
":",
"suspicious",
"[",
":line",
"]",
")",
"end",
"end"
] | Verifies the supplied `package.json` file
@param [string] package_json
Path to `package.json`, relative to current directory
@return [void] | [
"Verifies",
"the",
"supplied",
"package",
".",
"json",
"file"
] | 7cdd25864da877fe90bc33350db22324f394cbfc | https://github.com/notjosh/danger-package_json_lockdown/blob/7cdd25864da877fe90bc33350db22324f394cbfc/lib/package_json_lockdown/plugin.rb#L64-L72 | train |
notjosh/danger-package_json_lockdown | lib/package_json_lockdown/plugin.rb | Danger.DangerPackageJsonLockdown.inspect | def inspect(package_json)
json = JSON.parse(File.read(package_json))
suspicious_packages = []
dependency_keys.each do |dependency_key|
next unless json.key?(dependency_key)
results = find_something_suspicious(json[dependency_key], package_json)
suspicious_packages.push(*results)
end
suspicious_packages
end | ruby | def inspect(package_json)
json = JSON.parse(File.read(package_json))
suspicious_packages = []
dependency_keys.each do |dependency_key|
next unless json.key?(dependency_key)
results = find_something_suspicious(json[dependency_key], package_json)
suspicious_packages.push(*results)
end
suspicious_packages
end | [
"def",
"inspect",
"(",
"package_json",
")",
"json",
"=",
"JSON",
".",
"parse",
"(",
"File",
".",
"read",
"(",
"package_json",
")",
")",
"suspicious_packages",
"=",
"[",
"]",
"dependency_keys",
".",
"each",
"do",
"|",
"dependency_key",
"|",
"next",
"unless",
"json",
".",
"key?",
"(",
"dependency_key",
")",
"results",
"=",
"find_something_suspicious",
"(",
"json",
"[",
"dependency_key",
"]",
",",
"package_json",
")",
"suspicious_packages",
".",
"push",
"(",
"*",
"results",
")",
"end",
"suspicious_packages",
"end"
] | Inspects the supplied `package.json` file and returns problems
@param [string] package_json
Path to `package.json`, relative to current directory
@return [Array<{Symbol => String}>]
- `:package`: the offending package name
- `:version`: the version as written in `package.json`
- `:line`: (probably) the line number. | [
"Inspects",
"the",
"supplied",
"package",
".",
"json",
"file",
"and",
"returns",
"problems"
] | 7cdd25864da877fe90bc33350db22324f394cbfc | https://github.com/notjosh/danger-package_json_lockdown/blob/7cdd25864da877fe90bc33350db22324f394cbfc/lib/package_json_lockdown/plugin.rb#L81-L94 | train |
jemmyw/bisques | lib/bisques/queue_listener.rb | Bisques.QueueListener.listen | def listen(&block)
return if @listening
@listening = true
@thread = Thread.new do
while @listening
message = @queue.retrieve(@poll_time)
block.call(message) if message.present?
end
end
end | ruby | def listen(&block)
return if @listening
@listening = true
@thread = Thread.new do
while @listening
message = @queue.retrieve(@poll_time)
block.call(message) if message.present?
end
end
end | [
"def",
"listen",
"(",
"&",
"block",
")",
"return",
"if",
"@listening",
"@listening",
"=",
"true",
"@thread",
"=",
"Thread",
".",
"new",
"do",
"while",
"@listening",
"message",
"=",
"@queue",
".",
"retrieve",
"(",
"@poll_time",
")",
"block",
".",
"call",
"(",
"message",
")",
"if",
"message",
".",
"present?",
"end",
"end",
"end"
] | Listen for messages. This is asynchronous and returns immediately.
@example
queue = bisques.find_or_create_queue("my queue")
listener = QueuedListener.new(queue)
listener.listen do |message|
puts "Received #{message.object}"
message.delete
end
while true; sleep 1; end # Process messages forever
@note Note that the block you give to this method is executed in a new thread.
@yield [Message] a message received from the {Queue} | [
"Listen",
"for",
"messages",
".",
"This",
"is",
"asynchronous",
"and",
"returns",
"immediately",
"."
] | c48ab555f07664752bcbf9e8deb99bd75cbdc41b | https://github.com/jemmyw/bisques/blob/c48ab555f07664752bcbf9e8deb99bd75cbdc41b/lib/bisques/queue_listener.rb#L34-L44 | train |
mirrec/token_field | lib/token_field/form_builder.rb | TokenField.FormBuilder.token_field | def token_field(attribute_name, options = {})
association_type = @object.send(attribute_name).respond_to?(:each) ? :many : :one
model_name = options.fetch(:model) { attribute_name.to_s.gsub(/_ids?/, "") }.to_s
association = attribute_name.to_s.gsub(/_ids?/, "").to_sym
token_url = options.fetch(:token_url) { "/#{model_name.pluralize}/token.json" }
token_url_is_function = options.fetch(:token_url_is_function) { false }
append_to_id = options[:append_to_id]
token_method = options.fetch(:token_method) { :to_token }
token_limit = nil
token_limit = 1 if association_type == :one
id = @object.send(:id)
html_id = "#{@object_name}_#{attribute_name.to_s}"
if append_to_id == :id && id
html_id << "_#{id}"
elsif append_to_id && append_to_id != :id
html_id << "_#{append_to_id}"
end
html_id = html_id.parameterize.underscore
results = []
if association_type == :one && @object.public_send(association)
results << @object.public_send(association)
elsif association_type == :many && @object.public_send(association.to_s.pluralize).count > 0
@object.public_send(association.to_s.pluralize).each { |record| results << record }
end
data_pre = results.map{ |result| result.public_send(token_method) }
value = data_pre.map{ |row| row[:id] }.join(',')
on_add = options[:on_add] ? "#{options[:on_add]}" : "false"
on_delete = options[:on_delete] ? "#{options[:on_delete]}" : "false"
token_url = "'#{token_url}'" unless token_url_is_function
js_content = "
jQuery.noConflict();
jQuery(function() {
jQuery('##{html_id}').tokenInput(#{token_url}, {
crossDomain: false,
tokenLimit: #{token_limit.nil? ? "null" : token_limit.to_i},
preventDuplicates: true,
prePopulate: jQuery('##{attribute_name}').data('pre'),
theme: 'facebook',
hintText: '"+t('helpers.token_field.hint_text')+"',
searchingText: '"+t('helpers.token_field.searching_text')+"',
noResultsText: '"+t('helpers.token_field.no_results_text')+"',
onAdd: "+on_add+",
onDelete: "+on_delete+"
});
});
"
script = content_tag(:script, js_content.html_safe, :type => Mime::JS)
text_field("#{attribute_name}", "data-pre" => data_pre.to_json, :value => value, :id => html_id) + script
end | ruby | def token_field(attribute_name, options = {})
association_type = @object.send(attribute_name).respond_to?(:each) ? :many : :one
model_name = options.fetch(:model) { attribute_name.to_s.gsub(/_ids?/, "") }.to_s
association = attribute_name.to_s.gsub(/_ids?/, "").to_sym
token_url = options.fetch(:token_url) { "/#{model_name.pluralize}/token.json" }
token_url_is_function = options.fetch(:token_url_is_function) { false }
append_to_id = options[:append_to_id]
token_method = options.fetch(:token_method) { :to_token }
token_limit = nil
token_limit = 1 if association_type == :one
id = @object.send(:id)
html_id = "#{@object_name}_#{attribute_name.to_s}"
if append_to_id == :id && id
html_id << "_#{id}"
elsif append_to_id && append_to_id != :id
html_id << "_#{append_to_id}"
end
html_id = html_id.parameterize.underscore
results = []
if association_type == :one && @object.public_send(association)
results << @object.public_send(association)
elsif association_type == :many && @object.public_send(association.to_s.pluralize).count > 0
@object.public_send(association.to_s.pluralize).each { |record| results << record }
end
data_pre = results.map{ |result| result.public_send(token_method) }
value = data_pre.map{ |row| row[:id] }.join(',')
on_add = options[:on_add] ? "#{options[:on_add]}" : "false"
on_delete = options[:on_delete] ? "#{options[:on_delete]}" : "false"
token_url = "'#{token_url}'" unless token_url_is_function
js_content = "
jQuery.noConflict();
jQuery(function() {
jQuery('##{html_id}').tokenInput(#{token_url}, {
crossDomain: false,
tokenLimit: #{token_limit.nil? ? "null" : token_limit.to_i},
preventDuplicates: true,
prePopulate: jQuery('##{attribute_name}').data('pre'),
theme: 'facebook',
hintText: '"+t('helpers.token_field.hint_text')+"',
searchingText: '"+t('helpers.token_field.searching_text')+"',
noResultsText: '"+t('helpers.token_field.no_results_text')+"',
onAdd: "+on_add+",
onDelete: "+on_delete+"
});
});
"
script = content_tag(:script, js_content.html_safe, :type => Mime::JS)
text_field("#{attribute_name}", "data-pre" => data_pre.to_json, :value => value, :id => html_id) + script
end | [
"def",
"token_field",
"(",
"attribute_name",
",",
"options",
"=",
"{",
"}",
")",
"association_type",
"=",
"@object",
".",
"send",
"(",
"attribute_name",
")",
".",
"respond_to?",
"(",
":each",
")",
"?",
":many",
":",
":one",
"model_name",
"=",
"options",
".",
"fetch",
"(",
":model",
")",
"{",
"attribute_name",
".",
"to_s",
".",
"gsub",
"(",
"/",
"/",
",",
"\"\"",
")",
"}",
".",
"to_s",
"association",
"=",
"attribute_name",
".",
"to_s",
".",
"gsub",
"(",
"/",
"/",
",",
"\"\"",
")",
".",
"to_sym",
"token_url",
"=",
"options",
".",
"fetch",
"(",
":token_url",
")",
"{",
"\"/#{model_name.pluralize}/token.json\"",
"}",
"token_url_is_function",
"=",
"options",
".",
"fetch",
"(",
":token_url_is_function",
")",
"{",
"false",
"}",
"append_to_id",
"=",
"options",
"[",
":append_to_id",
"]",
"token_method",
"=",
"options",
".",
"fetch",
"(",
":token_method",
")",
"{",
":to_token",
"}",
"token_limit",
"=",
"nil",
"token_limit",
"=",
"1",
"if",
"association_type",
"==",
":one",
"id",
"=",
"@object",
".",
"send",
"(",
":id",
")",
"html_id",
"=",
"\"#{@object_name}_#{attribute_name.to_s}\"",
"if",
"append_to_id",
"==",
":id",
"&&",
"id",
"html_id",
"<<",
"\"_#{id}\"",
"elsif",
"append_to_id",
"&&",
"append_to_id",
"!=",
":id",
"html_id",
"<<",
"\"_#{append_to_id}\"",
"end",
"html_id",
"=",
"html_id",
".",
"parameterize",
".",
"underscore",
"results",
"=",
"[",
"]",
"if",
"association_type",
"==",
":one",
"&&",
"@object",
".",
"public_send",
"(",
"association",
")",
"results",
"<<",
"@object",
".",
"public_send",
"(",
"association",
")",
"elsif",
"association_type",
"==",
":many",
"&&",
"@object",
".",
"public_send",
"(",
"association",
".",
"to_s",
".",
"pluralize",
")",
".",
"count",
">",
"0",
"@object",
".",
"public_send",
"(",
"association",
".",
"to_s",
".",
"pluralize",
")",
".",
"each",
"{",
"|",
"record",
"|",
"results",
"<<",
"record",
"}",
"end",
"data_pre",
"=",
"results",
".",
"map",
"{",
"|",
"result",
"|",
"result",
".",
"public_send",
"(",
"token_method",
")",
"}",
"value",
"=",
"data_pre",
".",
"map",
"{",
"|",
"row",
"|",
"row",
"[",
":id",
"]",
"}",
".",
"join",
"(",
"','",
")",
"on_add",
"=",
"options",
"[",
":on_add",
"]",
"?",
"\"#{options[:on_add]}\"",
":",
"\"false\"",
"on_delete",
"=",
"options",
"[",
":on_delete",
"]",
"?",
"\"#{options[:on_delete]}\"",
":",
"\"false\"",
"token_url",
"=",
"\"'#{token_url}'\"",
"unless",
"token_url_is_function",
"js_content",
"=",
"\" jQuery.noConflict(); jQuery(function() { jQuery('##{html_id}').tokenInput(#{token_url}, { crossDomain: false, tokenLimit: #{token_limit.nil? ? \"null\" : token_limit.to_i}, preventDuplicates: true, prePopulate: jQuery('##{attribute_name}').data('pre'), theme: 'facebook', hintText: '\"",
"+",
"t",
"(",
"'helpers.token_field.hint_text'",
")",
"+",
"\"', searchingText: '\"",
"+",
"t",
"(",
"'helpers.token_field.searching_text'",
")",
"+",
"\"', noResultsText: '\"",
"+",
"t",
"(",
"'helpers.token_field.no_results_text'",
")",
"+",
"\"', onAdd: \"",
"+",
"on_add",
"+",
"\", onDelete: \"",
"+",
"on_delete",
"+",
"\" }); }); \"",
"script",
"=",
"content_tag",
"(",
":script",
",",
"js_content",
".",
"html_safe",
",",
":type",
"=>",
"Mime",
"::",
"JS",
")",
"text_field",
"(",
"\"#{attribute_name}\"",
",",
"\"data-pre\"",
"=>",
"data_pre",
".",
"to_json",
",",
":value",
"=>",
"value",
",",
":id",
"=>",
"html_id",
")",
"+",
"script",
"end"
] | form_for helper for token input with jquery token input plugin
for has_many and belongs_to association
http://railscasts.com/episodes/258-token-fields
http://loopj.com/jquery-tokeninput/
helper will render standard text field input with javascript.
javascript will change standard input to token field input
EXAMPLE
class Category < ActiveRecord::Base
attr_accessible :name, :parent_id, :product_ids
has_many :products
# method for converting array of categories to array of hashes in format that token input accepts
def to_token
{:id => id, :name => name}
end
end
class Product < ActiveRecord::Base
attr_accessible :name, :category_id
belongs_to :category
end
class CategoriesController < ApplicationController
# action for autocomplete
def token
categories = Category.where("categories.name like ?", "%#{params[:q]}%")
respond_to do |format|
format.json { render :json => categories.map(&:to_token) }
end
end
# rest of the class
end
then in routes add route for token ajax call
MyApplication::Application.routes.draw do
resources :categories do
collection do
get :token # route for token -> token_categories_path
end
end
end
then in view we call token_field
token_field input will be default expects, that Category model exists
<%= form_for @product do |f| %>
<%= f.token_field :category_id %>
<% end %>
possible options:
in case the association roles where given like this
class Product < ActiveRecord::Base
belongs_to :cat, :class_name => 'Category', :foreign_key => :cat_id
end
then right model need to be specified
<%= f.token_field :cat_id, :model => :category %>
We can use token_input also for mapping category to products
we will use ActiveRecord method product_ids which be default return array of ids from association
<%= form_for @category do |f| %>
<%= f.token_field :product_ids %>
<% end %>
in model we have to change product_ids= method like this
class Category < ActiveRecord::Base
has_many :products
alias_method :product_ids_old=, :product_ids=
def product_ids=(ids)
ids = ids.split(",").map(&:to_i) if ids.is_a?(String)
self.product_ids_old=ids
end
# rest of the class...
end | [
"form_for",
"helper",
"for",
"token",
"input",
"with",
"jquery",
"token",
"input",
"plugin",
"for",
"has_many",
"and",
"belongs_to",
"association"
] | a4abed90ef18890afeac5363b4f791e66f3fe62e | https://github.com/mirrec/token_field/blob/a4abed90ef18890afeac5363b4f791e66f3fe62e/lib/token_field/form_builder.rb#L94-L151 | train |
26fe/tree.rb | lib/tree_rb/input_plugins/html_page/dom_walker.rb | TreeRb.DomWalker.process_node | def process_node(node, level=1)
entries = node.children
@visitor.enter_node(node)
entries.each do |entry|
unless is_leaf?(entry)
process_node(entry, level+1)
else
@visitor.visit_leaf(entry)
end
end
@visitor.exit_node(node)
end | ruby | def process_node(node, level=1)
entries = node.children
@visitor.enter_node(node)
entries.each do |entry|
unless is_leaf?(entry)
process_node(entry, level+1)
else
@visitor.visit_leaf(entry)
end
end
@visitor.exit_node(node)
end | [
"def",
"process_node",
"(",
"node",
",",
"level",
"=",
"1",
")",
"entries",
"=",
"node",
".",
"children",
"@visitor",
".",
"enter_node",
"(",
"node",
")",
"entries",
".",
"each",
"do",
"|",
"entry",
"|",
"unless",
"is_leaf?",
"(",
"entry",
")",
"process_node",
"(",
"entry",
",",
"level",
"+",
"1",
")",
"else",
"@visitor",
".",
"visit_leaf",
"(",
"entry",
")",
"end",
"end",
"@visitor",
".",
"exit_node",
"(",
"node",
")",
"end"
] | recurse on nodes | [
"recurse",
"on",
"nodes"
] | 5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b | https://github.com/26fe/tree.rb/blob/5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b/lib/tree_rb/input_plugins/html_page/dom_walker.rb#L18-L29 | train |
marcmo/cxxproject | lib/cxxproject/buildingblocks/linkable.rb | Cxxproject.Linkable.handle_whole_archive | def handle_whole_archive(building_block, res, linker, flag)
if is_whole_archive(building_block)
res.push(flag) if flag and !flag.empty?
end
end | ruby | def handle_whole_archive(building_block, res, linker, flag)
if is_whole_archive(building_block)
res.push(flag) if flag and !flag.empty?
end
end | [
"def",
"handle_whole_archive",
"(",
"building_block",
",",
"res",
",",
"linker",
",",
"flag",
")",
"if",
"is_whole_archive",
"(",
"building_block",
")",
"res",
".",
"push",
"(",
"flag",
")",
"if",
"flag",
"and",
"!",
"flag",
".",
"empty?",
"end",
"end"
] | res the array with command line arguments that is used as result
linker the linker hash
sym the symbol that is used to fish out a value from the linker | [
"res",
"the",
"array",
"with",
"command",
"line",
"arguments",
"that",
"is",
"used",
"as",
"result",
"linker",
"the",
"linker",
"hash",
"sym",
"the",
"symbol",
"that",
"is",
"used",
"to",
"fish",
"out",
"a",
"value",
"from",
"the",
"linker"
] | 3740a09d6a143acd96bde3d2ff79055a6b810da4 | https://github.com/marcmo/cxxproject/blob/3740a09d6a143acd96bde3d2ff79055a6b810da4/lib/cxxproject/buildingblocks/linkable.rb#L152-L156 | train |
marcmo/cxxproject | lib/cxxproject/buildingblocks/linkable.rb | Cxxproject.Linkable.convert_to_rake | def convert_to_rake()
object_multitask = prepare_tasks_for_objects()
res = typed_file_task get_rake_task_type(), get_task_name => object_multitask do
cmd = calc_command_line
Dir.chdir(@project_dir) do
mapfileStr = @mapfile ? " >#{@mapfile}" : ""
rd, wr = IO.pipe
cmdLinePrint = cmd
printCmd(cmdLinePrint, "Linking #{executable_name}", false) #OK
cmd << {
:out=> @mapfile ? "#{@mapfile}" : wr, # > xy.map
:err=>wr
}
sp = spawn(*cmd)
cmd.pop
# for console print
cmd << " >#{@mapfile}" if @mapfile
consoleOutput = ProcessHelper.readOutput(sp, rd, wr)
process_result(cmdLinePrint, consoleOutput, @tcs[:LINKER][:ERROR_PARSER], nil)
check_config_file()
post_link_hook(@tcs[:LINKER])
end
end
res.tags = tags
res.immediate_output = true
res.enhance(@config_files)
res.enhance([@project_dir + "/" + @linker_script]) if @linker_script
add_output_dir_dependency(get_task_name, res, true)
add_grouping_tasks(get_task_name)
setup_rake_dependencies(res, object_multitask)
# check that all source libs are checked even if they are not a real rake dependency (can happen if "build this project only")
begin
libChecker = task get_task_name+"LibChecker" do
if File.exists?(get_task_name) # otherwise the task will be executed anyway
all_dependencies.each do |bb|
if bb and StaticLibrary === bb
f = bb.get_task_name # = abs path of library
if not File.exists?(f) or File.mtime(f) > File.mtime(get_task_name)
def res.needed?
true
end
break
end
end
end
end
end
rescue
def res.needed?
true
end
end
libChecker.transparent_timestamp = true
res.enhance([libChecker])
return res
end | ruby | def convert_to_rake()
object_multitask = prepare_tasks_for_objects()
res = typed_file_task get_rake_task_type(), get_task_name => object_multitask do
cmd = calc_command_line
Dir.chdir(@project_dir) do
mapfileStr = @mapfile ? " >#{@mapfile}" : ""
rd, wr = IO.pipe
cmdLinePrint = cmd
printCmd(cmdLinePrint, "Linking #{executable_name}", false) #OK
cmd << {
:out=> @mapfile ? "#{@mapfile}" : wr, # > xy.map
:err=>wr
}
sp = spawn(*cmd)
cmd.pop
# for console print
cmd << " >#{@mapfile}" if @mapfile
consoleOutput = ProcessHelper.readOutput(sp, rd, wr)
process_result(cmdLinePrint, consoleOutput, @tcs[:LINKER][:ERROR_PARSER], nil)
check_config_file()
post_link_hook(@tcs[:LINKER])
end
end
res.tags = tags
res.immediate_output = true
res.enhance(@config_files)
res.enhance([@project_dir + "/" + @linker_script]) if @linker_script
add_output_dir_dependency(get_task_name, res, true)
add_grouping_tasks(get_task_name)
setup_rake_dependencies(res, object_multitask)
# check that all source libs are checked even if they are not a real rake dependency (can happen if "build this project only")
begin
libChecker = task get_task_name+"LibChecker" do
if File.exists?(get_task_name) # otherwise the task will be executed anyway
all_dependencies.each do |bb|
if bb and StaticLibrary === bb
f = bb.get_task_name # = abs path of library
if not File.exists?(f) or File.mtime(f) > File.mtime(get_task_name)
def res.needed?
true
end
break
end
end
end
end
end
rescue
def res.needed?
true
end
end
libChecker.transparent_timestamp = true
res.enhance([libChecker])
return res
end | [
"def",
"convert_to_rake",
"(",
")",
"object_multitask",
"=",
"prepare_tasks_for_objects",
"(",
")",
"res",
"=",
"typed_file_task",
"get_rake_task_type",
"(",
")",
",",
"get_task_name",
"=>",
"object_multitask",
"do",
"cmd",
"=",
"calc_command_line",
"Dir",
".",
"chdir",
"(",
"@project_dir",
")",
"do",
"mapfileStr",
"=",
"@mapfile",
"?",
"\" >#{@mapfile}\"",
":",
"\"\"",
"rd",
",",
"wr",
"=",
"IO",
".",
"pipe",
"cmdLinePrint",
"=",
"cmd",
"printCmd",
"(",
"cmdLinePrint",
",",
"\"Linking #{executable_name}\"",
",",
"false",
")",
"cmd",
"<<",
"{",
":out",
"=>",
"@mapfile",
"?",
"\"#{@mapfile}\"",
":",
"wr",
",",
":err",
"=>",
"wr",
"}",
"sp",
"=",
"spawn",
"(",
"*",
"cmd",
")",
"cmd",
".",
"pop",
"cmd",
"<<",
"\" >#{@mapfile}\"",
"if",
"@mapfile",
"consoleOutput",
"=",
"ProcessHelper",
".",
"readOutput",
"(",
"sp",
",",
"rd",
",",
"wr",
")",
"process_result",
"(",
"cmdLinePrint",
",",
"consoleOutput",
",",
"@tcs",
"[",
":LINKER",
"]",
"[",
":ERROR_PARSER",
"]",
",",
"nil",
")",
"check_config_file",
"(",
")",
"post_link_hook",
"(",
"@tcs",
"[",
":LINKER",
"]",
")",
"end",
"end",
"res",
".",
"tags",
"=",
"tags",
"res",
".",
"immediate_output",
"=",
"true",
"res",
".",
"enhance",
"(",
"@config_files",
")",
"res",
".",
"enhance",
"(",
"[",
"@project_dir",
"+",
"\"/\"",
"+",
"@linker_script",
"]",
")",
"if",
"@linker_script",
"add_output_dir_dependency",
"(",
"get_task_name",
",",
"res",
",",
"true",
")",
"add_grouping_tasks",
"(",
"get_task_name",
")",
"setup_rake_dependencies",
"(",
"res",
",",
"object_multitask",
")",
"begin",
"libChecker",
"=",
"task",
"get_task_name",
"+",
"\"LibChecker\"",
"do",
"if",
"File",
".",
"exists?",
"(",
"get_task_name",
")",
"all_dependencies",
".",
"each",
"do",
"|",
"bb",
"|",
"if",
"bb",
"and",
"StaticLibrary",
"===",
"bb",
"f",
"=",
"bb",
".",
"get_task_name",
"if",
"not",
"File",
".",
"exists?",
"(",
"f",
")",
"or",
"File",
".",
"mtime",
"(",
"f",
")",
">",
"File",
".",
"mtime",
"(",
"get_task_name",
")",
"def",
"res",
".",
"needed?",
"true",
"end",
"break",
"end",
"end",
"end",
"end",
"end",
"rescue",
"def",
"res",
".",
"needed?",
"true",
"end",
"end",
"libChecker",
".",
"transparent_timestamp",
"=",
"true",
"res",
".",
"enhance",
"(",
"[",
"libChecker",
"]",
")",
"return",
"res",
"end"
] | create a task that will link an executable from a set of object files | [
"create",
"a",
"task",
"that",
"will",
"link",
"an",
"executable",
"from",
"a",
"set",
"of",
"object",
"files"
] | 3740a09d6a143acd96bde3d2ff79055a6b810da4 | https://github.com/marcmo/cxxproject/blob/3740a09d6a143acd96bde3d2ff79055a6b810da4/lib/cxxproject/buildingblocks/linkable.rb#L181-L241 | train |
marcmo/cxxproject | lib/cxxproject/buildingblocks/linkable.rb | Cxxproject.SharedLibrary.post_link_hook | def post_link_hook(linker)
basic_name = get_basic_name(linker)
soname = get_soname(linker)
symlink_lib_to basic_name
symlink_lib_to soname
end | ruby | def post_link_hook(linker)
basic_name = get_basic_name(linker)
soname = get_soname(linker)
symlink_lib_to basic_name
symlink_lib_to soname
end | [
"def",
"post_link_hook",
"(",
"linker",
")",
"basic_name",
"=",
"get_basic_name",
"(",
"linker",
")",
"soname",
"=",
"get_soname",
"(",
"linker",
")",
"symlink_lib_to",
"basic_name",
"symlink_lib_to",
"soname",
"end"
] | Some symbolic links
ln -s libfoo.so libfoo.1.2.so
ln -s libfoo.1.so libfoo.1.2.so | [
"Some",
"symbolic",
"links",
"ln",
"-",
"s",
"libfoo",
".",
"so",
"libfoo",
".",
"1",
".",
"2",
".",
"so",
"ln",
"-",
"s",
"libfoo",
".",
"1",
".",
"so",
"libfoo",
".",
"1",
".",
"2",
".",
"so"
] | 3740a09d6a143acd96bde3d2ff79055a6b810da4 | https://github.com/marcmo/cxxproject/blob/3740a09d6a143acd96bde3d2ff79055a6b810da4/lib/cxxproject/buildingblocks/linkable.rb#L355-L360 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.