id
int32 0
24.9k
| repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
|
---|---|---|---|---|---|---|---|---|---|---|---|
22,800 | benedikt/layer-ruby | lib/layer/conversation.rb | Layer.Conversation.contents | def contents
RelationProxy.new(self, Content, [Operations::Create, Operations::Find]) do
def create(mime_type, file, client = self.client)
response = client.post(url, {}, {
'Upload-Content-Type' => mime_type,
'Upload-Content-Length' => file.size
})
attributes = response.merge('size' => file.size, 'mime_type' => mime_type)
Content.from_response(attributes, client).tap do |content|
content.upload(file)
end
end
end
end | ruby | def contents
RelationProxy.new(self, Content, [Operations::Create, Operations::Find]) do
def create(mime_type, file, client = self.client)
response = client.post(url, {}, {
'Upload-Content-Type' => mime_type,
'Upload-Content-Length' => file.size
})
attributes = response.merge('size' => file.size, 'mime_type' => mime_type)
Content.from_response(attributes, client).tap do |content|
content.upload(file)
end
end
end
end | [
"def",
"contents",
"RelationProxy",
".",
"new",
"(",
"self",
",",
"Content",
",",
"[",
"Operations",
"::",
"Create",
",",
"Operations",
"::",
"Find",
"]",
")",
"do",
"def",
"create",
"(",
"mime_type",
",",
"file",
",",
"client",
"=",
"self",
".",
"client",
")",
"response",
"=",
"client",
".",
"post",
"(",
"url",
",",
"{",
"}",
",",
"{",
"'Upload-Content-Type'",
"=>",
"mime_type",
",",
"'Upload-Content-Length'",
"=>",
"file",
".",
"size",
"}",
")",
"attributes",
"=",
"response",
".",
"merge",
"(",
"'size'",
"=>",
"file",
".",
"size",
",",
"'mime_type'",
"=>",
"mime_type",
")",
"Content",
".",
"from_response",
"(",
"attributes",
",",
"client",
")",
".",
"tap",
"do",
"|",
"content",
"|",
"content",
".",
"upload",
"(",
"file",
")",
"end",
"end",
"end",
"end"
] | Allows creating and finding of the conversation's rich content
@return [Layer::RelationProxy] the conversation's rich content
@!macro platform-api | [
"Allows",
"creating",
"and",
"finding",
"of",
"the",
"conversation",
"s",
"rich",
"content"
] | 3eafc708f71961b98de86d01080ee5970e8482ef | https://github.com/benedikt/layer-ruby/blob/3eafc708f71961b98de86d01080ee5970e8482ef/lib/layer/conversation.rb#L66-L81 |
22,801 | benedikt/layer-ruby | lib/layer/conversation.rb | Layer.Conversation.delete | def delete(options = {})
options = { mode: :my_devices }.merge(options)
client.delete(url, {}, { params: options })
end | ruby | def delete(options = {})
options = { mode: :my_devices }.merge(options)
client.delete(url, {}, { params: options })
end | [
"def",
"delete",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"mode",
":",
":my_devices",
"}",
".",
"merge",
"(",
"options",
")",
"client",
".",
"delete",
"(",
"url",
",",
"{",
"}",
",",
"{",
"params",
":",
"options",
"}",
")",
"end"
] | Deletes the conversation, removing it from the user's devices by default
@param options [Hash] the options for the delete request (REST API only: `leave: true/false`, `mode: all_participants/my_devices`)
@raise [Layer::Exceptions::Exception] a subclass of Layer::Exceptions::Exception describing the error | [
"Deletes",
"the",
"conversation",
"removing",
"it",
"from",
"the",
"user",
"s",
"devices",
"by",
"default"
] | 3eafc708f71961b98de86d01080ee5970e8482ef | https://github.com/benedikt/layer-ruby/blob/3eafc708f71961b98de86d01080ee5970e8482ef/lib/layer/conversation.rb#L124-L127 |
22,802 | nesquena/dante | lib/dante/runner.rb | Dante.Runner.execute | def execute(opts={}, &block)
parse_options
self.options.merge!(opts)
@verify_options_hook.call(self.options) if @verify_options_hook
if options.include?(:kill)
self.stop
else # create process
self.stop if options.include?(:restart)
# If a username, uid, groupname, or gid is passed,
# drop privileges accordingly.
if options[:group]
gid = options[:group].is_a?(Integer) ? options[:group] : Etc.getgrnam(options[:group]).gid
Process::GID.change_privilege(gid)
end
if options[:user]
uid = options[:user].is_a?(Integer) ? options[:user] : Etc.getpwnam(options[:user]).uid
Process::UID.change_privilege(uid)
end
@startup_command = block if block_given?
options[:daemonize] ? daemonize : start
end
end | ruby | def execute(opts={}, &block)
parse_options
self.options.merge!(opts)
@verify_options_hook.call(self.options) if @verify_options_hook
if options.include?(:kill)
self.stop
else # create process
self.stop if options.include?(:restart)
# If a username, uid, groupname, or gid is passed,
# drop privileges accordingly.
if options[:group]
gid = options[:group].is_a?(Integer) ? options[:group] : Etc.getgrnam(options[:group]).gid
Process::GID.change_privilege(gid)
end
if options[:user]
uid = options[:user].is_a?(Integer) ? options[:user] : Etc.getpwnam(options[:user]).uid
Process::UID.change_privilege(uid)
end
@startup_command = block if block_given?
options[:daemonize] ? daemonize : start
end
end | [
"def",
"execute",
"(",
"opts",
"=",
"{",
"}",
",",
"&",
"block",
")",
"parse_options",
"self",
".",
"options",
".",
"merge!",
"(",
"opts",
")",
"@verify_options_hook",
".",
"call",
"(",
"self",
".",
"options",
")",
"if",
"@verify_options_hook",
"if",
"options",
".",
"include?",
"(",
":kill",
")",
"self",
".",
"stop",
"else",
"# create process",
"self",
".",
"stop",
"if",
"options",
".",
"include?",
"(",
":restart",
")",
"# If a username, uid, groupname, or gid is passed,",
"# drop privileges accordingly.",
"if",
"options",
"[",
":group",
"]",
"gid",
"=",
"options",
"[",
":group",
"]",
".",
"is_a?",
"(",
"Integer",
")",
"?",
"options",
"[",
":group",
"]",
":",
"Etc",
".",
"getgrnam",
"(",
"options",
"[",
":group",
"]",
")",
".",
"gid",
"Process",
"::",
"GID",
".",
"change_privilege",
"(",
"gid",
")",
"end",
"if",
"options",
"[",
":user",
"]",
"uid",
"=",
"options",
"[",
":user",
"]",
".",
"is_a?",
"(",
"Integer",
")",
"?",
"options",
"[",
":user",
"]",
":",
"Etc",
".",
"getpwnam",
"(",
"options",
"[",
":user",
"]",
")",
".",
"uid",
"Process",
"::",
"UID",
".",
"change_privilege",
"(",
"uid",
")",
"end",
"@startup_command",
"=",
"block",
"if",
"block_given?",
"options",
"[",
":daemonize",
"]",
"?",
"daemonize",
":",
"start",
"end",
"end"
] | Executes the runner based on options
@runner.execute
@runner.execute { ... } | [
"Executes",
"the",
"runner",
"based",
"on",
"options"
] | 2a5be903fded5bbd44e57b5192763d9107e9d740 | https://github.com/nesquena/dante/blob/2a5be903fded5bbd44e57b5192763d9107e9d740/lib/dante/runner.rb#L49-L76 |
22,803 | nesquena/dante | lib/dante/runner.rb | Dante.Runner.stop | def stop(kill_arg=nil)
if self.daemon_running?
kill_pid(kill_arg || options[:kill])
if until_true(MAX_START_TRIES) { self.daemon_stopped? }
FileUtils.rm options[:pid_path] # Only kill if we stopped the daemon
log "Daemonized process killed after term."
else
log "Failed to kill daemonized process"
if options[:force]
kill_pid(kill_arg || options[:kill], 'KILL')
if until_true(MAX_START_TRIES) { self.daemon_stopped? }
FileUtils.rm options[:pid_path] # Only kill if we stopped the daemon
log "Daemonized process killed after kill."
end
end
end
else # not running
log "No #{@name} processes are running"
false
end
end | ruby | def stop(kill_arg=nil)
if self.daemon_running?
kill_pid(kill_arg || options[:kill])
if until_true(MAX_START_TRIES) { self.daemon_stopped? }
FileUtils.rm options[:pid_path] # Only kill if we stopped the daemon
log "Daemonized process killed after term."
else
log "Failed to kill daemonized process"
if options[:force]
kill_pid(kill_arg || options[:kill], 'KILL')
if until_true(MAX_START_TRIES) { self.daemon_stopped? }
FileUtils.rm options[:pid_path] # Only kill if we stopped the daemon
log "Daemonized process killed after kill."
end
end
end
else # not running
log "No #{@name} processes are running"
false
end
end | [
"def",
"stop",
"(",
"kill_arg",
"=",
"nil",
")",
"if",
"self",
".",
"daemon_running?",
"kill_pid",
"(",
"kill_arg",
"||",
"options",
"[",
":kill",
"]",
")",
"if",
"until_true",
"(",
"MAX_START_TRIES",
")",
"{",
"self",
".",
"daemon_stopped?",
"}",
"FileUtils",
".",
"rm",
"options",
"[",
":pid_path",
"]",
"# Only kill if we stopped the daemon",
"log",
"\"Daemonized process killed after term.\"",
"else",
"log",
"\"Failed to kill daemonized process\"",
"if",
"options",
"[",
":force",
"]",
"kill_pid",
"(",
"kill_arg",
"||",
"options",
"[",
":kill",
"]",
",",
"'KILL'",
")",
"if",
"until_true",
"(",
"MAX_START_TRIES",
")",
"{",
"self",
".",
"daemon_stopped?",
"}",
"FileUtils",
".",
"rm",
"options",
"[",
":pid_path",
"]",
"# Only kill if we stopped the daemon",
"log",
"\"Daemonized process killed after kill.\"",
"end",
"end",
"end",
"else",
"# not running",
"log",
"\"No #{@name} processes are running\"",
"false",
"end",
"end"
] | Stops a daemonized process | [
"Stops",
"a",
"daemonized",
"process"
] | 2a5be903fded5bbd44e57b5192763d9107e9d740 | https://github.com/nesquena/dante/blob/2a5be903fded5bbd44e57b5192763d9107e9d740/lib/dante/runner.rb#L127-L149 |
22,804 | nesquena/dante | lib/dante/runner.rb | Dante.Runner.daemon_running? | def daemon_running?
return false unless File.exist?(options[:pid_path])
Process.kill 0, File.read(options[:pid_path]).to_i
true
rescue Errno::ESRCH
false
end | ruby | def daemon_running?
return false unless File.exist?(options[:pid_path])
Process.kill 0, File.read(options[:pid_path]).to_i
true
rescue Errno::ESRCH
false
end | [
"def",
"daemon_running?",
"return",
"false",
"unless",
"File",
".",
"exist?",
"(",
"options",
"[",
":pid_path",
"]",
")",
"Process",
".",
"kill",
"0",
",",
"File",
".",
"read",
"(",
"options",
"[",
":pid_path",
"]",
")",
".",
"to_i",
"true",
"rescue",
"Errno",
"::",
"ESRCH",
"false",
"end"
] | Returns running for the daemonized process
self.daemon_running? | [
"Returns",
"running",
"for",
"the",
"daemonized",
"process",
"self",
".",
"daemon_running?"
] | 2a5be903fded5bbd44e57b5192763d9107e9d740 | https://github.com/nesquena/dante/blob/2a5be903fded5bbd44e57b5192763d9107e9d740/lib/dante/runner.rb#L172-L178 |
22,805 | grackorg/grack | lib/grack/git_adapter.rb | Grack.GitAdapter.handle_pack | def handle_pack(pack_type, io_in, io_out, opts = {})
args = %w{--stateless-rpc}
if opts.fetch(:advertise_refs, false)
io_out.write(advertisement_prefix(pack_type))
args << '--advertise-refs'
end
args << repository_path.to_s
command(pack_type.sub(/^git-/, ''), args, io_in, io_out)
end | ruby | def handle_pack(pack_type, io_in, io_out, opts = {})
args = %w{--stateless-rpc}
if opts.fetch(:advertise_refs, false)
io_out.write(advertisement_prefix(pack_type))
args << '--advertise-refs'
end
args << repository_path.to_s
command(pack_type.sub(/^git-/, ''), args, io_in, io_out)
end | [
"def",
"handle_pack",
"(",
"pack_type",
",",
"io_in",
",",
"io_out",
",",
"opts",
"=",
"{",
"}",
")",
"args",
"=",
"%w{",
"--stateless-rpc",
"}",
"if",
"opts",
".",
"fetch",
"(",
":advertise_refs",
",",
"false",
")",
"io_out",
".",
"write",
"(",
"advertisement_prefix",
"(",
"pack_type",
")",
")",
"args",
"<<",
"'--advertise-refs'",
"end",
"args",
"<<",
"repository_path",
".",
"to_s",
"command",
"(",
"pack_type",
".",
"sub",
"(",
"/",
"/",
",",
"''",
")",
",",
"args",
",",
"io_in",
",",
"io_out",
")",
"end"
] | Process the pack file exchange protocol.
@param [String] pack_type the type of pack exchange to perform.
@param [#read] io_in a readable, IO-like object providing client input
data.
@param [#write] io_out a writable, IO-like object sending output data to
the client.
@param [Hash] opts options to pass to the Git adapter's #handle_pack
method.
@option opts [Boolean] :advertise_refs (false) | [
"Process",
"the",
"pack",
"file",
"exchange",
"protocol",
"."
] | 603bc28193923d3cc9c2fd3c47a7176680e58728 | https://github.com/grackorg/grack/blob/603bc28193923d3cc9c2fd3c47a7176680e58728/lib/grack/git_adapter.rb#L50-L58 |
22,806 | grackorg/grack | lib/grack/git_adapter.rb | Grack.GitAdapter.command | def command(cmd, args, io_in, io_out, dir = nil)
cmd = [git_path, cmd] + args
opts = {:err => :close}
opts[:chdir] = dir unless dir.nil?
cmd << opts
IO.popen(cmd, 'r+b') do |pipe|
while ! io_in.nil? && chunk = io_in.read(READ_SIZE) do
pipe.write(chunk)
end
pipe.close_write
while chunk = pipe.read(READ_SIZE) do
io_out.write(chunk) unless io_out.nil?
end
end
end | ruby | def command(cmd, args, io_in, io_out, dir = nil)
cmd = [git_path, cmd] + args
opts = {:err => :close}
opts[:chdir] = dir unless dir.nil?
cmd << opts
IO.popen(cmd, 'r+b') do |pipe|
while ! io_in.nil? && chunk = io_in.read(READ_SIZE) do
pipe.write(chunk)
end
pipe.close_write
while chunk = pipe.read(READ_SIZE) do
io_out.write(chunk) unless io_out.nil?
end
end
end | [
"def",
"command",
"(",
"cmd",
",",
"args",
",",
"io_in",
",",
"io_out",
",",
"dir",
"=",
"nil",
")",
"cmd",
"=",
"[",
"git_path",
",",
"cmd",
"]",
"+",
"args",
"opts",
"=",
"{",
":err",
"=>",
":close",
"}",
"opts",
"[",
":chdir",
"]",
"=",
"dir",
"unless",
"dir",
".",
"nil?",
"cmd",
"<<",
"opts",
"IO",
".",
"popen",
"(",
"cmd",
",",
"'r+b'",
")",
"do",
"|",
"pipe",
"|",
"while",
"!",
"io_in",
".",
"nil?",
"&&",
"chunk",
"=",
"io_in",
".",
"read",
"(",
"READ_SIZE",
")",
"do",
"pipe",
".",
"write",
"(",
"chunk",
")",
"end",
"pipe",
".",
"close_write",
"while",
"chunk",
"=",
"pipe",
".",
"read",
"(",
"READ_SIZE",
")",
"do",
"io_out",
".",
"write",
"(",
"chunk",
")",
"unless",
"io_out",
".",
"nil?",
"end",
"end",
"end"
] | Runs the Git utilty with the given subcommand.
@param [String] cmd the Git subcommand to invoke.
@param [Array<String>] args additional arguments for the command.
@param [#read, nil] io_in a readable, IO-like source of data to write to
the Git command.
@param [#write, nil] io_out a writable, IO-like sink for output produced
by the Git command.
@param [String, nil] dir a directory to switch to before invoking the Git
command. | [
"Runs",
"the",
"Git",
"utilty",
"with",
"the",
"given",
"subcommand",
"."
] | 603bc28193923d3cc9c2fd3c47a7176680e58728 | https://github.com/grackorg/grack/blob/603bc28193923d3cc9c2fd3c47a7176680e58728/lib/grack/git_adapter.rb#L130-L144 |
22,807 | grackorg/grack | lib/grack/app.rb | Grack.App.route | def route
# Sanitize the URI:
# * Unescape escaped characters
# * Replace runs of / with a single /
path_info = Rack::Utils.unescape(request.path_info).gsub(%r{/+}, '/')
ROUTES.each do |path_matcher, verb, handler|
path_info.match(path_matcher) do |match|
@repository_uri = match[1]
@request_verb = verb
return method_not_allowed unless verb == request.request_method
return bad_request if bad_uri?(@repository_uri)
git.repository_path = root + @repository_uri
return not_found unless git.exist?
return send(handler, *match[2..-1])
end
end
not_found
end | ruby | def route
# Sanitize the URI:
# * Unescape escaped characters
# * Replace runs of / with a single /
path_info = Rack::Utils.unescape(request.path_info).gsub(%r{/+}, '/')
ROUTES.each do |path_matcher, verb, handler|
path_info.match(path_matcher) do |match|
@repository_uri = match[1]
@request_verb = verb
return method_not_allowed unless verb == request.request_method
return bad_request if bad_uri?(@repository_uri)
git.repository_path = root + @repository_uri
return not_found unless git.exist?
return send(handler, *match[2..-1])
end
end
not_found
end | [
"def",
"route",
"# Sanitize the URI:",
"# * Unescape escaped characters",
"# * Replace runs of / with a single /",
"path_info",
"=",
"Rack",
"::",
"Utils",
".",
"unescape",
"(",
"request",
".",
"path_info",
")",
".",
"gsub",
"(",
"%r{",
"}",
",",
"'/'",
")",
"ROUTES",
".",
"each",
"do",
"|",
"path_matcher",
",",
"verb",
",",
"handler",
"|",
"path_info",
".",
"match",
"(",
"path_matcher",
")",
"do",
"|",
"match",
"|",
"@repository_uri",
"=",
"match",
"[",
"1",
"]",
"@request_verb",
"=",
"verb",
"return",
"method_not_allowed",
"unless",
"verb",
"==",
"request",
".",
"request_method",
"return",
"bad_request",
"if",
"bad_uri?",
"(",
"@repository_uri",
")",
"git",
".",
"repository_path",
"=",
"root",
"+",
"@repository_uri",
"return",
"not_found",
"unless",
"git",
".",
"exist?",
"return",
"send",
"(",
"handler",
",",
"match",
"[",
"2",
"..",
"-",
"1",
"]",
")",
"end",
"end",
"not_found",
"end"
] | Routes requests to appropriate handlers. Performs request path cleanup
and several sanity checks prior to attempting to handle the request.
@return a Rack response object. | [
"Routes",
"requests",
"to",
"appropriate",
"handlers",
".",
"Performs",
"request",
"path",
"cleanup",
"and",
"several",
"sanity",
"checks",
"prior",
"to",
"attempting",
"to",
"handle",
"the",
"request",
"."
] | 603bc28193923d3cc9c2fd3c47a7176680e58728 | https://github.com/grackorg/grack/blob/603bc28193923d3cc9c2fd3c47a7176680e58728/lib/grack/app.rb#L153-L174 |
22,808 | grackorg/grack | lib/grack/app.rb | Grack.App.handle_pack | def handle_pack(pack_type)
@pack_type = pack_type
unless request.content_type == "application/x-#{@pack_type}-request" &&
valid_pack_type? && authorized?
return no_access
end
headers = {'Content-Type' => "application/x-#{@pack_type}-result"}
exchange_pack(headers, request_io_in)
end | ruby | def handle_pack(pack_type)
@pack_type = pack_type
unless request.content_type == "application/x-#{@pack_type}-request" &&
valid_pack_type? && authorized?
return no_access
end
headers = {'Content-Type' => "application/x-#{@pack_type}-result"}
exchange_pack(headers, request_io_in)
end | [
"def",
"handle_pack",
"(",
"pack_type",
")",
"@pack_type",
"=",
"pack_type",
"unless",
"request",
".",
"content_type",
"==",
"\"application/x-#{@pack_type}-request\"",
"&&",
"valid_pack_type?",
"&&",
"authorized?",
"return",
"no_access",
"end",
"headers",
"=",
"{",
"'Content-Type'",
"=>",
"\"application/x-#{@pack_type}-result\"",
"}",
"exchange_pack",
"(",
"headers",
",",
"request_io_in",
")",
"end"
] | Processes pack file exchange requests for both push and pull. Ensures
that the request is allowed and properly formatted.
@param [String] pack_type the type of pack exchange to perform per the
request.
@return a Rack response object. | [
"Processes",
"pack",
"file",
"exchange",
"requests",
"for",
"both",
"push",
"and",
"pull",
".",
"Ensures",
"that",
"the",
"request",
"is",
"allowed",
"and",
"properly",
"formatted",
"."
] | 603bc28193923d3cc9c2fd3c47a7176680e58728 | https://github.com/grackorg/grack/blob/603bc28193923d3cc9c2fd3c47a7176680e58728/lib/grack/app.rb#L184-L193 |
22,809 | grackorg/grack | lib/grack/app.rb | Grack.App.info_refs | def info_refs
@pack_type = request.params['service']
return no_access unless authorized?
if @pack_type.nil?
git.update_server_info
send_file(
git.file('info/refs'), 'text/plain; charset=utf-8', hdr_nocache
)
elsif valid_pack_type?
headers = hdr_nocache
headers['Content-Type'] = "application/x-#{@pack_type}-advertisement"
exchange_pack(headers, nil, {:advertise_refs => true})
else
not_found
end
end | ruby | def info_refs
@pack_type = request.params['service']
return no_access unless authorized?
if @pack_type.nil?
git.update_server_info
send_file(
git.file('info/refs'), 'text/plain; charset=utf-8', hdr_nocache
)
elsif valid_pack_type?
headers = hdr_nocache
headers['Content-Type'] = "application/x-#{@pack_type}-advertisement"
exchange_pack(headers, nil, {:advertise_refs => true})
else
not_found
end
end | [
"def",
"info_refs",
"@pack_type",
"=",
"request",
".",
"params",
"[",
"'service'",
"]",
"return",
"no_access",
"unless",
"authorized?",
"if",
"@pack_type",
".",
"nil?",
"git",
".",
"update_server_info",
"send_file",
"(",
"git",
".",
"file",
"(",
"'info/refs'",
")",
",",
"'text/plain; charset=utf-8'",
",",
"hdr_nocache",
")",
"elsif",
"valid_pack_type?",
"headers",
"=",
"hdr_nocache",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"\"application/x-#{@pack_type}-advertisement\"",
"exchange_pack",
"(",
"headers",
",",
"nil",
",",
"{",
":advertise_refs",
"=>",
"true",
"}",
")",
"else",
"not_found",
"end",
"end"
] | Processes requests for the list of refs for the requested repository.
This works for both Smart HTTP clients and basic ones. For basic clients,
the Git adapter is used to update the +info/refs+ file which is then
served to the clients. For Smart HTTP clients, the more efficient pack
file exchange mechanism is used.
@return a Rack response object. | [
"Processes",
"requests",
"for",
"the",
"list",
"of",
"refs",
"for",
"the",
"requested",
"repository",
"."
] | 603bc28193923d3cc9c2fd3c47a7176680e58728 | https://github.com/grackorg/grack/blob/603bc28193923d3cc9c2fd3c47a7176680e58728/lib/grack/app.rb#L204-L220 |
22,810 | grackorg/grack | lib/grack/app.rb | Grack.App.send_file | def send_file(streamer, content_type, headers = {})
return not_found if streamer.nil?
headers['Content-Type'] = content_type
headers['Last-Modified'] = streamer.mtime.httpdate
[200, headers, streamer]
end | ruby | def send_file(streamer, content_type, headers = {})
return not_found if streamer.nil?
headers['Content-Type'] = content_type
headers['Last-Modified'] = streamer.mtime.httpdate
[200, headers, streamer]
end | [
"def",
"send_file",
"(",
"streamer",
",",
"content_type",
",",
"headers",
"=",
"{",
"}",
")",
"return",
"not_found",
"if",
"streamer",
".",
"nil?",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"content_type",
"headers",
"[",
"'Last-Modified'",
"]",
"=",
"streamer",
".",
"mtime",
".",
"httpdate",
"[",
"200",
",",
"headers",
",",
"streamer",
"]",
"end"
] | Produces a Rack response that wraps the output from the Git adapter.
A 404 response is produced if _streamer_ is +nil+. Otherwise a 200
response is produced with _streamer_ as the response body.
@param [FileStreamer,IOStreamer] streamer a provider of content for the
response body.
@param [String] content_type the MIME type of the content.
@param [Hash] headers additional headers to include in the response.
@return a Rack response object. | [
"Produces",
"a",
"Rack",
"response",
"that",
"wraps",
"the",
"output",
"from",
"the",
"Git",
"adapter",
"."
] | 603bc28193923d3cc9c2fd3c47a7176680e58728 | https://github.com/grackorg/grack/blob/603bc28193923d3cc9c2fd3c47a7176680e58728/lib/grack/app.rb#L311-L318 |
22,811 | grackorg/grack | lib/grack/app.rb | Grack.App.exchange_pack | def exchange_pack(headers, io_in, opts = {})
Rack::Response.new([], 200, headers).finish do |response|
git.handle_pack(pack_type, io_in, response, opts)
end
end | ruby | def exchange_pack(headers, io_in, opts = {})
Rack::Response.new([], 200, headers).finish do |response|
git.handle_pack(pack_type, io_in, response, opts)
end
end | [
"def",
"exchange_pack",
"(",
"headers",
",",
"io_in",
",",
"opts",
"=",
"{",
"}",
")",
"Rack",
"::",
"Response",
".",
"new",
"(",
"[",
"]",
",",
"200",
",",
"headers",
")",
".",
"finish",
"do",
"|",
"response",
"|",
"git",
".",
"handle_pack",
"(",
"pack_type",
",",
"io_in",
",",
"response",
",",
"opts",
")",
"end",
"end"
] | Opens a tunnel for the pack file exchange protocol between the client and
the Git adapter.
@param [Hash] headers headers to provide in the Rack response.
@param [#read] io_in a readable, IO-like object providing client input
data.
@param [Hash] opts options to pass to the Git adapter's #handle_pack
method.
@return a Rack response object. | [
"Opens",
"a",
"tunnel",
"for",
"the",
"pack",
"file",
"exchange",
"protocol",
"between",
"the",
"client",
"and",
"the",
"Git",
"adapter",
"."
] | 603bc28193923d3cc9c2fd3c47a7176680e58728 | https://github.com/grackorg/grack/blob/603bc28193923d3cc9c2fd3c47a7176680e58728/lib/grack/app.rb#L331-L335 |
22,812 | grackorg/grack | lib/grack/app.rb | Grack.App.bad_uri? | def bad_uri?(path)
invalid_segments = %w{. ..}
path.split('/').any? { |segment| invalid_segments.include?(segment) }
end | ruby | def bad_uri?(path)
invalid_segments = %w{. ..}
path.split('/').any? { |segment| invalid_segments.include?(segment) }
end | [
"def",
"bad_uri?",
"(",
"path",
")",
"invalid_segments",
"=",
"%w{",
".",
"..",
"}",
"path",
".",
"split",
"(",
"'/'",
")",
".",
"any?",
"{",
"|",
"segment",
"|",
"invalid_segments",
".",
"include?",
"(",
"segment",
")",
"}",
"end"
] | Determines whether or not _path_ is an acceptable URI.
@param [String] path the path part of the request URI.
@return [Boolean] +true+ if the requested path is considered invalid;
otherwise, +false+. | [
"Determines",
"whether",
"or",
"not",
"_path_",
"is",
"an",
"acceptable",
"URI",
"."
] | 603bc28193923d3cc9c2fd3c47a7176680e58728 | https://github.com/grackorg/grack/blob/603bc28193923d3cc9c2fd3c47a7176680e58728/lib/grack/app.rb#L362-L365 |
22,813 | swcraig/oxford-dictionary | lib/oxford_dictionary/request.rb | OxfordDictionary.Request.search_endpoint_url | def search_endpoint_url(params)
params[:prefix] || params[:prefix] = false
append = ''
if params[:translations]
append = "/translations=#{params[:translations]}"
params.delete(:translations)
end
"#{append}?#{create_query_string(params, '&')}"
end | ruby | def search_endpoint_url(params)
params[:prefix] || params[:prefix] = false
append = ''
if params[:translations]
append = "/translations=#{params[:translations]}"
params.delete(:translations)
end
"#{append}?#{create_query_string(params, '&')}"
end | [
"def",
"search_endpoint_url",
"(",
"params",
")",
"params",
"[",
":prefix",
"]",
"||",
"params",
"[",
":prefix",
"]",
"=",
"false",
"append",
"=",
"''",
"if",
"params",
"[",
":translations",
"]",
"append",
"=",
"\"/translations=#{params[:translations]}\"",
"params",
".",
"delete",
"(",
":translations",
")",
"end",
"\"#{append}?#{create_query_string(params, '&')}\"",
"end"
] | The search endpoint has a slightly different url structure | [
"The",
"search",
"endpoint",
"has",
"a",
"slightly",
"different",
"url",
"structure"
] | bcd1d9f8a81781726e846e33e2f36ac71ffa8c18 | https://github.com/swcraig/oxford-dictionary/blob/bcd1d9f8a81781726e846e33e2f36ac71ffa8c18/lib/oxford_dictionary/request.rb#L69-L77 |
22,814 | noboru-i/danger-checkstyle_format | lib/checkstyle_format/plugin.rb | Danger.DangerCheckstyleFormat.report | def report(file, inline_mode = true)
raise "Please specify file name." if file.empty?
raise "No checkstyle file was found at #{file}" unless File.exist? file
errors = parse(File.read(file))
send_comment(errors, inline_mode)
end | ruby | def report(file, inline_mode = true)
raise "Please specify file name." if file.empty?
raise "No checkstyle file was found at #{file}" unless File.exist? file
errors = parse(File.read(file))
send_comment(errors, inline_mode)
end | [
"def",
"report",
"(",
"file",
",",
"inline_mode",
"=",
"true",
")",
"raise",
"\"Please specify file name.\"",
"if",
"file",
".",
"empty?",
"raise",
"\"No checkstyle file was found at #{file}\"",
"unless",
"File",
".",
"exist?",
"file",
"errors",
"=",
"parse",
"(",
"File",
".",
"read",
"(",
"file",
")",
")",
"send_comment",
"(",
"errors",
",",
"inline_mode",
")",
"end"
] | Report checkstyle warnings
@return [void] | [
"Report",
"checkstyle",
"warnings"
] | 3b8656c834d7ff9522f5d912fbe223b008914d64 | https://github.com/noboru-i/danger-checkstyle_format/blob/3b8656c834d7ff9522f5d912fbe223b008914d64/lib/checkstyle_format/plugin.rb#L28-L34 |
22,815 | noboru-i/danger-checkstyle_format | lib/checkstyle_format/plugin.rb | Danger.DangerCheckstyleFormat.report_by_text | def report_by_text(text, inline_mode = true)
raise "Please specify xml text." if text.empty?
errors = parse(text)
send_comment(errors, inline_mode)
end | ruby | def report_by_text(text, inline_mode = true)
raise "Please specify xml text." if text.empty?
errors = parse(text)
send_comment(errors, inline_mode)
end | [
"def",
"report_by_text",
"(",
"text",
",",
"inline_mode",
"=",
"true",
")",
"raise",
"\"Please specify xml text.\"",
"if",
"text",
".",
"empty?",
"errors",
"=",
"parse",
"(",
"text",
")",
"send_comment",
"(",
"errors",
",",
"inline_mode",
")",
"end"
] | Report checkstyle warnings by XML text
@return [void] | [
"Report",
"checkstyle",
"warnings",
"by",
"XML",
"text"
] | 3b8656c834d7ff9522f5d912fbe223b008914d64 | https://github.com/noboru-i/danger-checkstyle_format/blob/3b8656c834d7ff9522f5d912fbe223b008914d64/lib/checkstyle_format/plugin.rb#L39-L44 |
22,816 | jistr/mobvious | lib/mobvious/manager.rb | Mobvious.Manager.call | def call(env)
request = Rack::Request.new(env)
assign_device_type(request)
status, headers, body = @app.call(env)
response = Rack::Response.new(body, status, headers)
response_callback(request, response)
[status, headers, body]
end | ruby | def call(env)
request = Rack::Request.new(env)
assign_device_type(request)
status, headers, body = @app.call(env)
response = Rack::Response.new(body, status, headers)
response_callback(request, response)
[status, headers, body]
end | [
"def",
"call",
"(",
"env",
")",
"request",
"=",
"Rack",
"::",
"Request",
".",
"new",
"(",
"env",
")",
"assign_device_type",
"(",
"request",
")",
"status",
",",
"headers",
",",
"body",
"=",
"@app",
".",
"call",
"(",
"env",
")",
"response",
"=",
"Rack",
"::",
"Response",
".",
"new",
"(",
"body",
",",
"status",
",",
"headers",
")",
"response_callback",
"(",
"request",
",",
"response",
")",
"[",
"status",
",",
"headers",
",",
"body",
"]",
"end"
] | Create a new instance of this rack middleware.
@param app Rack application that can be called.
Perform the device type detection and call the inner Rack application.
@param env Rack environment.
@return rack response `[status, headers, body]` | [
"Create",
"a",
"new",
"instance",
"of",
"this",
"rack",
"middleware",
"."
] | 085190877fe184bc380497915a74207d575f5e77 | https://github.com/jistr/mobvious/blob/085190877fe184bc380497915a74207d575f5e77/lib/mobvious/manager.rb#L21-L31 |
22,817 | aviator/aviator | lib/aviator/core/session.rb | Aviator.Session.authenticate | def authenticate(opts={}, &block)
block ||= lambda do |params|
config[:auth_credentials].each do |key, value|
begin
params[key] = value
rescue NameError => e
raise NameError.new("Unknown param name '#{key}'")
end
end
end
response = auth_service.request(config[:auth_service][:request].to_sym, opts, &block)
if [200, 201].include? response.status
@auth_response = Hashish.new({
:headers => response.headers,
:body => response.body
})
update_services_session_data
else
raise AuthenticationError.new(response.body)
end
self
end | ruby | def authenticate(opts={}, &block)
block ||= lambda do |params|
config[:auth_credentials].each do |key, value|
begin
params[key] = value
rescue NameError => e
raise NameError.new("Unknown param name '#{key}'")
end
end
end
response = auth_service.request(config[:auth_service][:request].to_sym, opts, &block)
if [200, 201].include? response.status
@auth_response = Hashish.new({
:headers => response.headers,
:body => response.body
})
update_services_session_data
else
raise AuthenticationError.new(response.body)
end
self
end | [
"def",
"authenticate",
"(",
"opts",
"=",
"{",
"}",
",",
"&",
"block",
")",
"block",
"||=",
"lambda",
"do",
"|",
"params",
"|",
"config",
"[",
":auth_credentials",
"]",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"begin",
"params",
"[",
"key",
"]",
"=",
"value",
"rescue",
"NameError",
"=>",
"e",
"raise",
"NameError",
".",
"new",
"(",
"\"Unknown param name '#{key}'\"",
")",
"end",
"end",
"end",
"response",
"=",
"auth_service",
".",
"request",
"(",
"config",
"[",
":auth_service",
"]",
"[",
":request",
"]",
".",
"to_sym",
",",
"opts",
",",
"block",
")",
"if",
"[",
"200",
",",
"201",
"]",
".",
"include?",
"response",
".",
"status",
"@auth_response",
"=",
"Hashish",
".",
"new",
"(",
"{",
":headers",
"=>",
"response",
".",
"headers",
",",
":body",
"=>",
"response",
".",
"body",
"}",
")",
"update_services_session_data",
"else",
"raise",
"AuthenticationError",
".",
"new",
"(",
"response",
".",
"body",
")",
"end",
"self",
"end"
] | Create a new Session instance.
<b>Initialize with a config file</b>
Aviator::Session.new(:config_file => 'path/to/aviator.yml', :environment => :production)
In the above example, the config file must have the following form:
production:
provider: openstack
auth_service:
name: identity
host_uri: 'http://my.openstackenv.org:5000'
request: create_token
validator: list_tenants
api_version: v2
auth_credentials:
username: myusername
password: mypassword
tenant_name: myproject
<b>SIDENOTE:</b> For more information about the <tt>validator</tt> member, see Session#validate.
Once the session has been instantiated, you may authenticate against the
provider as follows:
session.authenticate
The members you put under <tt>auth_credentials</tt> will depend on the request
class you declare under <tt>auth_service:request</tt> and what parameters it
accepts. To know more about a request class and its parameters, you can use
the CLI tool <tt>aviator describe</tt> or view the request definition file directly.
If writing the <tt>auth_credentials</tt> in the config file is not acceptable,
you may omit it and just supply the credentials at runtime. For example:
session.authenticate do |params|
params.username = ARGV[0]
params.password = ARGV[1]
params.tenant_name = ARGV[2]
end
See Session#authenticate for more info.
Note that while the example config file above only has one environment (production),
you can declare an arbitrary number of environments in your config file. Shifting
between environments is as simple as changing the <tt>:environment</tt> to refer to that.
<b>Initialize with an in-memory hash</b>
You can create an in-memory hash with a structure similar to the config file but without
the environment name. For example:
configuration = {
:provider => 'openstack',
:auth_service => {
:name => 'identity',
:host_uri => 'http://devstack:5000/v2.0',
:request => 'create_token',
:validator => 'list_tenants'
}
}
Supply this to the initializer using the <tt>:config</tt> option. For example:
Aviator::Session.new(:config => configuration)
<b>Initialize with a session dump</b>
You can create a new Session instance using a dump from another instance. For example:
session_dump = session1.dump
session2 = Aviator::Session.new(:session_dump => session_dump)
However, Session.load is cleaner and recommended over this method.
<b>Optionally supply a log file</b>
In all forms above, you may optionally add a <tt>:log_file</tt> option to make
Aviator write all HTTP calls to the given path. For example:
Aviator::Session.new(:config_file => 'path/to/aviator.yml', :environment => :production, :log_file => 'path/to/log')
Authenticates against the backend provider using the auth_service request class
declared in the session's configuration. Please see Session.new for more information
on declaring the request class to use for authentication.
<b>Request params block</b>
If the auth_service request class accepts parameters, you may supply that
as a block and it will be directly passed to the request. For example:
session = Aviator::Session.new(:config => config)
session.authenticate do |params|
params.username = username
params.password = password
params.tenant_name = project
end
If your configuration happens to have an <tt>auth_credentials</tt> in it, those
will be overridden by this block.
<b>Treat parameters as a hash</b>
You can also treat the params struct like a hash with the attribute
names as the keys. For example, we can rewrite the above as:
session = Aviator::Session.new(:config => config)
session.authenticate do |params|
params[:username] = username
params[:password] = password
params[:tenant_name] = project
end
Keys can be symbols or strings.
<b>Use a hash argument instead of a block</b>
You may also provide request params as an argument instead of a block. This is
especially useful if you want to mock Aviator as it's easier to specify ordinary
argument expectations over blocks. Further rewriting the example above,
we end up with:
session = Aviator::Session.new(:config => config)
session.authenticate :params => {
:username => username,
:password => password,
:tenant_name => project
}
If both <tt>:params</tt> and a block are provided, the <tt>:params</tt>
values will be used and the block ignored.
<b>Success requirements</b>
Expects an HTTP status 200 or 201 response from the backend. Any other
status is treated as a failure. | [
"Create",
"a",
"new",
"Session",
"instance",
"."
] | 96fd83c1a131bc0532fc89696935173506c891fa | https://github.com/aviator/aviator/blob/96fd83c1a131bc0532fc89696935173506c891fa/lib/aviator/core/session.rb#L212-L235 |
22,818 | mhgbrown/cached_resource | lib/cached_resource/configuration.rb | CachedResource.Configuration.sample_range | def sample_range(range, seed=nil)
srand seed if seed
rand * (range.end - range.begin) + range.begin
end | ruby | def sample_range(range, seed=nil)
srand seed if seed
rand * (range.end - range.begin) + range.begin
end | [
"def",
"sample_range",
"(",
"range",
",",
"seed",
"=",
"nil",
")",
"srand",
"seed",
"if",
"seed",
"rand",
"*",
"(",
"range",
".",
"end",
"-",
"range",
".",
"begin",
")",
"+",
"range",
".",
"begin",
"end"
] | Choose a random value from within the given range, optionally
seeded by seed. | [
"Choose",
"a",
"random",
"value",
"from",
"within",
"the",
"given",
"range",
"optionally",
"seeded",
"by",
"seed",
"."
] | 0a69e2abf6d9432655b2795f081065ac4b6735b6 | https://github.com/mhgbrown/cached_resource/blob/0a69e2abf6d9432655b2795f081065ac4b6735b6/lib/cached_resource/configuration.rb#L67-L70 |
22,819 | voloko/twitter-stream | lib/twitter/json_stream.rb | Twitter.JSONStream.receive_stream_data | def receive_stream_data(data)
begin
@buffer.extract(data).each do |line|
parse_stream_line(line)
end
@stream = ''
rescue => e
receive_error("#{e.class}: " + [e.message, e.backtrace].flatten.join("\n\t"))
close_connection
return
end
end | ruby | def receive_stream_data(data)
begin
@buffer.extract(data).each do |line|
parse_stream_line(line)
end
@stream = ''
rescue => e
receive_error("#{e.class}: " + [e.message, e.backtrace].flatten.join("\n\t"))
close_connection
return
end
end | [
"def",
"receive_stream_data",
"(",
"data",
")",
"begin",
"@buffer",
".",
"extract",
"(",
"data",
")",
".",
"each",
"do",
"|",
"line",
"|",
"parse_stream_line",
"(",
"line",
")",
"end",
"@stream",
"=",
"''",
"rescue",
"=>",
"e",
"receive_error",
"(",
"\"#{e.class}: \"",
"+",
"[",
"e",
".",
"message",
",",
"e",
".",
"backtrace",
"]",
".",
"flatten",
".",
"join",
"(",
"\"\\n\\t\"",
")",
")",
"close_connection",
"return",
"end",
"end"
] | Called every time a chunk of data is read from the connection once it has
been opened and after the headers have been processed. | [
"Called",
"every",
"time",
"a",
"chunk",
"of",
"data",
"is",
"read",
"from",
"the",
"connection",
"once",
"it",
"has",
"been",
"opened",
"and",
"after",
"the",
"headers",
"have",
"been",
"processed",
"."
] | 45ce963d56e6e383f0e001522a817e7538438f71 | https://github.com/voloko/twitter-stream/blob/45ce963d56e6e383f0e001522a817e7538438f71/lib/twitter/json_stream.rb#L226-L237 |
22,820 | voloko/twitter-stream | lib/twitter/json_stream.rb | Twitter.JSONStream.oauth_header | def oauth_header
uri = uri_base + @options[:path].to_s
# The hash SimpleOAuth accepts is slightly different from that of
# ROAuth. To preserve backward compatability, fix the cache here
# so that the arguments passed in don't need to change.
oauth = {
:consumer_key => @options[:oauth][:consumer_key],
:consumer_secret => @options[:oauth][:consumer_secret],
:token => @options[:oauth][:access_key],
:token_secret => @options[:oauth][:access_secret]
}
data = ['POST', 'PUT'].include?(@options[:method]) ? params : {}
SimpleOAuth::Header.new(@options[:method], uri, data, oauth)
end | ruby | def oauth_header
uri = uri_base + @options[:path].to_s
# The hash SimpleOAuth accepts is slightly different from that of
# ROAuth. To preserve backward compatability, fix the cache here
# so that the arguments passed in don't need to change.
oauth = {
:consumer_key => @options[:oauth][:consumer_key],
:consumer_secret => @options[:oauth][:consumer_secret],
:token => @options[:oauth][:access_key],
:token_secret => @options[:oauth][:access_secret]
}
data = ['POST', 'PUT'].include?(@options[:method]) ? params : {}
SimpleOAuth::Header.new(@options[:method], uri, data, oauth)
end | [
"def",
"oauth_header",
"uri",
"=",
"uri_base",
"+",
"@options",
"[",
":path",
"]",
".",
"to_s",
"# The hash SimpleOAuth accepts is slightly different from that of",
"# ROAuth. To preserve backward compatability, fix the cache here",
"# so that the arguments passed in don't need to change.",
"oauth",
"=",
"{",
":consumer_key",
"=>",
"@options",
"[",
":oauth",
"]",
"[",
":consumer_key",
"]",
",",
":consumer_secret",
"=>",
"@options",
"[",
":oauth",
"]",
"[",
":consumer_secret",
"]",
",",
":token",
"=>",
"@options",
"[",
":oauth",
"]",
"[",
":access_key",
"]",
",",
":token_secret",
"=>",
"@options",
"[",
":oauth",
"]",
"[",
":access_secret",
"]",
"}",
"data",
"=",
"[",
"'POST'",
",",
"'PUT'",
"]",
".",
"include?",
"(",
"@options",
"[",
":method",
"]",
")",
"?",
"params",
":",
"{",
"}",
"SimpleOAuth",
"::",
"Header",
".",
"new",
"(",
"@options",
"[",
":method",
"]",
",",
"uri",
",",
"data",
",",
"oauth",
")",
"end"
] | URL and request components
:filters => %w(miama lebron jesus)
:oauth => {
:consumer_key => [key],
:consumer_secret => [token],
:access_key => [access key],
:access_secret => [access secret]
} | [
"URL",
"and",
"request",
"components"
] | 45ce963d56e6e383f0e001522a817e7538438f71 | https://github.com/voloko/twitter-stream/blob/45ce963d56e6e383f0e001522a817e7538438f71/lib/twitter/json_stream.rb#L322-L338 |
22,821 | voloko/twitter-stream | lib/twitter/json_stream.rb | Twitter.JSONStream.params | def params
flat = {}
@options[:params].merge( :track => @options[:filters] ).each do |param, val|
next if val.to_s.empty? || (val.respond_to?(:empty?) && val.empty?)
val = val.join(",") if val.respond_to?(:join)
flat[param.to_s] = val.to_s
end
flat
end | ruby | def params
flat = {}
@options[:params].merge( :track => @options[:filters] ).each do |param, val|
next if val.to_s.empty? || (val.respond_to?(:empty?) && val.empty?)
val = val.join(",") if val.respond_to?(:join)
flat[param.to_s] = val.to_s
end
flat
end | [
"def",
"params",
"flat",
"=",
"{",
"}",
"@options",
"[",
":params",
"]",
".",
"merge",
"(",
":track",
"=>",
"@options",
"[",
":filters",
"]",
")",
".",
"each",
"do",
"|",
"param",
",",
"val",
"|",
"next",
"if",
"val",
".",
"to_s",
".",
"empty?",
"||",
"(",
"val",
".",
"respond_to?",
"(",
":empty?",
")",
"&&",
"val",
".",
"empty?",
")",
"val",
"=",
"val",
".",
"join",
"(",
"\",\"",
")",
"if",
"val",
".",
"respond_to?",
"(",
":join",
")",
"flat",
"[",
"param",
".",
"to_s",
"]",
"=",
"val",
".",
"to_s",
"end",
"flat",
"end"
] | Normalized query hash of escaped string keys and escaped string values
nil values are skipped | [
"Normalized",
"query",
"hash",
"of",
"escaped",
"string",
"keys",
"and",
"escaped",
"string",
"values",
"nil",
"values",
"are",
"skipped"
] | 45ce963d56e6e383f0e001522a817e7538438f71 | https://github.com/voloko/twitter-stream/blob/45ce963d56e6e383f0e001522a817e7538438f71/lib/twitter/json_stream.rb#L347-L355 |
22,822 | crowdin/crowdin-api | lib/crowdin-api/methods.rb | Crowdin.API.add_file | def add_file(files, params = {})
params[:files] = Hash[files.map { |f| [
f[:dest] || raise(ArgumentError, "'`:dest`' is required"),
::File.open(f[:source] || raise(ArgumentError, "'`:source` is required'"))
] }]
params[:titles] = Hash[files.map { |f| [f[:dest], f[:title]] }]
params[:titles].delete_if { |_, v| v.nil? }
params[:export_patterns] = Hash[files.map { |f| [f[:dest], f[:export_pattern]] }]
params[:export_patterns].delete_if { |_, v| v.nil? }
params.delete_if { |_, v| v.respond_to?(:empty?) ? !!v.empty? : !v }
request(
:method => :post,
:path => "/api/project/#{@project_id}/add-file",
:query => params,
)
end | ruby | def add_file(files, params = {})
params[:files] = Hash[files.map { |f| [
f[:dest] || raise(ArgumentError, "'`:dest`' is required"),
::File.open(f[:source] || raise(ArgumentError, "'`:source` is required'"))
] }]
params[:titles] = Hash[files.map { |f| [f[:dest], f[:title]] }]
params[:titles].delete_if { |_, v| v.nil? }
params[:export_patterns] = Hash[files.map { |f| [f[:dest], f[:export_pattern]] }]
params[:export_patterns].delete_if { |_, v| v.nil? }
params.delete_if { |_, v| v.respond_to?(:empty?) ? !!v.empty? : !v }
request(
:method => :post,
:path => "/api/project/#{@project_id}/add-file",
:query => params,
)
end | [
"def",
"add_file",
"(",
"files",
",",
"params",
"=",
"{",
"}",
")",
"params",
"[",
":files",
"]",
"=",
"Hash",
"[",
"files",
".",
"map",
"{",
"|",
"f",
"|",
"[",
"f",
"[",
":dest",
"]",
"||",
"raise",
"(",
"ArgumentError",
",",
"\"'`:dest`' is required\"",
")",
",",
"::",
"File",
".",
"open",
"(",
"f",
"[",
":source",
"]",
"||",
"raise",
"(",
"ArgumentError",
",",
"\"'`:source` is required'\"",
")",
")",
"]",
"}",
"]",
"params",
"[",
":titles",
"]",
"=",
"Hash",
"[",
"files",
".",
"map",
"{",
"|",
"f",
"|",
"[",
"f",
"[",
":dest",
"]",
",",
"f",
"[",
":title",
"]",
"]",
"}",
"]",
"params",
"[",
":titles",
"]",
".",
"delete_if",
"{",
"|",
"_",
",",
"v",
"|",
"v",
".",
"nil?",
"}",
"params",
"[",
":export_patterns",
"]",
"=",
"Hash",
"[",
"files",
".",
"map",
"{",
"|",
"f",
"|",
"[",
"f",
"[",
":dest",
"]",
",",
"f",
"[",
":export_pattern",
"]",
"]",
"}",
"]",
"params",
"[",
":export_patterns",
"]",
".",
"delete_if",
"{",
"|",
"_",
",",
"v",
"|",
"v",
".",
"nil?",
"}",
"params",
".",
"delete_if",
"{",
"|",
"_",
",",
"v",
"|",
"v",
".",
"respond_to?",
"(",
":empty?",
")",
"?",
"!",
"!",
"v",
".",
"empty?",
":",
"!",
"v",
"}",
"request",
"(",
":method",
"=>",
":post",
",",
":path",
"=>",
"\"/api/project/#{@project_id}/add-file\"",
",",
":query",
"=>",
"params",
",",
")",
"end"
] | Add new file to Crowdin project.
== Parameters
files - Array of files that should be added to Crowdin project.
file is a Hash { :dest, :source, :title, :export_pattern }
* :dest - file name with path in Crowdin project (required)
* :source - path for uploaded file (required)
* :title - title in Crowdin UI (optional)
* :export_pattern - Resulted file name (optional)
Optional:
* :branch - a branch name.
If the branch is not exists Crowdin will be return an error:
"error":{
"code":8,
"message":"File was not found"
}
== Request
POST https://api.crowdin.com/api/project/{project-identifier}/add-file?key={project-key} | [
"Add",
"new",
"file",
"to",
"Crowdin",
"project",
"."
] | e36e09dd5474244e69b664c8ec33c627cd20c299 | https://github.com/crowdin/crowdin-api/blob/e36e09dd5474244e69b664c8ec33c627cd20c299/lib/crowdin-api/methods.rb#L33-L52 |
22,823 | crowdin/crowdin-api | lib/crowdin-api/methods.rb | Crowdin.API.update_file | def update_file(files, params = {})
params[:files] = Hash[files.map { |f|
dest = f[:dest] || raise(ArgumentError, "'`:dest` is required'")
source = ::File.open(f[:source] || raise(ArgumentError, "'`:source` is required'"))
source.define_singleton_method(:original_filename) do
dest
end
[dest, source]
}]
params[:titles] = Hash[files.map { |f| [f[:dest], f[:title]] }]
params[:titles].delete_if { |_, v| v.nil? }
params[:export_patterns] = Hash[files.map { |f| [f[:dest], f[:export_pattern]] }]
params[:export_patterns].delete_if { |_, v| v.nil? }
params.delete_if { |_, v| v.respond_to?(:empty?) ? !!v.empty? : !v }
request(
:method => :post,
:path => "/api/project/#{@project_id}/update-file",
:query => params,
)
end | ruby | def update_file(files, params = {})
params[:files] = Hash[files.map { |f|
dest = f[:dest] || raise(ArgumentError, "'`:dest` is required'")
source = ::File.open(f[:source] || raise(ArgumentError, "'`:source` is required'"))
source.define_singleton_method(:original_filename) do
dest
end
[dest, source]
}]
params[:titles] = Hash[files.map { |f| [f[:dest], f[:title]] }]
params[:titles].delete_if { |_, v| v.nil? }
params[:export_patterns] = Hash[files.map { |f| [f[:dest], f[:export_pattern]] }]
params[:export_patterns].delete_if { |_, v| v.nil? }
params.delete_if { |_, v| v.respond_to?(:empty?) ? !!v.empty? : !v }
request(
:method => :post,
:path => "/api/project/#{@project_id}/update-file",
:query => params,
)
end | [
"def",
"update_file",
"(",
"files",
",",
"params",
"=",
"{",
"}",
")",
"params",
"[",
":files",
"]",
"=",
"Hash",
"[",
"files",
".",
"map",
"{",
"|",
"f",
"|",
"dest",
"=",
"f",
"[",
":dest",
"]",
"||",
"raise",
"(",
"ArgumentError",
",",
"\"'`:dest` is required'\"",
")",
"source",
"=",
"::",
"File",
".",
"open",
"(",
"f",
"[",
":source",
"]",
"||",
"raise",
"(",
"ArgumentError",
",",
"\"'`:source` is required'\"",
")",
")",
"source",
".",
"define_singleton_method",
"(",
":original_filename",
")",
"do",
"dest",
"end",
"[",
"dest",
",",
"source",
"]",
"}",
"]",
"params",
"[",
":titles",
"]",
"=",
"Hash",
"[",
"files",
".",
"map",
"{",
"|",
"f",
"|",
"[",
"f",
"[",
":dest",
"]",
",",
"f",
"[",
":title",
"]",
"]",
"}",
"]",
"params",
"[",
":titles",
"]",
".",
"delete_if",
"{",
"|",
"_",
",",
"v",
"|",
"v",
".",
"nil?",
"}",
"params",
"[",
":export_patterns",
"]",
"=",
"Hash",
"[",
"files",
".",
"map",
"{",
"|",
"f",
"|",
"[",
"f",
"[",
":dest",
"]",
",",
"f",
"[",
":export_pattern",
"]",
"]",
"}",
"]",
"params",
"[",
":export_patterns",
"]",
".",
"delete_if",
"{",
"|",
"_",
",",
"v",
"|",
"v",
".",
"nil?",
"}",
"params",
".",
"delete_if",
"{",
"|",
"_",
",",
"v",
"|",
"v",
".",
"respond_to?",
"(",
":empty?",
")",
"?",
"!",
"!",
"v",
".",
"empty?",
":",
"!",
"v",
"}",
"request",
"(",
":method",
"=>",
":post",
",",
":path",
"=>",
"\"/api/project/#{@project_id}/update-file\"",
",",
":query",
"=>",
"params",
",",
")",
"end"
] | Upload fresh version of your localization file to Crowdin.
== Parameters
files - Array of files that should be updated in Crowdin project.
file is a Hash { :dest, :source }
* :dest - file name with path in Crowdin project (required)
* :source - path for uploaded file (required)
* :title - title in Crowdin UI (optional)
* :export_pattern - Resulted file name (optional)
Optional:
* :branch - a branch name
== Request
POST https://api.crowdin.com/api/project/{project-identifier}/update-file?key={project-key} | [
"Upload",
"fresh",
"version",
"of",
"your",
"localization",
"file",
"to",
"Crowdin",
"."
] | e36e09dd5474244e69b664c8ec33c627cd20c299 | https://github.com/crowdin/crowdin-api/blob/e36e09dd5474244e69b664c8ec33c627cd20c299/lib/crowdin-api/methods.rb#L72-L95 |
22,824 | crowdin/crowdin-api | lib/crowdin-api/methods.rb | Crowdin.API.upload_translation | def upload_translation(files, language, params = {})
params[:files] = Hash[files.map { |f| [
f[:dest] || raise(ArgumentError, "`:dest` is required"),
::File.open(f[:source] || raise(ArgumentError, "`:source` is required"))
] }]
params[:language] = language
request(
:method => :post,
:path => "/api/project/#{@project_id}/upload-translation",
:query => params,
)
end | ruby | def upload_translation(files, language, params = {})
params[:files] = Hash[files.map { |f| [
f[:dest] || raise(ArgumentError, "`:dest` is required"),
::File.open(f[:source] || raise(ArgumentError, "`:source` is required"))
] }]
params[:language] = language
request(
:method => :post,
:path => "/api/project/#{@project_id}/upload-translation",
:query => params,
)
end | [
"def",
"upload_translation",
"(",
"files",
",",
"language",
",",
"params",
"=",
"{",
"}",
")",
"params",
"[",
":files",
"]",
"=",
"Hash",
"[",
"files",
".",
"map",
"{",
"|",
"f",
"|",
"[",
"f",
"[",
":dest",
"]",
"||",
"raise",
"(",
"ArgumentError",
",",
"\"`:dest` is required\"",
")",
",",
"::",
"File",
".",
"open",
"(",
"f",
"[",
":source",
"]",
"||",
"raise",
"(",
"ArgumentError",
",",
"\"`:source` is required\"",
")",
")",
"]",
"}",
"]",
"params",
"[",
":language",
"]",
"=",
"language",
"request",
"(",
":method",
"=>",
":post",
",",
":path",
"=>",
"\"/api/project/#{@project_id}/upload-translation\"",
",",
":query",
"=>",
"params",
",",
")",
"end"
] | Upload existing translations to your Crowdin project.
== Parameters
files - Array of files that should be added to Crowdin project.
file is a Hash { :dest, :source }
* :dest - file name with path in Crowdin project (required)
* :source - path for uploaded file (required)
language - Target language. With a single call it's possible to upload translations for several
files but only into one of the languages. (required)
Optional:
* :import_duplicates (default: false)
* :import_eq_suggestions (default: false)
* :auto_approve_imported (default: false)
* :branch - a branch name
== Request
POST https://api.crowdin.com/api/project/{project-identifier}/upload-translation?key={project-key} | [
"Upload",
"existing",
"translations",
"to",
"your",
"Crowdin",
"project",
"."
] | e36e09dd5474244e69b664c8ec33c627cd20c299 | https://github.com/crowdin/crowdin-api/blob/e36e09dd5474244e69b664c8ec33c627cd20c299/lib/crowdin-api/methods.rb#L118-L131 |
22,825 | crowdin/crowdin-api | lib/crowdin-api.rb | Crowdin.API.request | def request(params, &block)
# Returns a query hash with non nil values.
params[:query].reject! { |_, value| value.nil? } if params[:query]
case params[:method]
when :post
query = @connection.options.merge(params[:query] || {})
@connection[params[:path]].post(query) { |response, _, _|
@response = response
}
when :get
query = @connection.options[:params].merge(params[:query] || {})
@connection[params[:path]].get(:params => query) { |response, _, _|
@response = response
}
end
log.debug("args: #{@response.request.args}") if log
if @response.headers[:content_disposition]
filename = params[:output] || @response.headers[:content_disposition][/attachment; filename="(.+?)"/, 1]
body = @response.body
file = open(filename, 'wb')
file.write(body)
file.close
return true
else
doc = JSON.load(@response.body)
log.debug("body: #{doc}") if log
if doc.kind_of?(Hash) && doc['success'] == false
code = doc['error']['code']
message = doc['error']['message']
error = Crowdin::API::Errors::Error.new(code, message)
raise(error)
else
return doc
end
end
end | ruby | def request(params, &block)
# Returns a query hash with non nil values.
params[:query].reject! { |_, value| value.nil? } if params[:query]
case params[:method]
when :post
query = @connection.options.merge(params[:query] || {})
@connection[params[:path]].post(query) { |response, _, _|
@response = response
}
when :get
query = @connection.options[:params].merge(params[:query] || {})
@connection[params[:path]].get(:params => query) { |response, _, _|
@response = response
}
end
log.debug("args: #{@response.request.args}") if log
if @response.headers[:content_disposition]
filename = params[:output] || @response.headers[:content_disposition][/attachment; filename="(.+?)"/, 1]
body = @response.body
file = open(filename, 'wb')
file.write(body)
file.close
return true
else
doc = JSON.load(@response.body)
log.debug("body: #{doc}") if log
if doc.kind_of?(Hash) && doc['success'] == false
code = doc['error']['code']
message = doc['error']['message']
error = Crowdin::API::Errors::Error.new(code, message)
raise(error)
else
return doc
end
end
end | [
"def",
"request",
"(",
"params",
",",
"&",
"block",
")",
"# Returns a query hash with non nil values.",
"params",
"[",
":query",
"]",
".",
"reject!",
"{",
"|",
"_",
",",
"value",
"|",
"value",
".",
"nil?",
"}",
"if",
"params",
"[",
":query",
"]",
"case",
"params",
"[",
":method",
"]",
"when",
":post",
"query",
"=",
"@connection",
".",
"options",
".",
"merge",
"(",
"params",
"[",
":query",
"]",
"||",
"{",
"}",
")",
"@connection",
"[",
"params",
"[",
":path",
"]",
"]",
".",
"post",
"(",
"query",
")",
"{",
"|",
"response",
",",
"_",
",",
"_",
"|",
"@response",
"=",
"response",
"}",
"when",
":get",
"query",
"=",
"@connection",
".",
"options",
"[",
":params",
"]",
".",
"merge",
"(",
"params",
"[",
":query",
"]",
"||",
"{",
"}",
")",
"@connection",
"[",
"params",
"[",
":path",
"]",
"]",
".",
"get",
"(",
":params",
"=>",
"query",
")",
"{",
"|",
"response",
",",
"_",
",",
"_",
"|",
"@response",
"=",
"response",
"}",
"end",
"log",
".",
"debug",
"(",
"\"args: #{@response.request.args}\"",
")",
"if",
"log",
"if",
"@response",
".",
"headers",
"[",
":content_disposition",
"]",
"filename",
"=",
"params",
"[",
":output",
"]",
"||",
"@response",
".",
"headers",
"[",
":content_disposition",
"]",
"[",
"/",
"/",
",",
"1",
"]",
"body",
"=",
"@response",
".",
"body",
"file",
"=",
"open",
"(",
"filename",
",",
"'wb'",
")",
"file",
".",
"write",
"(",
"body",
")",
"file",
".",
"close",
"return",
"true",
"else",
"doc",
"=",
"JSON",
".",
"load",
"(",
"@response",
".",
"body",
")",
"log",
".",
"debug",
"(",
"\"body: #{doc}\"",
")",
"if",
"log",
"if",
"doc",
".",
"kind_of?",
"(",
"Hash",
")",
"&&",
"doc",
"[",
"'success'",
"]",
"==",
"false",
"code",
"=",
"doc",
"[",
"'error'",
"]",
"[",
"'code'",
"]",
"message",
"=",
"doc",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
"error",
"=",
"Crowdin",
"::",
"API",
"::",
"Errors",
"::",
"Error",
".",
"new",
"(",
"code",
",",
"message",
")",
"raise",
"(",
"error",
")",
"else",
"return",
"doc",
"end",
"end",
"end"
] | Create a new API object using the given parameters.
@param [String] api_key the authentication API key can be found on the project settings page
@param [String] project_id the project identifier.
@param [String] account_key the account API Key
@param [String] base_url the url of the Crowdin API | [
"Create",
"a",
"new",
"API",
"object",
"using",
"the",
"given",
"parameters",
"."
] | e36e09dd5474244e69b664c8ec33c627cd20c299 | https://github.com/crowdin/crowdin-api/blob/e36e09dd5474244e69b664c8ec33c627cd20c299/lib/crowdin-api.rb#L72-L112 |
22,826 | locaweb/heartcheck | lib/heartcheck/app.rb | Heartcheck.App.call | def call(env)
req = Rack::Request.new(env)
[200, { 'Content-Type' => 'application/json' }, [dispatch_action(req)]]
rescue Heartcheck::Errors::RoutingError
[404, { 'Content-Type' => 'application/json' }, ['Not found']]
end | ruby | def call(env)
req = Rack::Request.new(env)
[200, { 'Content-Type' => 'application/json' }, [dispatch_action(req)]]
rescue Heartcheck::Errors::RoutingError
[404, { 'Content-Type' => 'application/json' }, ['Not found']]
end | [
"def",
"call",
"(",
"env",
")",
"req",
"=",
"Rack",
"::",
"Request",
".",
"new",
"(",
"env",
")",
"[",
"200",
",",
"{",
"'Content-Type'",
"=>",
"'application/json'",
"}",
",",
"[",
"dispatch_action",
"(",
"req",
")",
"]",
"]",
"rescue",
"Heartcheck",
"::",
"Errors",
"::",
"RoutingError",
"[",
"404",
",",
"{",
"'Content-Type'",
"=>",
"'application/json'",
"}",
",",
"[",
"'Not found'",
"]",
"]",
"end"
] | Sets up the rack application.
@param app [RackApp] is a rack app where
heartcheck is included.
@return [void]
Sets up the rack application.
@param env [Hash] is an instance of Hash
that includes CGI-like headers.
@return [Array] must be an array that contains
- The HTTP response code
- A Hash of headers
- The response body, which must respond to each | [
"Sets",
"up",
"the",
"rack",
"application",
"."
] | b1ee73c8a1498f1de28f494c4272cb4698e71e26 | https://github.com/locaweb/heartcheck/blob/b1ee73c8a1498f1de28f494c4272cb4698e71e26/lib/heartcheck/app.rb#L43-L49 |
22,827 | locaweb/heartcheck | lib/heartcheck/app.rb | Heartcheck.App.dispatch_action | def dispatch_action(req)
controller = ROUTE_TO_CONTROLLER[req.path_info]
fail Heartcheck::Errors::RoutingError if controller.nil?
Logger.info "Start [#{controller}] from #{req.ip} at #{Time.now}"
controller.new.index.tap do |_|
Logger.info "End [#{controller}]\n"
end
end | ruby | def dispatch_action(req)
controller = ROUTE_TO_CONTROLLER[req.path_info]
fail Heartcheck::Errors::RoutingError if controller.nil?
Logger.info "Start [#{controller}] from #{req.ip} at #{Time.now}"
controller.new.index.tap do |_|
Logger.info "End [#{controller}]\n"
end
end | [
"def",
"dispatch_action",
"(",
"req",
")",
"controller",
"=",
"ROUTE_TO_CONTROLLER",
"[",
"req",
".",
"path_info",
"]",
"fail",
"Heartcheck",
"::",
"Errors",
"::",
"RoutingError",
"if",
"controller",
".",
"nil?",
"Logger",
".",
"info",
"\"Start [#{controller}] from #{req.ip} at #{Time.now}\"",
"controller",
".",
"new",
".",
"index",
".",
"tap",
"do",
"|",
"_",
"|",
"Logger",
".",
"info",
"\"End [#{controller}]\\n\"",
"end",
"end"
] | Find a controller to espefic path
and call the index method
@param req [Rack::Request] an instance of request
@return [String] a response body | [
"Find",
"a",
"controller",
"to",
"espefic",
"path",
"and",
"call",
"the",
"index",
"method"
] | b1ee73c8a1498f1de28f494c4272cb4698e71e26 | https://github.com/locaweb/heartcheck/blob/b1ee73c8a1498f1de28f494c4272cb4698e71e26/lib/heartcheck/app.rb#L59-L68 |
22,828 | czarneckid/redis_pagination | lib/redis_pagination/paginator.rb | RedisPagination.Paginator.paginate | def paginate(key, options = {})
type = RedisPagination.redis.type(key)
case type
when 'list'
RedisPagination::Paginator::ListPaginator.new(key, options)
when 'zset'
RedisPagination::Paginator::SortedSetPaginator.new(key, options)
when 'none'
RedisPagination::Paginator::NonePaginator.new(key, options)
else
raise "Pagination is not supported for #{type}"
end
end | ruby | def paginate(key, options = {})
type = RedisPagination.redis.type(key)
case type
when 'list'
RedisPagination::Paginator::ListPaginator.new(key, options)
when 'zset'
RedisPagination::Paginator::SortedSetPaginator.new(key, options)
when 'none'
RedisPagination::Paginator::NonePaginator.new(key, options)
else
raise "Pagination is not supported for #{type}"
end
end | [
"def",
"paginate",
"(",
"key",
",",
"options",
"=",
"{",
"}",
")",
"type",
"=",
"RedisPagination",
".",
"redis",
".",
"type",
"(",
"key",
")",
"case",
"type",
"when",
"'list'",
"RedisPagination",
"::",
"Paginator",
"::",
"ListPaginator",
".",
"new",
"(",
"key",
",",
"options",
")",
"when",
"'zset'",
"RedisPagination",
"::",
"Paginator",
"::",
"SortedSetPaginator",
".",
"new",
"(",
"key",
",",
"options",
")",
"when",
"'none'",
"RedisPagination",
"::",
"Paginator",
"::",
"NonePaginator",
".",
"new",
"(",
"key",
",",
"options",
")",
"else",
"raise",
"\"Pagination is not supported for #{type}\"",
"end",
"end"
] | Retrieve a paginator class appropriate for the +key+ in Redis.
+key+ must be one of +list+ or +zset+, otherwise an exception
will be raised.
@params key [String] Redis key
@params options [Hash] Options to be passed to the individual paginator class.
@return Returns either a +RedisPagination::Paginator::ListPaginator+ or
a +RedisPagination::Paginator::SortedSetPaginator+ depending on the
type of +key+. | [
"Retrieve",
"a",
"paginator",
"class",
"appropriate",
"for",
"the",
"+",
"key",
"+",
"in",
"Redis",
".",
"+",
"key",
"+",
"must",
"be",
"one",
"of",
"+",
"list",
"+",
"or",
"+",
"zset",
"+",
"otherwise",
"an",
"exception",
"will",
"be",
"raised",
"."
] | fecc1d9ee579ceb3ca7df5c45031422d43aaceef | https://github.com/czarneckid/redis_pagination/blob/fecc1d9ee579ceb3ca7df5c45031422d43aaceef/lib/redis_pagination/paginator.rb#L17-L30 |
22,829 | locaweb/heartcheck | lib/heartcheck/caching_app.rb | Heartcheck.CachingApp.call | def call(env)
req = Rack::Request.new(env)
controller = Heartcheck::App::ROUTE_TO_CONTROLLER[req.path_info]
if controller && (result = cache.result(controller))
[200, { 'Content-type' => 'application/json' }, [result]]
else
@app.call(env)
end
end | ruby | def call(env)
req = Rack::Request.new(env)
controller = Heartcheck::App::ROUTE_TO_CONTROLLER[req.path_info]
if controller && (result = cache.result(controller))
[200, { 'Content-type' => 'application/json' }, [result]]
else
@app.call(env)
end
end | [
"def",
"call",
"(",
"env",
")",
"req",
"=",
"Rack",
"::",
"Request",
".",
"new",
"(",
"env",
")",
"controller",
"=",
"Heartcheck",
"::",
"App",
"::",
"ROUTE_TO_CONTROLLER",
"[",
"req",
".",
"path_info",
"]",
"if",
"controller",
"&&",
"(",
"result",
"=",
"cache",
".",
"result",
"(",
"controller",
")",
")",
"[",
"200",
",",
"{",
"'Content-type'",
"=>",
"'application/json'",
"}",
",",
"[",
"result",
"]",
"]",
"else",
"@app",
".",
"call",
"(",
"env",
")",
"end",
"end"
] | Creates an instance of the middleware
@param app [Heartcheck:App] the Rack app to wrap around
@param ttl [Integer] the time to cache the results in seconds
@param cache [Heartcheck::CachingApp::Cache] the cache instance to use
The cache will be created on first use if not supplied
@return [#call] rack compatible middleware
Invokes the middleware
@param env [Hash] the rack request/environment
@return [Array] a rack compatible response | [
"Creates",
"an",
"instance",
"of",
"the",
"middleware"
] | b1ee73c8a1498f1de28f494c4272cb4698e71e26 | https://github.com/locaweb/heartcheck/blob/b1ee73c8a1498f1de28f494c4272cb4698e71e26/lib/heartcheck/caching_app.rb#L26-L35 |
22,830 | giuseb/mork | lib/mork/grid_omr.rb | Mork.GridOMR.rx | def rx(corner)
case corner
when :tl; reg_off
when :tr; page_width - reg_crop - reg_off
when :br; page_width - reg_crop - reg_off
when :bl; reg_off
end
end | ruby | def rx(corner)
case corner
when :tl; reg_off
when :tr; page_width - reg_crop - reg_off
when :br; page_width - reg_crop - reg_off
when :bl; reg_off
end
end | [
"def",
"rx",
"(",
"corner",
")",
"case",
"corner",
"when",
":tl",
";",
"reg_off",
"when",
":tr",
";",
"page_width",
"-",
"reg_crop",
"-",
"reg_off",
"when",
":br",
";",
"page_width",
"-",
"reg_crop",
"-",
"reg_off",
"when",
":bl",
";",
"reg_off",
"end",
"end"
] | iterationless x registration | [
"iterationless",
"x",
"registration"
] | 63acbe762b09e4cda92f5d8dad41ac5735279724 | https://github.com/giuseb/mork/blob/63acbe762b09e4cda92f5d8dad41ac5735279724/lib/mork/grid_omr.rb#L72-L79 |
22,831 | giuseb/mork | lib/mork/grid_pdf.rb | Mork.GridPDF.qnum_xy | def qnum_xy(q)
[
item_x(q).mm - qnum_width - qnum_margin,
item_y(q).mm
]
end | ruby | def qnum_xy(q)
[
item_x(q).mm - qnum_width - qnum_margin,
item_y(q).mm
]
end | [
"def",
"qnum_xy",
"(",
"q",
")",
"[",
"item_x",
"(",
"q",
")",
".",
"mm",
"-",
"qnum_width",
"-",
"qnum_margin",
",",
"item_y",
"(",
"q",
")",
".",
"mm",
"]",
"end"
] | Coordinates at which to place item numbers | [
"Coordinates",
"at",
"which",
"to",
"place",
"item",
"numbers"
] | 63acbe762b09e4cda92f5d8dad41ac5735279724 | https://github.com/giuseb/mork/blob/63acbe762b09e4cda92f5d8dad41ac5735279724/lib/mork/grid_pdf.rb#L46-L51 |
22,832 | giuseb/mork | lib/mork/sheet_omr.rb | Mork.SheetOMR.marked_letters | def marked_letters
return if not_registered
marked_choices.map do |q|
q.map { |cho| (65+cho).chr }
end
end | ruby | def marked_letters
return if not_registered
marked_choices.map do |q|
q.map { |cho| (65+cho).chr }
end
end | [
"def",
"marked_letters",
"return",
"if",
"not_registered",
"marked_choices",
".",
"map",
"do",
"|",
"q",
"|",
"q",
".",
"map",
"{",
"|",
"cho",
"|",
"(",
"65",
"+",
"cho",
")",
".",
"chr",
"}",
"end",
"end"
] | The set of letters marked on the response sheet. At this time, only the
latin sequence 'A, B, C...' is supported.
@return [Array] an array of arrays of 1-character strings; each element
contains the list of letters marked for the corresponding question. | [
"The",
"set",
"of",
"letters",
"marked",
"on",
"the",
"response",
"sheet",
".",
"At",
"this",
"time",
"only",
"the",
"latin",
"sequence",
"A",
"B",
"C",
"...",
"is",
"supported",
"."
] | 63acbe762b09e4cda92f5d8dad41ac5735279724 | https://github.com/giuseb/mork/blob/63acbe762b09e4cda92f5d8dad41ac5735279724/lib/mork/sheet_omr.rb#L129-L134 |
22,833 | sikachu/sprockets-redirect | lib/sprockets/redirect.rb | Sprockets.Redirect.redirect_to_digest_version | def redirect_to_digest_version(env)
url = URI(computed_asset_host || @request.url)
url.path = "#{@prefix}/#{digest_path}"
headers = { 'Location' => url.to_s,
'Content-Type' => Rack::Mime.mime_type(::File.extname(digest_path)),
'Pragma' => 'no-cache',
'Cache-Control' => 'no-cache; max-age=0' }
[self.class.redirect_status, headers, [redirect_message(url.to_s)]]
end | ruby | def redirect_to_digest_version(env)
url = URI(computed_asset_host || @request.url)
url.path = "#{@prefix}/#{digest_path}"
headers = { 'Location' => url.to_s,
'Content-Type' => Rack::Mime.mime_type(::File.extname(digest_path)),
'Pragma' => 'no-cache',
'Cache-Control' => 'no-cache; max-age=0' }
[self.class.redirect_status, headers, [redirect_message(url.to_s)]]
end | [
"def",
"redirect_to_digest_version",
"(",
"env",
")",
"url",
"=",
"URI",
"(",
"computed_asset_host",
"||",
"@request",
".",
"url",
")",
"url",
".",
"path",
"=",
"\"#{@prefix}/#{digest_path}\"",
"headers",
"=",
"{",
"'Location'",
"=>",
"url",
".",
"to_s",
",",
"'Content-Type'",
"=>",
"Rack",
"::",
"Mime",
".",
"mime_type",
"(",
"::",
"File",
".",
"extname",
"(",
"digest_path",
")",
")",
",",
"'Pragma'",
"=>",
"'no-cache'",
",",
"'Cache-Control'",
"=>",
"'no-cache; max-age=0'",
"}",
"[",
"self",
".",
"class",
".",
"redirect_status",
",",
"headers",
",",
"[",
"redirect_message",
"(",
"url",
".",
"to_s",
")",
"]",
"]",
"end"
] | Sends a redirect header back to browser | [
"Sends",
"a",
"redirect",
"header",
"back",
"to",
"browser"
] | e6d1f175d73ed0e63ac8350fc84017b70e05bfaa | https://github.com/sikachu/sprockets-redirect/blob/e6d1f175d73ed0e63ac8350fc84017b70e05bfaa/lib/sprockets/redirect.rb#L80-L90 |
22,834 | giuseb/mork | lib/mork/mimage.rb | Mork.Mimage.register | def register
each_corner { |c| @rm[c] = rm_centroid_on c }
@rm.all? { |k,v| v[:status] == :ok }
end | ruby | def register
each_corner { |c| @rm[c] = rm_centroid_on c }
@rm.all? { |k,v| v[:status] == :ok }
end | [
"def",
"register",
"each_corner",
"{",
"|",
"c",
"|",
"@rm",
"[",
"c",
"]",
"=",
"rm_centroid_on",
"c",
"}",
"@rm",
".",
"all?",
"{",
"|",
"k",
",",
"v",
"|",
"v",
"[",
":status",
"]",
"==",
":ok",
"}",
"end"
] | find the XY coordinates of the 4 registration marks,
plus the stdev of the search area as quality control | [
"find",
"the",
"XY",
"coordinates",
"of",
"the",
"4",
"registration",
"marks",
"plus",
"the",
"stdev",
"of",
"the",
"search",
"area",
"as",
"quality",
"control"
] | 63acbe762b09e4cda92f5d8dad41ac5735279724 | https://github.com/giuseb/mork/blob/63acbe762b09e4cda92f5d8dad41ac5735279724/lib/mork/mimage.rb#L160-L163 |
22,835 | giuseb/mork | lib/mork/mimage.rb | Mork.Mimage.rm_centroid_on | def rm_centroid_on(corner)
c = @grom.rm_crop_area(corner)
p = @mack.rm_patch(c, @grom.rm_blur, @grom.rm_dilate)
# byebug
n = NPatch.new(p, c.w, c.h)
cx, cy, sd = n.centroid
st = (cx < 2) or (cy < 2) or (cy > c.h-2) or (cx > c.w-2)
status = st ? :edgy : :ok
return {x: cx+c.x, y: cy+c.y, sd: sd, status: status}
end | ruby | def rm_centroid_on(corner)
c = @grom.rm_crop_area(corner)
p = @mack.rm_patch(c, @grom.rm_blur, @grom.rm_dilate)
# byebug
n = NPatch.new(p, c.w, c.h)
cx, cy, sd = n.centroid
st = (cx < 2) or (cy < 2) or (cy > c.h-2) or (cx > c.w-2)
status = st ? :edgy : :ok
return {x: cx+c.x, y: cy+c.y, sd: sd, status: status}
end | [
"def",
"rm_centroid_on",
"(",
"corner",
")",
"c",
"=",
"@grom",
".",
"rm_crop_area",
"(",
"corner",
")",
"p",
"=",
"@mack",
".",
"rm_patch",
"(",
"c",
",",
"@grom",
".",
"rm_blur",
",",
"@grom",
".",
"rm_dilate",
")",
"# byebug",
"n",
"=",
"NPatch",
".",
"new",
"(",
"p",
",",
"c",
".",
"w",
",",
"c",
".",
"h",
")",
"cx",
",",
"cy",
",",
"sd",
"=",
"n",
".",
"centroid",
"st",
"=",
"(",
"cx",
"<",
"2",
")",
"or",
"(",
"cy",
"<",
"2",
")",
"or",
"(",
"cy",
">",
"c",
".",
"h",
"-",
"2",
")",
"or",
"(",
"cx",
">",
"c",
".",
"w",
"-",
"2",
")",
"status",
"=",
"st",
"?",
":edgy",
":",
":ok",
"return",
"{",
"x",
":",
"cx",
"+",
"c",
".",
"x",
",",
"y",
":",
"cy",
"+",
"c",
".",
"y",
",",
"sd",
":",
"sd",
",",
"status",
":",
"status",
"}",
"end"
] | returns the centroid of the dark region within the given area
in the XY coordinates of the entire image | [
"returns",
"the",
"centroid",
"of",
"the",
"dark",
"region",
"within",
"the",
"given",
"area",
"in",
"the",
"XY",
"coordinates",
"of",
"the",
"entire",
"image"
] | 63acbe762b09e4cda92f5d8dad41ac5735279724 | https://github.com/giuseb/mork/blob/63acbe762b09e4cda92f5d8dad41ac5735279724/lib/mork/mimage.rb#L167-L176 |
22,836 | rails-engine/exception-track | lib/exception_notifier/exception_track_notifier.rb | ExceptionNotifier.ExceptionTrackNotifier.headers_for_env | def headers_for_env(env)
return "" if env.blank?
parameters = filter_parameters(env)
headers = []
headers << "Method: #{env['REQUEST_METHOD']}"
headers << "URL: #{env['REQUEST_URI']}"
if env['REQUEST_METHOD'].downcase != "get"
headers << "Parameters:\n#{pretty_hash(parameters.except(:controller, :action), 13)}"
end
headers << "Controller: #{parameters['controller']}##{parameters['action']}"
headers << "RequestId: #{env['action_dispatch.request_id']}"
headers << "User-Agent: #{env['HTTP_USER_AGENT']}"
headers << "Remote IP: #{env['REMOTE_ADDR']}"
headers << "Language: #{env['HTTP_ACCEPT_LANGUAGE']}"
headers << "Server: #{Socket.gethostname}"
headers << "Process: #{$PROCESS_ID}"
headers.join("\n")
end | ruby | def headers_for_env(env)
return "" if env.blank?
parameters = filter_parameters(env)
headers = []
headers << "Method: #{env['REQUEST_METHOD']}"
headers << "URL: #{env['REQUEST_URI']}"
if env['REQUEST_METHOD'].downcase != "get"
headers << "Parameters:\n#{pretty_hash(parameters.except(:controller, :action), 13)}"
end
headers << "Controller: #{parameters['controller']}##{parameters['action']}"
headers << "RequestId: #{env['action_dispatch.request_id']}"
headers << "User-Agent: #{env['HTTP_USER_AGENT']}"
headers << "Remote IP: #{env['REMOTE_ADDR']}"
headers << "Language: #{env['HTTP_ACCEPT_LANGUAGE']}"
headers << "Server: #{Socket.gethostname}"
headers << "Process: #{$PROCESS_ID}"
headers.join("\n")
end | [
"def",
"headers_for_env",
"(",
"env",
")",
"return",
"\"\"",
"if",
"env",
".",
"blank?",
"parameters",
"=",
"filter_parameters",
"(",
"env",
")",
"headers",
"=",
"[",
"]",
"headers",
"<<",
"\"Method: #{env['REQUEST_METHOD']}\"",
"headers",
"<<",
"\"URL: #{env['REQUEST_URI']}\"",
"if",
"env",
"[",
"'REQUEST_METHOD'",
"]",
".",
"downcase",
"!=",
"\"get\"",
"headers",
"<<",
"\"Parameters:\\n#{pretty_hash(parameters.except(:controller, :action), 13)}\"",
"end",
"headers",
"<<",
"\"Controller: #{parameters['controller']}##{parameters['action']}\"",
"headers",
"<<",
"\"RequestId: #{env['action_dispatch.request_id']}\"",
"headers",
"<<",
"\"User-Agent: #{env['HTTP_USER_AGENT']}\"",
"headers",
"<<",
"\"Remote IP: #{env['REMOTE_ADDR']}\"",
"headers",
"<<",
"\"Language: #{env['HTTP_ACCEPT_LANGUAGE']}\"",
"headers",
"<<",
"\"Server: #{Socket.gethostname}\"",
"headers",
"<<",
"\"Process: #{$PROCESS_ID}\"",
"headers",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] | Log Request headers from Rack env | [
"Log",
"Request",
"headers",
"from",
"Rack",
"env"
] | 7b9a506b95f745e895e623d923d6d23817bc26f1 | https://github.com/rails-engine/exception-track/blob/7b9a506b95f745e895e623d923d6d23817bc26f1/lib/exception_notifier/exception_track_notifier.rb#L38-L58 |
22,837 | dkubb/yardstick | lib/yardstick/rule_config.rb | Yardstick.RuleConfig.exclude? | def exclude?(path)
exclude.include?(path) ||
exclude.include?(path.split(METHOD_SEPARATOR).first)
end | ruby | def exclude?(path)
exclude.include?(path) ||
exclude.include?(path.split(METHOD_SEPARATOR).first)
end | [
"def",
"exclude?",
"(",
"path",
")",
"exclude",
".",
"include?",
"(",
"path",
")",
"||",
"exclude",
".",
"include?",
"(",
"path",
".",
"split",
"(",
"METHOD_SEPARATOR",
")",
".",
"first",
")",
"end"
] | Checks if given path is in exclude list
If exact match fails then checks if the method class is in the exclude
list.
@param [String] path
document path
@return [Boolean]
true if path is in the exclude list
@api private | [
"Checks",
"if",
"given",
"path",
"is",
"in",
"exclude",
"list"
] | 6dcc0139eca3b6bfbdfd6722c77937142e6ed1b9 | https://github.com/dkubb/yardstick/blob/6dcc0139eca3b6bfbdfd6722c77937142e6ed1b9/lib/yardstick/rule_config.rb#L52-L55 |
22,838 | dkubb/yardstick | lib/yardstick/document_set.rb | Yardstick.DocumentSet.measure | def measure(config)
reduce(MeasurementSet.new) do |set, document|
set.merge(Document.measure(document, config))
end
end | ruby | def measure(config)
reduce(MeasurementSet.new) do |set, document|
set.merge(Document.measure(document, config))
end
end | [
"def",
"measure",
"(",
"config",
")",
"reduce",
"(",
"MeasurementSet",
".",
"new",
")",
"do",
"|",
"set",
",",
"document",
"|",
"set",
".",
"merge",
"(",
"Document",
".",
"measure",
"(",
"document",
",",
"config",
")",
")",
"end",
"end"
] | Measure documents using given config
@return [Yardstick::MeasurementSet]
a collection of measurements
@api private | [
"Measure",
"documents",
"using",
"given",
"config"
] | 6dcc0139eca3b6bfbdfd6722c77937142e6ed1b9 | https://github.com/dkubb/yardstick/blob/6dcc0139eca3b6bfbdfd6722c77937142e6ed1b9/lib/yardstick/document_set.rb#L12-L16 |
22,839 | dkubb/yardstick | lib/yardstick/config.rb | Yardstick.Config.for_rule | def for_rule(rule_class)
key = rule_class.to_s[NAMESPACE_PREFIX.length..-1]
if key
RuleConfig.new(@rules.fetch(key.to_sym, {}))
else
fail InvalidRule, "every rule must begin with #{NAMESPACE_PREFIX}"
end
end | ruby | def for_rule(rule_class)
key = rule_class.to_s[NAMESPACE_PREFIX.length..-1]
if key
RuleConfig.new(@rules.fetch(key.to_sym, {}))
else
fail InvalidRule, "every rule must begin with #{NAMESPACE_PREFIX}"
end
end | [
"def",
"for_rule",
"(",
"rule_class",
")",
"key",
"=",
"rule_class",
".",
"to_s",
"[",
"NAMESPACE_PREFIX",
".",
"length",
"..",
"-",
"1",
"]",
"if",
"key",
"RuleConfig",
".",
"new",
"(",
"@rules",
".",
"fetch",
"(",
"key",
".",
"to_sym",
",",
"{",
"}",
")",
")",
"else",
"fail",
"InvalidRule",
",",
"\"every rule must begin with #{NAMESPACE_PREFIX}\"",
"end",
"end"
] | Initializes new config
@param [Hash] options
optional configuration
@yieldparam [Yardstick::Config] config
the config object
@return [Yardstick::Config]
@api private
Return config for given rule
@param [Class] rule_class
@return [RuleConfig]
@api private | [
"Initializes",
"new",
"config"
] | 6dcc0139eca3b6bfbdfd6722c77937142e6ed1b9 | https://github.com/dkubb/yardstick/blob/6dcc0139eca3b6bfbdfd6722c77937142e6ed1b9/lib/yardstick/config.rb#L119-L127 |
22,840 | dkubb/yardstick | lib/yardstick/config.rb | Yardstick.Config.defaults= | def defaults=(options)
@threshold = options.fetch(:threshold, 100)
@verbose = options.fetch(:verbose, true)
@path = options.fetch(:path, 'lib/**/*.rb')
@require_exact_threshold = options.fetch(:require_exact_threshold, true)
@rules = options.fetch(:rules, {})
self.output = 'measurements/report.txt'
end | ruby | def defaults=(options)
@threshold = options.fetch(:threshold, 100)
@verbose = options.fetch(:verbose, true)
@path = options.fetch(:path, 'lib/**/*.rb')
@require_exact_threshold = options.fetch(:require_exact_threshold, true)
@rules = options.fetch(:rules, {})
self.output = 'measurements/report.txt'
end | [
"def",
"defaults",
"=",
"(",
"options",
")",
"@threshold",
"=",
"options",
".",
"fetch",
"(",
":threshold",
",",
"100",
")",
"@verbose",
"=",
"options",
".",
"fetch",
"(",
":verbose",
",",
"true",
")",
"@path",
"=",
"options",
".",
"fetch",
"(",
":path",
",",
"'lib/**/*.rb'",
")",
"@require_exact_threshold",
"=",
"options",
".",
"fetch",
"(",
":require_exact_threshold",
",",
"true",
")",
"@rules",
"=",
"options",
".",
"fetch",
"(",
":rules",
",",
"{",
"}",
")",
"self",
".",
"output",
"=",
"'measurements/report.txt'",
"end"
] | Sets default options
@param [Hash] options
optional configuration
@return [undefined]
@api private | [
"Sets",
"default",
"options"
] | 6dcc0139eca3b6bfbdfd6722c77937142e6ed1b9 | https://github.com/dkubb/yardstick/blob/6dcc0139eca3b6bfbdfd6722c77937142e6ed1b9/lib/yardstick/config.rb#L169-L176 |
22,841 | clarete/s3sync | lib/s3sync/sync.rb | S3Sync.Node.compare_small_comparators | def compare_small_comparators(other)
return true if @size > SMALL_FILE || other.size > SMALL_FILE
return true if small_comparator.nil? || other.small_comparator.nil?
small_comparator.call == other.small_comparator.call
end | ruby | def compare_small_comparators(other)
return true if @size > SMALL_FILE || other.size > SMALL_FILE
return true if small_comparator.nil? || other.small_comparator.nil?
small_comparator.call == other.small_comparator.call
end | [
"def",
"compare_small_comparators",
"(",
"other",
")",
"return",
"true",
"if",
"@size",
">",
"SMALL_FILE",
"||",
"other",
".",
"size",
">",
"SMALL_FILE",
"return",
"true",
"if",
"small_comparator",
".",
"nil?",
"||",
"other",
".",
"small_comparator",
".",
"nil?",
"small_comparator",
".",
"call",
"==",
"other",
".",
"small_comparator",
".",
"call",
"end"
] | If files are small and both nodes have a comparator, we can call an extra
provided block to verify equality. This allows | [
"If",
"files",
"are",
"small",
"and",
"both",
"nodes",
"have",
"a",
"comparator",
"we",
"can",
"call",
"an",
"extra",
"provided",
"block",
"to",
"verify",
"equality",
".",
"This",
"allows"
] | b690957f6bb4299bca3224258855f1694406aab3 | https://github.com/clarete/s3sync/blob/b690957f6bb4299bca3224258855f1694406aab3/lib/s3sync/sync.rb#L102-L107 |
22,842 | acatighera/statistics | lib/statistics.rb | Statistics.HasStats.define_calculated_statistic | def define_calculated_statistic(name, &block)
method_name = name.to_s.gsub(" ", "").underscore + "_stat"
@statistics ||= {}
@statistics[name] = method_name
(class<<self; self; end).instance_eval do
define_method(method_name) do |filters|
@filters = filters
yield
end
end
end | ruby | def define_calculated_statistic(name, &block)
method_name = name.to_s.gsub(" ", "").underscore + "_stat"
@statistics ||= {}
@statistics[name] = method_name
(class<<self; self; end).instance_eval do
define_method(method_name) do |filters|
@filters = filters
yield
end
end
end | [
"def",
"define_calculated_statistic",
"(",
"name",
",",
"&",
"block",
")",
"method_name",
"=",
"name",
".",
"to_s",
".",
"gsub",
"(",
"\" \"",
",",
"\"\"",
")",
".",
"underscore",
"+",
"\"_stat\"",
"@statistics",
"||=",
"{",
"}",
"@statistics",
"[",
"name",
"]",
"=",
"method_name",
"(",
"class",
"<<",
"self",
";",
"self",
";",
"end",
")",
".",
"instance_eval",
"do",
"define_method",
"(",
"method_name",
")",
"do",
"|",
"filters",
"|",
"@filters",
"=",
"filters",
"yield",
"end",
"end",
"end"
] | Defines a statistic using a block that has access to all other defined statistics
EXAMPLE:
class MockModel < ActiveRecord::Base
define_statistic "Basic Count", :count => :all
define_statistic "Basic Sum", :sum => :all, :column_name => 'amount'
define_calculated_statistic "Total Profit"
defined_stats('Basic Sum') * defined_stats('Basic Count')
end | [
"Defines",
"a",
"statistic",
"using",
"a",
"block",
"that",
"has",
"access",
"to",
"all",
"other",
"defined",
"statistics"
] | 33699ccb3aaccd78506b910e56145911323419a5 | https://github.com/acatighera/statistics/blob/33699ccb3aaccd78506b910e56145911323419a5/lib/statistics.rb#L105-L117 |
22,843 | acatighera/statistics | lib/statistics.rb | Statistics.HasStats.statistics | def statistics(filters = {}, except = nil)
(@statistics || {}).inject({}) do |stats_hash, stat|
stats_hash[stat.first] = send(stat.last, filters) if stat.last != except
stats_hash
end
end | ruby | def statistics(filters = {}, except = nil)
(@statistics || {}).inject({}) do |stats_hash, stat|
stats_hash[stat.first] = send(stat.last, filters) if stat.last != except
stats_hash
end
end | [
"def",
"statistics",
"(",
"filters",
"=",
"{",
"}",
",",
"except",
"=",
"nil",
")",
"(",
"@statistics",
"||",
"{",
"}",
")",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"stats_hash",
",",
"stat",
"|",
"stats_hash",
"[",
"stat",
".",
"first",
"]",
"=",
"send",
"(",
"stat",
".",
"last",
",",
"filters",
")",
"if",
"stat",
".",
"last",
"!=",
"except",
"stats_hash",
"end",
"end"
] | Calculates all the statistics defined for this AR class and returns a hash with the values.
There is an optional parameter that is a hash of all values you want to filter by.
EXAMPLE:
MockModel.statistics
MockModel.statistics(:user_type => 'registered', :user_status => 'active') | [
"Calculates",
"all",
"the",
"statistics",
"defined",
"for",
"this",
"AR",
"class",
"and",
"returns",
"a",
"hash",
"with",
"the",
"values",
".",
"There",
"is",
"an",
"optional",
"parameter",
"that",
"is",
"a",
"hash",
"of",
"all",
"values",
"you",
"want",
"to",
"filter",
"by",
"."
] | 33699ccb3aaccd78506b910e56145911323419a5 | https://github.com/acatighera/statistics/blob/33699ccb3aaccd78506b910e56145911323419a5/lib/statistics.rb#L130-L135 |
22,844 | fcheung/keychain | lib/keychain/keychain.rb | Keychain.Keychain.add_to_search_list | def add_to_search_list
list = FFI::MemoryPointer.new(:pointer)
status = Sec.SecKeychainCopySearchList(list)
Sec.check_osstatus(status)
ruby_list = CF::Base.typecast(list.read_pointer).release_on_gc.to_ruby
ruby_list << self unless ruby_list.include?(self)
status = Sec.SecKeychainSetSearchList(CF::Array.immutable(ruby_list))
Sec.check_osstatus(status)
self
end | ruby | def add_to_search_list
list = FFI::MemoryPointer.new(:pointer)
status = Sec.SecKeychainCopySearchList(list)
Sec.check_osstatus(status)
ruby_list = CF::Base.typecast(list.read_pointer).release_on_gc.to_ruby
ruby_list << self unless ruby_list.include?(self)
status = Sec.SecKeychainSetSearchList(CF::Array.immutable(ruby_list))
Sec.check_osstatus(status)
self
end | [
"def",
"add_to_search_list",
"list",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":pointer",
")",
"status",
"=",
"Sec",
".",
"SecKeychainCopySearchList",
"(",
"list",
")",
"Sec",
".",
"check_osstatus",
"(",
"status",
")",
"ruby_list",
"=",
"CF",
"::",
"Base",
".",
"typecast",
"(",
"list",
".",
"read_pointer",
")",
".",
"release_on_gc",
".",
"to_ruby",
"ruby_list",
"<<",
"self",
"unless",
"ruby_list",
".",
"include?",
"(",
"self",
")",
"status",
"=",
"Sec",
".",
"SecKeychainSetSearchList",
"(",
"CF",
"::",
"Array",
".",
"immutable",
"(",
"ruby_list",
")",
")",
"Sec",
".",
"check_osstatus",
"(",
"status",
")",
"self",
"end"
] | Add the keychain to the default searchlist | [
"Add",
"the",
"keychain",
"to",
"the",
"default",
"searchlist"
] | f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b | https://github.com/fcheung/keychain/blob/f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b/lib/keychain/keychain.rb#L60-L69 |
22,845 | fcheung/keychain | lib/keychain/keychain.rb | Keychain.Keychain.import | def import(input, app_list=[])
input = input.read if input.is_a? IO
# Create array of TrustedApplication objects
trusted_apps = get_trusted_apps(app_list)
# Create an Access object
access_buffer = FFI::MemoryPointer.new(:pointer)
status = Sec.SecAccessCreate(path.to_cf, trusted_apps, access_buffer)
Sec.check_osstatus status
access = CF::Base.typecast(access_buffer.read_pointer)
key_params = Sec::SecItemImportExportKeyParameters.new
key_params[:accessRef] = access
# Import item to the keychain
cf_data = CF::Data.from_string(input).release_on_gc
cf_array = FFI::MemoryPointer.new(:pointer)
status = Sec.SecItemImport(cf_data, nil, :kSecFormatUnknown, :kSecItemTypeUnknown, :kSecItemPemArmour, key_params, self, cf_array)
access.release
Sec.check_osstatus status
item_array = CF::Base.typecast(cf_array.read_pointer).release_on_gc
item_array.to_ruby
end | ruby | def import(input, app_list=[])
input = input.read if input.is_a? IO
# Create array of TrustedApplication objects
trusted_apps = get_trusted_apps(app_list)
# Create an Access object
access_buffer = FFI::MemoryPointer.new(:pointer)
status = Sec.SecAccessCreate(path.to_cf, trusted_apps, access_buffer)
Sec.check_osstatus status
access = CF::Base.typecast(access_buffer.read_pointer)
key_params = Sec::SecItemImportExportKeyParameters.new
key_params[:accessRef] = access
# Import item to the keychain
cf_data = CF::Data.from_string(input).release_on_gc
cf_array = FFI::MemoryPointer.new(:pointer)
status = Sec.SecItemImport(cf_data, nil, :kSecFormatUnknown, :kSecItemTypeUnknown, :kSecItemPemArmour, key_params, self, cf_array)
access.release
Sec.check_osstatus status
item_array = CF::Base.typecast(cf_array.read_pointer).release_on_gc
item_array.to_ruby
end | [
"def",
"import",
"(",
"input",
",",
"app_list",
"=",
"[",
"]",
")",
"input",
"=",
"input",
".",
"read",
"if",
"input",
".",
"is_a?",
"IO",
"# Create array of TrustedApplication objects",
"trusted_apps",
"=",
"get_trusted_apps",
"(",
"app_list",
")",
"# Create an Access object",
"access_buffer",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":pointer",
")",
"status",
"=",
"Sec",
".",
"SecAccessCreate",
"(",
"path",
".",
"to_cf",
",",
"trusted_apps",
",",
"access_buffer",
")",
"Sec",
".",
"check_osstatus",
"status",
"access",
"=",
"CF",
"::",
"Base",
".",
"typecast",
"(",
"access_buffer",
".",
"read_pointer",
")",
"key_params",
"=",
"Sec",
"::",
"SecItemImportExportKeyParameters",
".",
"new",
"key_params",
"[",
":accessRef",
"]",
"=",
"access",
"# Import item to the keychain",
"cf_data",
"=",
"CF",
"::",
"Data",
".",
"from_string",
"(",
"input",
")",
".",
"release_on_gc",
"cf_array",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":pointer",
")",
"status",
"=",
"Sec",
".",
"SecItemImport",
"(",
"cf_data",
",",
"nil",
",",
":kSecFormatUnknown",
",",
":kSecItemTypeUnknown",
",",
":kSecItemPemArmour",
",",
"key_params",
",",
"self",
",",
"cf_array",
")",
"access",
".",
"release",
"Sec",
".",
"check_osstatus",
"status",
"item_array",
"=",
"CF",
"::",
"Base",
".",
"typecast",
"(",
"cf_array",
".",
"read_pointer",
")",
".",
"release_on_gc",
"item_array",
".",
"to_ruby",
"end"
] | Imports item from string or file to this keychain
@param [IO, String] input IO object or String with raw data to import
@param [Array <String>] app_list List of applications which will be
permitted to access imported items
@return [Array <SecKeychainItem>] List of imported keychain objects,
each of which may be a SecCertificate, SecKey, or SecIdentity instance | [
"Imports",
"item",
"from",
"string",
"or",
"file",
"to",
"this",
"keychain"
] | f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b | https://github.com/fcheung/keychain/blob/f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b/lib/keychain/keychain.rb#L123-L147 |
22,846 | fcheung/keychain | lib/keychain/keychain.rb | Keychain.Keychain.path | def path
out_buffer = FFI::MemoryPointer.new(:uchar, 2048)
io_size = FFI::MemoryPointer.new(:uint32)
io_size.put_uint32(0, out_buffer.size)
status = Sec.SecKeychainGetPath(self,io_size, out_buffer)
Sec.check_osstatus(status)
out_buffer.read_string(io_size.get_uint32(0)).force_encoding(Encoding::UTF_8)
end | ruby | def path
out_buffer = FFI::MemoryPointer.new(:uchar, 2048)
io_size = FFI::MemoryPointer.new(:uint32)
io_size.put_uint32(0, out_buffer.size)
status = Sec.SecKeychainGetPath(self,io_size, out_buffer)
Sec.check_osstatus(status)
out_buffer.read_string(io_size.get_uint32(0)).force_encoding(Encoding::UTF_8)
end | [
"def",
"path",
"out_buffer",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":uchar",
",",
"2048",
")",
"io_size",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":uint32",
")",
"io_size",
".",
"put_uint32",
"(",
"0",
",",
"out_buffer",
".",
"size",
")",
"status",
"=",
"Sec",
".",
"SecKeychainGetPath",
"(",
"self",
",",
"io_size",
",",
"out_buffer",
")",
"Sec",
".",
"check_osstatus",
"(",
"status",
")",
"out_buffer",
".",
"read_string",
"(",
"io_size",
".",
"get_uint32",
"(",
"0",
")",
")",
".",
"force_encoding",
"(",
"Encoding",
"::",
"UTF_8",
")",
"end"
] | Returns the path at which the keychain is stored
See https://developer.apple.com/library/mac/documentation/security/Reference/keychainservices/Reference/reference.html#//apple_ref/c/func/SecKeychainGetPath
@return [String] path to the keychain file | [
"Returns",
"the",
"path",
"at",
"which",
"the",
"keychain",
"is",
"stored"
] | f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b | https://github.com/fcheung/keychain/blob/f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b/lib/keychain/keychain.rb#L170-L179 |
22,847 | fcheung/keychain | lib/keychain/keychain.rb | Keychain.Keychain.unlock! | def unlock! password=nil
if password
password = password.encode(Encoding::UTF_8)
status = Sec.SecKeychainUnlock self, password.bytesize, password, 1
else
status = Sec.SecKeychainUnlock self, 0, nil, 0
end
Sec.check_osstatus status
end | ruby | def unlock! password=nil
if password
password = password.encode(Encoding::UTF_8)
status = Sec.SecKeychainUnlock self, password.bytesize, password, 1
else
status = Sec.SecKeychainUnlock self, 0, nil, 0
end
Sec.check_osstatus status
end | [
"def",
"unlock!",
"password",
"=",
"nil",
"if",
"password",
"password",
"=",
"password",
".",
"encode",
"(",
"Encoding",
"::",
"UTF_8",
")",
"status",
"=",
"Sec",
".",
"SecKeychainUnlock",
"self",
",",
"password",
".",
"bytesize",
",",
"password",
",",
"1",
"else",
"status",
"=",
"Sec",
".",
"SecKeychainUnlock",
"self",
",",
"0",
",",
"nil",
",",
"0",
"end",
"Sec",
".",
"check_osstatus",
"status",
"end"
] | Unlocks the keychain
@param [optional, String] password the password to unlock the keychain with. If no password is supplied the keychain will prompt the user for a password | [
"Unlocks",
"the",
"keychain"
] | f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b | https://github.com/fcheung/keychain/blob/f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b/lib/keychain/keychain.rb#L191-L199 |
22,848 | fcheung/keychain | lib/keychain/item.rb | Keychain.Item.password | def password
return @unsaved_password if @unsaved_password
out_buffer = FFI::MemoryPointer.new(:pointer)
status = Sec.SecItemCopyMatching({Sec::Query::ITEM_LIST => CF::Array.immutable([self]),
Sec::Query::SEARCH_LIST => [self.keychain],
Sec::Query::CLASS => self.klass,
Sec::Query::RETURN_DATA => true}.to_cf, out_buffer)
Sec.check_osstatus(status)
CF::Base.typecast(out_buffer.read_pointer).release_on_gc.to_s
end | ruby | def password
return @unsaved_password if @unsaved_password
out_buffer = FFI::MemoryPointer.new(:pointer)
status = Sec.SecItemCopyMatching({Sec::Query::ITEM_LIST => CF::Array.immutable([self]),
Sec::Query::SEARCH_LIST => [self.keychain],
Sec::Query::CLASS => self.klass,
Sec::Query::RETURN_DATA => true}.to_cf, out_buffer)
Sec.check_osstatus(status)
CF::Base.typecast(out_buffer.read_pointer).release_on_gc.to_s
end | [
"def",
"password",
"return",
"@unsaved_password",
"if",
"@unsaved_password",
"out_buffer",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":pointer",
")",
"status",
"=",
"Sec",
".",
"SecItemCopyMatching",
"(",
"{",
"Sec",
"::",
"Query",
"::",
"ITEM_LIST",
"=>",
"CF",
"::",
"Array",
".",
"immutable",
"(",
"[",
"self",
"]",
")",
",",
"Sec",
"::",
"Query",
"::",
"SEARCH_LIST",
"=>",
"[",
"self",
".",
"keychain",
"]",
",",
"Sec",
"::",
"Query",
"::",
"CLASS",
"=>",
"self",
".",
"klass",
",",
"Sec",
"::",
"Query",
"::",
"RETURN_DATA",
"=>",
"true",
"}",
".",
"to_cf",
",",
"out_buffer",
")",
"Sec",
".",
"check_osstatus",
"(",
"status",
")",
"CF",
"::",
"Base",
".",
"typecast",
"(",
"out_buffer",
".",
"read_pointer",
")",
".",
"release_on_gc",
".",
"to_s",
"end"
] | Fetches the password data associated with the item. This may cause the user to be asked for access
@return [String] The password data, an ASCII_8BIT encoded string | [
"Fetches",
"the",
"password",
"data",
"associated",
"with",
"the",
"item",
".",
"This",
"may",
"cause",
"the",
"user",
"to",
"be",
"asked",
"for",
"access"
] | f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b | https://github.com/fcheung/keychain/blob/f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b/lib/keychain/item.rb#L80-L89 |
22,849 | fcheung/keychain | lib/keychain/item.rb | Keychain.Item.save! | def save!(options={})
if persisted?
cf_dict = update
else
cf_dict = create(options)
self.ptr = cf_dict[Sec::Value::REF].to_ptr
self.retain.release_on_gc
end
@unsaved_password = nil
update_self_from_dictionary(cf_dict)
cf_dict.release
self
end | ruby | def save!(options={})
if persisted?
cf_dict = update
else
cf_dict = create(options)
self.ptr = cf_dict[Sec::Value::REF].to_ptr
self.retain.release_on_gc
end
@unsaved_password = nil
update_self_from_dictionary(cf_dict)
cf_dict.release
self
end | [
"def",
"save!",
"(",
"options",
"=",
"{",
"}",
")",
"if",
"persisted?",
"cf_dict",
"=",
"update",
"else",
"cf_dict",
"=",
"create",
"(",
"options",
")",
"self",
".",
"ptr",
"=",
"cf_dict",
"[",
"Sec",
"::",
"Value",
"::",
"REF",
"]",
".",
"to_ptr",
"self",
".",
"retain",
".",
"release_on_gc",
"end",
"@unsaved_password",
"=",
"nil",
"update_self_from_dictionary",
"(",
"cf_dict",
")",
"cf_dict",
".",
"release",
"self",
"end"
] | Attempts to update the keychain with any changes made to the item
or saves a previously unpersisted item
@param [optional, Hash] options extra options when saving the item
@option options [Keychain::Keychain] :keychain when saving an unsaved item, they keychain to save it in
@return [Keychain::Item] returns the item | [
"Attempts",
"to",
"update",
"the",
"keychain",
"with",
"any",
"changes",
"made",
"to",
"the",
"item",
"or",
"saves",
"a",
"previously",
"unpersisted",
"item"
] | f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b | https://github.com/fcheung/keychain/blob/f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b/lib/keychain/item.rb#L96-L108 |
22,850 | devrandom/net_dav | lib/net/dav.rb | Net.DAV.propfind | def propfind(path,*options)
headers = {'Depth' => '1'}
if(options[0] == :acl)
body = '<?xml version="1.0" encoding="utf-8" ?><D:propfind xmlns:D="DAV:"><D:prop><D:owner/>' +
'<D:supported-privilege-set/><D:current-user-privilege-set/><D:acl/></D:prop></D:propfind>'
else
body = options[0]
end
if(!body)
body = '<?xml version="1.0" encoding="utf-8"?><DAV:propfind xmlns:DAV="DAV:"><DAV:allprop/></DAV:propfind>'
end
res = @handler.request(:propfind, path, body, headers.merge(@headers))
Nokogiri::XML.parse(res.body)
end | ruby | def propfind(path,*options)
headers = {'Depth' => '1'}
if(options[0] == :acl)
body = '<?xml version="1.0" encoding="utf-8" ?><D:propfind xmlns:D="DAV:"><D:prop><D:owner/>' +
'<D:supported-privilege-set/><D:current-user-privilege-set/><D:acl/></D:prop></D:propfind>'
else
body = options[0]
end
if(!body)
body = '<?xml version="1.0" encoding="utf-8"?><DAV:propfind xmlns:DAV="DAV:"><DAV:allprop/></DAV:propfind>'
end
res = @handler.request(:propfind, path, body, headers.merge(@headers))
Nokogiri::XML.parse(res.body)
end | [
"def",
"propfind",
"(",
"path",
",",
"*",
"options",
")",
"headers",
"=",
"{",
"'Depth'",
"=>",
"'1'",
"}",
"if",
"(",
"options",
"[",
"0",
"]",
"==",
":acl",
")",
"body",
"=",
"'<?xml version=\"1.0\" encoding=\"utf-8\" ?><D:propfind xmlns:D=\"DAV:\"><D:prop><D:owner/>'",
"+",
"'<D:supported-privilege-set/><D:current-user-privilege-set/><D:acl/></D:prop></D:propfind>'",
"else",
"body",
"=",
"options",
"[",
"0",
"]",
"end",
"if",
"(",
"!",
"body",
")",
"body",
"=",
"'<?xml version=\"1.0\" encoding=\"utf-8\"?><DAV:propfind xmlns:DAV=\"DAV:\"><DAV:allprop/></DAV:propfind>'",
"end",
"res",
"=",
"@handler",
".",
"request",
"(",
":propfind",
",",
"path",
",",
"body",
",",
"headers",
".",
"merge",
"(",
"@headers",
")",
")",
"Nokogiri",
"::",
"XML",
".",
"parse",
"(",
"res",
".",
"body",
")",
"end"
] | Perform a PROPFIND request
Example:
Basic propfind:
properties = propfind('/path/')
Get ACL for resource:
properties = propfind('/path/', :acl)
Custom propfind:
properties = propfind('/path/', '<?xml version="1.0" encoding="utf-8"?>...')
See http://webdav.org/specs/rfc3744.html#rfc.section.5.9 for more on
how to retrieve access control properties. | [
"Perform",
"a",
"PROPFIND",
"request"
] | dd41e51dee05d81f7eb4256dce3f263f8d12e44e | https://github.com/devrandom/net_dav/blob/dd41e51dee05d81f7eb4256dce3f263f8d12e44e/lib/net/dav.rb#L487-L500 |
22,851 | devrandom/net_dav | lib/net/dav.rb | Net.DAV.cd | def cd(url)
new_uri = @uri.merge(url)
if new_uri.host != @uri.host || new_uri.port != @uri.port || new_uri.scheme != @uri.scheme
raise Exception , "uri must have same scheme, host and port"
end
@uri = new_uri
end | ruby | def cd(url)
new_uri = @uri.merge(url)
if new_uri.host != @uri.host || new_uri.port != @uri.port || new_uri.scheme != @uri.scheme
raise Exception , "uri must have same scheme, host and port"
end
@uri = new_uri
end | [
"def",
"cd",
"(",
"url",
")",
"new_uri",
"=",
"@uri",
".",
"merge",
"(",
"url",
")",
"if",
"new_uri",
".",
"host",
"!=",
"@uri",
".",
"host",
"||",
"new_uri",
".",
"port",
"!=",
"@uri",
".",
"port",
"||",
"new_uri",
".",
"scheme",
"!=",
"@uri",
".",
"scheme",
"raise",
"Exception",
",",
"\"uri must have same scheme, host and port\"",
"end",
"@uri",
"=",
"new_uri",
"end"
] | Change the base URL for use in handling relative paths | [
"Change",
"the",
"base",
"URL",
"for",
"use",
"in",
"handling",
"relative",
"paths"
] | dd41e51dee05d81f7eb4256dce3f263f8d12e44e | https://github.com/devrandom/net_dav/blob/dd41e51dee05d81f7eb4256dce3f263f8d12e44e/lib/net/dav.rb#L583-L589 |
22,852 | devrandom/net_dav | lib/net/dav.rb | Net.DAV.get | def get(path, &block)
path = @uri.merge(path).path
body = @handler.request_returning_body(:get, path, @headers, &block)
body
end | ruby | def get(path, &block)
path = @uri.merge(path).path
body = @handler.request_returning_body(:get, path, @headers, &block)
body
end | [
"def",
"get",
"(",
"path",
",",
"&",
"block",
")",
"path",
"=",
"@uri",
".",
"merge",
"(",
"path",
")",
".",
"path",
"body",
"=",
"@handler",
".",
"request_returning_body",
"(",
":get",
",",
"path",
",",
"@headers",
",",
"block",
")",
"body",
"end"
] | Get the content of a resource as a string
If called with a block, yields each fragment of the
entity body in turn as a string as it is read from
the socket. Note that in this case, the returned response
object will *not* contain a (meaningful) body. | [
"Get",
"the",
"content",
"of",
"a",
"resource",
"as",
"a",
"string"
] | dd41e51dee05d81f7eb4256dce3f263f8d12e44e | https://github.com/devrandom/net_dav/blob/dd41e51dee05d81f7eb4256dce3f263f8d12e44e/lib/net/dav.rb#L598-L602 |
22,853 | devrandom/net_dav | lib/net/dav.rb | Net.DAV.put | def put(path, stream, length)
path = @uri.merge(path).path
res = @handler.request_sending_stream(:put, path, stream, length, @headers)
res.body
end | ruby | def put(path, stream, length)
path = @uri.merge(path).path
res = @handler.request_sending_stream(:put, path, stream, length, @headers)
res.body
end | [
"def",
"put",
"(",
"path",
",",
"stream",
",",
"length",
")",
"path",
"=",
"@uri",
".",
"merge",
"(",
"path",
")",
".",
"path",
"res",
"=",
"@handler",
".",
"request_sending_stream",
"(",
":put",
",",
"path",
",",
"stream",
",",
"length",
",",
"@headers",
")",
"res",
".",
"body",
"end"
] | Stores the content of a stream to a URL
Example:
File.open(file, "r") do |stream|
dav.put(url.path, stream, File.size(file))
end | [
"Stores",
"the",
"content",
"of",
"a",
"stream",
"to",
"a",
"URL"
] | dd41e51dee05d81f7eb4256dce3f263f8d12e44e | https://github.com/devrandom/net_dav/blob/dd41e51dee05d81f7eb4256dce3f263f8d12e44e/lib/net/dav.rb#L610-L614 |
22,854 | devrandom/net_dav | lib/net/dav.rb | Net.DAV.put_string | def put_string(path, str)
path = @uri.merge(path).path
res = @handler.request_sending_body(:put, path, str, @headers)
res.body
end | ruby | def put_string(path, str)
path = @uri.merge(path).path
res = @handler.request_sending_body(:put, path, str, @headers)
res.body
end | [
"def",
"put_string",
"(",
"path",
",",
"str",
")",
"path",
"=",
"@uri",
".",
"merge",
"(",
"path",
")",
".",
"path",
"res",
"=",
"@handler",
".",
"request_sending_body",
"(",
":put",
",",
"path",
",",
"str",
",",
"@headers",
")",
"res",
".",
"body",
"end"
] | Stores the content of a string to a URL
Example:
dav.put(url.path, "hello world") | [
"Stores",
"the",
"content",
"of",
"a",
"string",
"to",
"a",
"URL"
] | dd41e51dee05d81f7eb4256dce3f263f8d12e44e | https://github.com/devrandom/net_dav/blob/dd41e51dee05d81f7eb4256dce3f263f8d12e44e/lib/net/dav.rb#L621-L625 |
22,855 | devrandom/net_dav | lib/net/dav.rb | Net.DAV.move | def move(path,destination)
path = @uri.merge(path).path
destination = @uri.merge(destination).to_s
headers = {'Destination' => destination}
res = @handler.request(:move, path, nil, headers.merge(@headers))
res.body
end | ruby | def move(path,destination)
path = @uri.merge(path).path
destination = @uri.merge(destination).to_s
headers = {'Destination' => destination}
res = @handler.request(:move, path, nil, headers.merge(@headers))
res.body
end | [
"def",
"move",
"(",
"path",
",",
"destination",
")",
"path",
"=",
"@uri",
".",
"merge",
"(",
"path",
")",
".",
"path",
"destination",
"=",
"@uri",
".",
"merge",
"(",
"destination",
")",
".",
"to_s",
"headers",
"=",
"{",
"'Destination'",
"=>",
"destination",
"}",
"res",
"=",
"@handler",
".",
"request",
"(",
":move",
",",
"path",
",",
"nil",
",",
"headers",
".",
"merge",
"(",
"@headers",
")",
")",
"res",
".",
"body",
"end"
] | Send a move request to the server.
Example:
dav.move(original_path, new_path) | [
"Send",
"a",
"move",
"request",
"to",
"the",
"server",
"."
] | dd41e51dee05d81f7eb4256dce3f263f8d12e44e | https://github.com/devrandom/net_dav/blob/dd41e51dee05d81f7eb4256dce3f263f8d12e44e/lib/net/dav.rb#L641-L647 |
22,856 | devrandom/net_dav | lib/net/dav.rb | Net.DAV.proppatch | def proppatch(path, xml_snippet)
path = @uri.merge(path).path
headers = {'Depth' => '1'}
body = '<?xml version="1.0"?>' +
'<d:propertyupdate xmlns:d="DAV:">' +
xml_snippet +
'</d:propertyupdate>'
res = @handler.request(:proppatch, path, body, headers.merge(@headers))
Nokogiri::XML.parse(res.body)
end | ruby | def proppatch(path, xml_snippet)
path = @uri.merge(path).path
headers = {'Depth' => '1'}
body = '<?xml version="1.0"?>' +
'<d:propertyupdate xmlns:d="DAV:">' +
xml_snippet +
'</d:propertyupdate>'
res = @handler.request(:proppatch, path, body, headers.merge(@headers))
Nokogiri::XML.parse(res.body)
end | [
"def",
"proppatch",
"(",
"path",
",",
"xml_snippet",
")",
"path",
"=",
"@uri",
".",
"merge",
"(",
"path",
")",
".",
"path",
"headers",
"=",
"{",
"'Depth'",
"=>",
"'1'",
"}",
"body",
"=",
"'<?xml version=\"1.0\"?>'",
"+",
"'<d:propertyupdate xmlns:d=\"DAV:\">'",
"+",
"xml_snippet",
"+",
"'</d:propertyupdate>'",
"res",
"=",
"@handler",
".",
"request",
"(",
":proppatch",
",",
"path",
",",
"body",
",",
"headers",
".",
"merge",
"(",
"@headers",
")",
")",
"Nokogiri",
"::",
"XML",
".",
"parse",
"(",
"res",
".",
"body",
")",
"end"
] | Do a proppatch request to the server to
update properties on resources or collections.
Example:
dav.proppatch(uri.path,
"<d:set><d:prop>" +
"<d:creationdate>#{new_date}</d:creationdate>" +
"</d:set></d:prop>" +
) | [
"Do",
"a",
"proppatch",
"request",
"to",
"the",
"server",
"to",
"update",
"properties",
"on",
"resources",
"or",
"collections",
"."
] | dd41e51dee05d81f7eb4256dce3f263f8d12e44e | https://github.com/devrandom/net_dav/blob/dd41e51dee05d81f7eb4256dce3f263f8d12e44e/lib/net/dav.rb#L670-L679 |
22,857 | devrandom/net_dav | lib/net/dav.rb | Net.DAV.unlock | def unlock(path, locktoken)
headers = {'Lock-Token' => '<'+locktoken+'>'}
path = @uri.merge(path).path
res = @handler.request(:unlock, path, nil, headers.merge(@headers))
end | ruby | def unlock(path, locktoken)
headers = {'Lock-Token' => '<'+locktoken+'>'}
path = @uri.merge(path).path
res = @handler.request(:unlock, path, nil, headers.merge(@headers))
end | [
"def",
"unlock",
"(",
"path",
",",
"locktoken",
")",
"headers",
"=",
"{",
"'Lock-Token'",
"=>",
"'<'",
"+",
"locktoken",
"+",
"'>'",
"}",
"path",
"=",
"@uri",
".",
"merge",
"(",
"path",
")",
".",
"path",
"res",
"=",
"@handler",
".",
"request",
"(",
":unlock",
",",
"path",
",",
"nil",
",",
"headers",
".",
"merge",
"(",
"@headers",
")",
")",
"end"
] | Send an unlock request to the server
Example:
dav.unlock(uri.path, "opaquelocktoken:eee47ade-09ac-626b-02f7-e354175d984e") | [
"Send",
"an",
"unlock",
"request",
"to",
"the",
"server"
] | dd41e51dee05d81f7eb4256dce3f263f8d12e44e | https://github.com/devrandom/net_dav/blob/dd41e51dee05d81f7eb4256dce3f263f8d12e44e/lib/net/dav.rb#L702-L706 |
22,858 | devrandom/net_dav | lib/net/dav.rb | Net.DAV.exists? | def exists?(path)
path = @uri.merge(path).path
headers = {'Depth' => '1'}
body = '<?xml version="1.0" encoding="utf-8"?><DAV:propfind xmlns:DAV="DAV:"><DAV:allprop/></DAV:propfind>'
begin
res = @handler.request(:propfind, path, body, headers.merge(@headers))
rescue
return false
end
return (res.is_a? Net::HTTPSuccess)
end | ruby | def exists?(path)
path = @uri.merge(path).path
headers = {'Depth' => '1'}
body = '<?xml version="1.0" encoding="utf-8"?><DAV:propfind xmlns:DAV="DAV:"><DAV:allprop/></DAV:propfind>'
begin
res = @handler.request(:propfind, path, body, headers.merge(@headers))
rescue
return false
end
return (res.is_a? Net::HTTPSuccess)
end | [
"def",
"exists?",
"(",
"path",
")",
"path",
"=",
"@uri",
".",
"merge",
"(",
"path",
")",
".",
"path",
"headers",
"=",
"{",
"'Depth'",
"=>",
"'1'",
"}",
"body",
"=",
"'<?xml version=\"1.0\" encoding=\"utf-8\"?><DAV:propfind xmlns:DAV=\"DAV:\"><DAV:allprop/></DAV:propfind>'",
"begin",
"res",
"=",
"@handler",
".",
"request",
"(",
":propfind",
",",
"path",
",",
"body",
",",
"headers",
".",
"merge",
"(",
"@headers",
")",
")",
"rescue",
"return",
"false",
"end",
"return",
"(",
"res",
".",
"is_a?",
"Net",
"::",
"HTTPSuccess",
")",
"end"
] | Returns true if resource exists on server.
Example:
dav.exists?('https://www.example.com/collection/') => true
dav.exists?('/collection/') => true | [
"Returns",
"true",
"if",
"resource",
"exists",
"on",
"server",
"."
] | dd41e51dee05d81f7eb4256dce3f263f8d12e44e | https://github.com/devrandom/net_dav/blob/dd41e51dee05d81f7eb4256dce3f263f8d12e44e/lib/net/dav.rb#L713-L723 |
22,859 | fcheung/keychain | lib/keychain/sec.rb | Sec.Base.keychain | def keychain
out = FFI::MemoryPointer.new :pointer
status = Sec.SecKeychainItemCopyKeychain(self,out)
Sec.check_osstatus(status)
CF::Base.new(out.read_pointer).release_on_gc
end | ruby | def keychain
out = FFI::MemoryPointer.new :pointer
status = Sec.SecKeychainItemCopyKeychain(self,out)
Sec.check_osstatus(status)
CF::Base.new(out.read_pointer).release_on_gc
end | [
"def",
"keychain",
"out",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"new",
":pointer",
"status",
"=",
"Sec",
".",
"SecKeychainItemCopyKeychain",
"(",
"self",
",",
"out",
")",
"Sec",
".",
"check_osstatus",
"(",
"status",
")",
"CF",
"::",
"Base",
".",
"new",
"(",
"out",
".",
"read_pointer",
")",
".",
"release_on_gc",
"end"
] | Returns the keychain the item is in
@return [Keychain::Keychain] | [
"Returns",
"the",
"keychain",
"the",
"item",
"is",
"in"
] | f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b | https://github.com/fcheung/keychain/blob/f45c9d8335bb2e0ac377a85d8c6dc583edde8e2b/lib/keychain/sec.rb#L150-L155 |
22,860 | pmahoney/process_shared | lib/process_shared/mutex.rb | ProcessShared.Mutex.sleep | def sleep(timeout = nil)
unlock
begin
timeout ? Kernel.sleep(timeout) : Kernel.sleep
ensure
lock
end
end | ruby | def sleep(timeout = nil)
unlock
begin
timeout ? Kernel.sleep(timeout) : Kernel.sleep
ensure
lock
end
end | [
"def",
"sleep",
"(",
"timeout",
"=",
"nil",
")",
"unlock",
"begin",
"timeout",
"?",
"Kernel",
".",
"sleep",
"(",
"timeout",
")",
":",
"Kernel",
".",
"sleep",
"ensure",
"lock",
"end",
"end"
] | Releases the lock and sleeps timeout seconds if it is given and
non-nil or forever.
@return [Numeric] | [
"Releases",
"the",
"lock",
"and",
"sleeps",
"timeout",
"seconds",
"if",
"it",
"is",
"given",
"and",
"non",
"-",
"nil",
"or",
"forever",
"."
] | 9ef0acb09335c44ac5133bfac566786b038fcd90 | https://github.com/pmahoney/process_shared/blob/9ef0acb09335c44ac5133bfac566786b038fcd90/lib/process_shared/mutex.rb#L52-L59 |
22,861 | pmahoney/process_shared | lib/mach/port.rb | Mach.Port.insert_right | def insert_right(right, opts = {})
ipc_space = opts[:ipc_space] || @ipc_space
port_name = opts[:port_name] || @port
mach_port_insert_right(ipc_space.to_i, port_name.to_i, @port, right)
end | ruby | def insert_right(right, opts = {})
ipc_space = opts[:ipc_space] || @ipc_space
port_name = opts[:port_name] || @port
mach_port_insert_right(ipc_space.to_i, port_name.to_i, @port, right)
end | [
"def",
"insert_right",
"(",
"right",
",",
"opts",
"=",
"{",
"}",
")",
"ipc_space",
"=",
"opts",
"[",
":ipc_space",
"]",
"||",
"@ipc_space",
"port_name",
"=",
"opts",
"[",
":port_name",
"]",
"||",
"@port",
"mach_port_insert_right",
"(",
"ipc_space",
".",
"to_i",
",",
"port_name",
".",
"to_i",
",",
"@port",
",",
"right",
")",
"end"
] | Insert +right+ into another ipc space. The current task must
have sufficient rights to insert the requested right.
@param [MsgType] right
@param [Hash] opts
@option opts [Port,Integer] :ipc_space the space (task port) into which
+right+ will be inserted; defaults to this port's ipc_space
@option opts [Port,Integer] :port the name the port right should
have in :ipc_space; defaults to the same name as this port | [
"Insert",
"+",
"right",
"+",
"into",
"another",
"ipc",
"space",
".",
"The",
"current",
"task",
"must",
"have",
"sufficient",
"rights",
"to",
"insert",
"the",
"requested",
"right",
"."
] | 9ef0acb09335c44ac5133bfac566786b038fcd90 | https://github.com/pmahoney/process_shared/blob/9ef0acb09335c44ac5133bfac566786b038fcd90/lib/mach/port.rb#L88-L93 |
22,862 | pmahoney/process_shared | lib/mach/port.rb | Mach.Port.send_right | def send_right(right, remote_port)
msg = SendRightMsg.new
msg[:header].tap do |h|
h[:remote_port] = remote_port.to_i
h[:local_port] = PORT_NULL
h[:bits] =
(MsgType[right] | (0 << 8)) | 0x80000000 # MACH_MSGH_BITS_COMPLEX
h[:size] = 40 # msg.size
end
msg[:body][:descriptor_count] = 1
msg[:port].tap do |p|
p[:name] = port
p[:disposition] = MsgType[right]
p[:type] = 0 # MSG_PORT_DESCRIPTOR;
end
mach_msg_send msg
end | ruby | def send_right(right, remote_port)
msg = SendRightMsg.new
msg[:header].tap do |h|
h[:remote_port] = remote_port.to_i
h[:local_port] = PORT_NULL
h[:bits] =
(MsgType[right] | (0 << 8)) | 0x80000000 # MACH_MSGH_BITS_COMPLEX
h[:size] = 40 # msg.size
end
msg[:body][:descriptor_count] = 1
msg[:port].tap do |p|
p[:name] = port
p[:disposition] = MsgType[right]
p[:type] = 0 # MSG_PORT_DESCRIPTOR;
end
mach_msg_send msg
end | [
"def",
"send_right",
"(",
"right",
",",
"remote_port",
")",
"msg",
"=",
"SendRightMsg",
".",
"new",
"msg",
"[",
":header",
"]",
".",
"tap",
"do",
"|",
"h",
"|",
"h",
"[",
":remote_port",
"]",
"=",
"remote_port",
".",
"to_i",
"h",
"[",
":local_port",
"]",
"=",
"PORT_NULL",
"h",
"[",
":bits",
"]",
"=",
"(",
"MsgType",
"[",
"right",
"]",
"|",
"(",
"0",
"<<",
"8",
")",
")",
"|",
"0x80000000",
"# MACH_MSGH_BITS_COMPLEX",
"h",
"[",
":size",
"]",
"=",
"40",
"# msg.size",
"end",
"msg",
"[",
":body",
"]",
"[",
":descriptor_count",
"]",
"=",
"1",
"msg",
"[",
":port",
"]",
".",
"tap",
"do",
"|",
"p",
"|",
"p",
"[",
":name",
"]",
"=",
"port",
"p",
"[",
":disposition",
"]",
"=",
"MsgType",
"[",
"right",
"]",
"p",
"[",
":type",
"]",
"=",
"0",
"# MSG_PORT_DESCRIPTOR;",
"end",
"mach_msg_send",
"msg",
"end"
] | Send +right+ on this Port to +remote_port+. The current task
must already have the requisite rights allowing it to send
+right+. | [
"Send",
"+",
"right",
"+",
"on",
"this",
"Port",
"to",
"+",
"remote_port",
"+",
".",
"The",
"current",
"task",
"must",
"already",
"have",
"the",
"requisite",
"rights",
"allowing",
"it",
"to",
"send",
"+",
"right",
"+",
"."
] | 9ef0acb09335c44ac5133bfac566786b038fcd90 | https://github.com/pmahoney/process_shared/blob/9ef0acb09335c44ac5133bfac566786b038fcd90/lib/mach/port.rb#L98-L118 |
22,863 | pmahoney/process_shared | lib/mach/port.rb | Mach.Port.receive_right | def receive_right
msg = ReceiveRightMsg.new
mach_msg(msg,
2, # RCV_MSG,
0,
msg.size,
port,
MSG_TIMEOUT_NONE,
PORT_NULL)
self.class.new :port => msg[:port][:name]
end | ruby | def receive_right
msg = ReceiveRightMsg.new
mach_msg(msg,
2, # RCV_MSG,
0,
msg.size,
port,
MSG_TIMEOUT_NONE,
PORT_NULL)
self.class.new :port => msg[:port][:name]
end | [
"def",
"receive_right",
"msg",
"=",
"ReceiveRightMsg",
".",
"new",
"mach_msg",
"(",
"msg",
",",
"2",
",",
"# RCV_MSG,",
"0",
",",
"msg",
".",
"size",
",",
"port",
",",
"MSG_TIMEOUT_NONE",
",",
"PORT_NULL",
")",
"self",
".",
"class",
".",
"new",
":port",
"=>",
"msg",
"[",
":port",
"]",
"[",
":name",
"]",
"end"
] | Create a new Port by receiving a port right message on this
port. | [
"Create",
"a",
"new",
"Port",
"by",
"receiving",
"a",
"port",
"right",
"message",
"on",
"this",
"port",
"."
] | 9ef0acb09335c44ac5133bfac566786b038fcd90 | https://github.com/pmahoney/process_shared/blob/9ef0acb09335c44ac5133bfac566786b038fcd90/lib/mach/port.rb#L129-L141 |
22,864 | pmahoney/process_shared | lib/mach/semaphore.rb | Mach.Semaphore.destroy | def destroy(opts = {})
task = opts[:task] || ipc_space || mach_task_self
semaphore_destroy(task.to_i, port)
end | ruby | def destroy(opts = {})
task = opts[:task] || ipc_space || mach_task_self
semaphore_destroy(task.to_i, port)
end | [
"def",
"destroy",
"(",
"opts",
"=",
"{",
"}",
")",
"task",
"=",
"opts",
"[",
":task",
"]",
"||",
"ipc_space",
"||",
"mach_task_self",
"semaphore_destroy",
"(",
"task",
".",
"to_i",
",",
"port",
")",
"end"
] | Create a new Semaphore.
@param [Hash] opts
@option opts [Integer] :value the initial value of the
semaphore; defaults to 1
@option opts [Integer] :task the Mach task that owns the
semaphore (defaults to Mach.task_self)
@options opts [Integer] :sync_policy the sync policy for this
semaphore (defaults to SyncPolicy::FIFO)
@options opts [Integer] :port existing port to wrap with a
Semaphore object; otherwise a new semaphore is created
@return [Integer] a semaphore port name
Destroy a Semaphore.
@param [Hash] opts
@option opts [Integer] :task the Mach task that owns the
semaphore (defaults to the owning task) | [
"Create",
"a",
"new",
"Semaphore",
"."
] | 9ef0acb09335c44ac5133bfac566786b038fcd90 | https://github.com/pmahoney/process_shared/blob/9ef0acb09335c44ac5133bfac566786b038fcd90/lib/mach/semaphore.rb#L49-L52 |
22,865 | jdan/rubycards | lib/rubycards/card.rb | RubyCards.Card.suit | def suit(glyph = false)
case @suit
when 1
glyph ? CLUB.black.bold : 'Clubs'
when 2
glyph ? DIAMOND.red : 'Diamonds'
when 3
glyph ? HEART.red : 'Hearts'
when 4
glyph ? SPADE.black.bold : 'Spades'
end
end | ruby | def suit(glyph = false)
case @suit
when 1
glyph ? CLUB.black.bold : 'Clubs'
when 2
glyph ? DIAMOND.red : 'Diamonds'
when 3
glyph ? HEART.red : 'Hearts'
when 4
glyph ? SPADE.black.bold : 'Spades'
end
end | [
"def",
"suit",
"(",
"glyph",
"=",
"false",
")",
"case",
"@suit",
"when",
"1",
"glyph",
"?",
"CLUB",
".",
"black",
".",
"bold",
":",
"'Clubs'",
"when",
"2",
"glyph",
"?",
"DIAMOND",
".",
"red",
":",
"'Diamonds'",
"when",
"3",
"glyph",
"?",
"HEART",
".",
"red",
":",
"'Hearts'",
"when",
"4",
"glyph",
"?",
"SPADE",
".",
"black",
".",
"bold",
":",
"'Spades'",
"end",
"end"
] | Returns the suit of the card.
@param glyph [Boolean] Optional setting to draw a unicode glyph in place
of a word
@return [String] The string (of glyph) representation of the card's suit | [
"Returns",
"the",
"suit",
"of",
"the",
"card",
"."
] | e6e7fda255451844681d43b5a9da2ab2393da052 | https://github.com/jdan/rubycards/blob/e6e7fda255451844681d43b5a9da2ab2393da052/lib/rubycards/card.rb#L45-L56 |
22,866 | enkessler/cql | lib/cql/filters.rb | CQL.TagFilter.has_tags? | def has_tags?(object, target_tags)
target_tags.all? { |target_tag|
tags = object.tags
tags = tags.collect { |tag| tag.name } unless Gem.loaded_specs['cuke_modeler'].version.version[/^0/]
tags.include?(target_tag)
}
end | ruby | def has_tags?(object, target_tags)
target_tags.all? { |target_tag|
tags = object.tags
tags = tags.collect { |tag| tag.name } unless Gem.loaded_specs['cuke_modeler'].version.version[/^0/]
tags.include?(target_tag)
}
end | [
"def",
"has_tags?",
"(",
"object",
",",
"target_tags",
")",
"target_tags",
".",
"all?",
"{",
"|",
"target_tag",
"|",
"tags",
"=",
"object",
".",
"tags",
"tags",
"=",
"tags",
".",
"collect",
"{",
"|",
"tag",
"|",
"tag",
".",
"name",
"}",
"unless",
"Gem",
".",
"loaded_specs",
"[",
"'cuke_modeler'",
"]",
".",
"version",
".",
"version",
"[",
"/",
"/",
"]",
"tags",
".",
"include?",
"(",
"target_tag",
")",
"}",
"end"
] | Creates a new filter
Returns whether or not the object has the target tags | [
"Creates",
"a",
"new",
"filter",
"Returns",
"whether",
"or",
"not",
"the",
"object",
"has",
"the",
"target",
"tags"
] | 4c0b264db64dc02e436e490b9a6286d52d7ab515 | https://github.com/enkessler/cql/blob/4c0b264db64dc02e436e490b9a6286d52d7ab515/lib/cql/filters.rb#L15-L21 |
22,867 | enkessler/cql | lib/cql/filters.rb | CQL.ContentMatchFilter.content_match? | def content_match?(content)
if pattern.is_a?(String)
content.any? { |thing| thing == pattern }
else
content.any? { |thing| thing =~ pattern }
end
end | ruby | def content_match?(content)
if pattern.is_a?(String)
content.any? { |thing| thing == pattern }
else
content.any? { |thing| thing =~ pattern }
end
end | [
"def",
"content_match?",
"(",
"content",
")",
"if",
"pattern",
".",
"is_a?",
"(",
"String",
")",
"content",
".",
"any?",
"{",
"|",
"thing",
"|",
"thing",
"==",
"pattern",
"}",
"else",
"content",
".",
"any?",
"{",
"|",
"thing",
"|",
"thing",
"=~",
"pattern",
"}",
"end",
"end"
] | Creates a new filter
Returns whether or not the content matches the pattern | [
"Creates",
"a",
"new",
"filter",
"Returns",
"whether",
"or",
"not",
"the",
"content",
"matches",
"the",
"pattern"
] | 4c0b264db64dc02e436e490b9a6286d52d7ab515 | https://github.com/enkessler/cql/blob/4c0b264db64dc02e436e490b9a6286d52d7ab515/lib/cql/filters.rb#L46-L52 |
22,868 | enkessler/cql | lib/cql/filters.rb | CQL.TypeCountFilter.execute | def execute(input, negate)
method = negate ? :reject : :select
input.send(method) do |object|
type_count(object).send(comparison.operator, comparison.amount)
end
end | ruby | def execute(input, negate)
method = negate ? :reject : :select
input.send(method) do |object|
type_count(object).send(comparison.operator, comparison.amount)
end
end | [
"def",
"execute",
"(",
"input",
",",
"negate",
")",
"method",
"=",
"negate",
"?",
":reject",
":",
":select",
"input",
".",
"send",
"(",
"method",
")",
"do",
"|",
"object",
"|",
"type_count",
"(",
"object",
")",
".",
"send",
"(",
"comparison",
".",
"operator",
",",
"comparison",
".",
"amount",
")",
"end",
"end"
] | Creates a new filter
Not a part of the public API. Subject to change at any time.
Filters the input models so that only the desired ones are returned | [
"Creates",
"a",
"new",
"filter",
"Not",
"a",
"part",
"of",
"the",
"public",
"API",
".",
"Subject",
"to",
"change",
"at",
"any",
"time",
".",
"Filters",
"the",
"input",
"models",
"so",
"that",
"only",
"the",
"desired",
"ones",
"are",
"returned"
] | 4c0b264db64dc02e436e490b9a6286d52d7ab515 | https://github.com/enkessler/cql/blob/4c0b264db64dc02e436e490b9a6286d52d7ab515/lib/cql/filters.rb#L72-L78 |
22,869 | datacite/bolognese | lib/bolognese/doi_utils.rb | Bolognese.DoiUtils.get_doi_ra | def get_doi_ra(doi)
prefix = validate_prefix(doi)
return nil if prefix.blank?
url = "https://doi.org/ra/#{prefix}"
result = Maremma.get(url)
result.body.dig("data", 0, "RA")
end | ruby | def get_doi_ra(doi)
prefix = validate_prefix(doi)
return nil if prefix.blank?
url = "https://doi.org/ra/#{prefix}"
result = Maremma.get(url)
result.body.dig("data", 0, "RA")
end | [
"def",
"get_doi_ra",
"(",
"doi",
")",
"prefix",
"=",
"validate_prefix",
"(",
"doi",
")",
"return",
"nil",
"if",
"prefix",
".",
"blank?",
"url",
"=",
"\"https://doi.org/ra/#{prefix}\"",
"result",
"=",
"Maremma",
".",
"get",
"(",
"url",
")",
"result",
".",
"body",
".",
"dig",
"(",
"\"data\"",
",",
"0",
",",
"\"RA\"",
")",
"end"
] | get DOI registration agency | [
"get",
"DOI",
"registration",
"agency"
] | 10b8666a6724c0a9508df4547a9f9213bf80b59c | https://github.com/datacite/bolognese/blob/10b8666a6724c0a9508df4547a9f9213bf80b59c/lib/bolognese/doi_utils.rb#L45-L53 |
22,870 | davidesantangelo/emailhunter | lib/email_hunter/api.rb | EmailHunter.Api.search | def search(domain, params = {})
EmailHunter::Search.new(domain, self.key, params).hunt
end | ruby | def search(domain, params = {})
EmailHunter::Search.new(domain, self.key, params).hunt
end | [
"def",
"search",
"(",
"domain",
",",
"params",
"=",
"{",
"}",
")",
"EmailHunter",
"::",
"Search",
".",
"new",
"(",
"domain",
",",
"self",
".",
"key",
",",
"params",
")",
".",
"hunt",
"end"
] | Domain search API | [
"Domain",
"search",
"API"
] | cbb092e4acb57b8cb209119d103128c8833aac63 | https://github.com/davidesantangelo/emailhunter/blob/cbb092e4acb57b8cb209119d103128c8833aac63/lib/email_hunter/api.rb#L18-L20 |
22,871 | davidesantangelo/emailhunter | lib/email_hunter/api.rb | EmailHunter.Api.finder | def finder(domain, first_name, last_name)
EmailHunter::Finder.new(domain, first_name, last_name, self.key).hunt
end | ruby | def finder(domain, first_name, last_name)
EmailHunter::Finder.new(domain, first_name, last_name, self.key).hunt
end | [
"def",
"finder",
"(",
"domain",
",",
"first_name",
",",
"last_name",
")",
"EmailHunter",
"::",
"Finder",
".",
"new",
"(",
"domain",
",",
"first_name",
",",
"last_name",
",",
"self",
".",
"key",
")",
".",
"hunt",
"end"
] | Email Finder API | [
"Email",
"Finder",
"API"
] | cbb092e4acb57b8cb209119d103128c8833aac63 | https://github.com/davidesantangelo/emailhunter/blob/cbb092e4acb57b8cb209119d103128c8833aac63/lib/email_hunter/api.rb#L33-L35 |
22,872 | datacite/bolognese | lib/bolognese/metadata_utils.rb | Bolognese.MetadataUtils.raw | def raw
r = string.present? ? string.strip : nil
return r unless (from == "datacite" && r.present?)
doc = Nokogiri::XML(string, nil, 'UTF-8', &:noblanks)
node = doc.at_css("identifier")
node.content = doi.to_s.upcase if node.present? && doi.present?
doc.to_xml.strip
end | ruby | def raw
r = string.present? ? string.strip : nil
return r unless (from == "datacite" && r.present?)
doc = Nokogiri::XML(string, nil, 'UTF-8', &:noblanks)
node = doc.at_css("identifier")
node.content = doi.to_s.upcase if node.present? && doi.present?
doc.to_xml.strip
end | [
"def",
"raw",
"r",
"=",
"string",
".",
"present?",
"?",
"string",
".",
"strip",
":",
"nil",
"return",
"r",
"unless",
"(",
"from",
"==",
"\"datacite\"",
"&&",
"r",
".",
"present?",
")",
"doc",
"=",
"Nokogiri",
"::",
"XML",
"(",
"string",
",",
"nil",
",",
"'UTF-8'",
",",
":noblanks",
")",
"node",
"=",
"doc",
".",
"at_css",
"(",
"\"identifier\"",
")",
"node",
".",
"content",
"=",
"doi",
".",
"to_s",
".",
"upcase",
"if",
"node",
".",
"present?",
"&&",
"doi",
".",
"present?",
"doc",
".",
"to_xml",
".",
"strip",
"end"
] | replace DOI in XML if provided in options | [
"replace",
"DOI",
"in",
"XML",
"if",
"provided",
"in",
"options"
] | 10b8666a6724c0a9508df4547a9f9213bf80b59c | https://github.com/datacite/bolognese/blob/10b8666a6724c0a9508df4547a9f9213bf80b59c/lib/bolognese/metadata_utils.rb#L69-L77 |
22,873 | datacite/bolognese | lib/bolognese/author_utils.rb | Bolognese.AuthorUtils.get_authors | def get_authors(authors)
Array.wrap(authors).map { |author| get_one_author(author) }.compact
end | ruby | def get_authors(authors)
Array.wrap(authors).map { |author| get_one_author(author) }.compact
end | [
"def",
"get_authors",
"(",
"authors",
")",
"Array",
".",
"wrap",
"(",
"authors",
")",
".",
"map",
"{",
"|",
"author",
"|",
"get_one_author",
"(",
"author",
")",
"}",
".",
"compact",
"end"
] | parse array of author strings into CSL format | [
"parse",
"array",
"of",
"author",
"strings",
"into",
"CSL",
"format"
] | 10b8666a6724c0a9508df4547a9f9213bf80b59c | https://github.com/datacite/bolognese/blob/10b8666a6724c0a9508df4547a9f9213bf80b59c/lib/bolognese/author_utils.rb#L116-L118 |
22,874 | celluloid/dcell | lib/dcell/directory.rb | DCell.Directory.find | def find(id)
return nil unless id
meta = DCell.registry.get_node(id)
DirectoryMeta.new(id, meta)
end | ruby | def find(id)
return nil unless id
meta = DCell.registry.get_node(id)
DirectoryMeta.new(id, meta)
end | [
"def",
"find",
"(",
"id",
")",
"return",
"nil",
"unless",
"id",
"meta",
"=",
"DCell",
".",
"registry",
".",
"get_node",
"(",
"id",
")",
"DirectoryMeta",
".",
"new",
"(",
"id",
",",
"meta",
")",
"end"
] | Get the address for a particular Node ID | [
"Get",
"the",
"address",
"for",
"a",
"particular",
"Node",
"ID"
] | a8fecfae220cb2c20d3761bc27880e4133aba498 | https://github.com/celluloid/dcell/blob/a8fecfae220cb2c20d3761bc27880e4133aba498/lib/dcell/directory.rb#L67-L71 |
22,875 | dicom/rtkit | lib/rtkit/control_point.rb | RTKIT.ControlPoint.add_collimator | def add_collimator(coll)
raise ArgumentError, "Invalid argument 'coll'. Expected CollimatorSetup, got #{coll.class}." unless coll.is_a?(CollimatorSetup)
@collimators << coll unless @associated_collimators[coll.type]
@associated_collimators[coll.type] = coll
end | ruby | def add_collimator(coll)
raise ArgumentError, "Invalid argument 'coll'. Expected CollimatorSetup, got #{coll.class}." unless coll.is_a?(CollimatorSetup)
@collimators << coll unless @associated_collimators[coll.type]
@associated_collimators[coll.type] = coll
end | [
"def",
"add_collimator",
"(",
"coll",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'coll'. Expected CollimatorSetup, got #{coll.class}.\"",
"unless",
"coll",
".",
"is_a?",
"(",
"CollimatorSetup",
")",
"@collimators",
"<<",
"coll",
"unless",
"@associated_collimators",
"[",
"coll",
".",
"type",
"]",
"@associated_collimators",
"[",
"coll",
".",
"type",
"]",
"=",
"coll",
"end"
] | Adds a CollimatorSetup instance to this ControlPoint.
@param [CollimatorSetup] coll a collimator setup instance to be associated with this control point | [
"Adds",
"a",
"CollimatorSetup",
"instance",
"to",
"this",
"ControlPoint",
"."
] | 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/control_point.rb#L132-L136 |
22,876 | dicom/rtkit | lib/rtkit/projection_image.rb | RTKIT.ProjectionImage.load_pixel_data | def load_pixel_data(dcm)
raise ArgumentError, "Invalid argument 'dcm'. Expected DObject, got #{dcm.class}." unless dcm.is_a?(DICOM::DObject)
raise ArgumentError, "Invalid argument 'dcm'. Expected modality 'RTIMAGE', got #{dcm.value(MODALITY)}." unless dcm.value(MODALITY) == 'RTIMAGE'
# Set attributes common for all image modalities, i.e. CT, MR, RTDOSE & RTIMAGE:
@dcm = dcm
@narray = dcm.narray
@date = dcm.value(IMAGE_DATE)
@time = dcm.value(IMAGE_TIME)
@columns = dcm.value(COLUMNS)
@rows = dcm.value(ROWS)
# Some difference in where we pick our values depending on if we have an
# RTIMAGE or another type (e.g. CR):
if @series.modality == 'RTIMAGE'
image_position = dcm.value(RT_IMAGE_POSITION).split("\\")
raise "Invalid DICOM image: 2 basckslash-separated values expected for RT Image Position (Patient), got: #{image_position}" unless image_position.length == 2
@pos_x = image_position[0].to_f
@pos_y = image_position[1].to_f
spacing = dcm.value(IMAGE_PLANE_SPACING).split("\\")
raise "Invalid DICOM image: 2 basckslash-separated values expected for Image Plane Pixel Spacing, got: #{spacing}" unless spacing.length == 2
@col_spacing = spacing[1].to_f
@row_spacing = spacing[0].to_f
else
image_position = dcm.value(IMAGE_POSITION).split("\\")
raise "Invalid DICOM image: 3 basckslash-separated values expected for Image Position (Patient), got: #{image_position}" unless image_position.length == 3
@pos_x = image_position[0].to_f
@pos_y = image_position[1].to_f
spacing = dcm.value(SPACING).split("\\")
raise "Invalid DICOM image: 2 basckslash-separated values expected for Pixel Spacing, got: #{spacing}" unless spacing.length == 2
@col_spacing = spacing[1].to_f
@row_spacing = spacing[0].to_f
end
end | ruby | def load_pixel_data(dcm)
raise ArgumentError, "Invalid argument 'dcm'. Expected DObject, got #{dcm.class}." unless dcm.is_a?(DICOM::DObject)
raise ArgumentError, "Invalid argument 'dcm'. Expected modality 'RTIMAGE', got #{dcm.value(MODALITY)}." unless dcm.value(MODALITY) == 'RTIMAGE'
# Set attributes common for all image modalities, i.e. CT, MR, RTDOSE & RTIMAGE:
@dcm = dcm
@narray = dcm.narray
@date = dcm.value(IMAGE_DATE)
@time = dcm.value(IMAGE_TIME)
@columns = dcm.value(COLUMNS)
@rows = dcm.value(ROWS)
# Some difference in where we pick our values depending on if we have an
# RTIMAGE or another type (e.g. CR):
if @series.modality == 'RTIMAGE'
image_position = dcm.value(RT_IMAGE_POSITION).split("\\")
raise "Invalid DICOM image: 2 basckslash-separated values expected for RT Image Position (Patient), got: #{image_position}" unless image_position.length == 2
@pos_x = image_position[0].to_f
@pos_y = image_position[1].to_f
spacing = dcm.value(IMAGE_PLANE_SPACING).split("\\")
raise "Invalid DICOM image: 2 basckslash-separated values expected for Image Plane Pixel Spacing, got: #{spacing}" unless spacing.length == 2
@col_spacing = spacing[1].to_f
@row_spacing = spacing[0].to_f
else
image_position = dcm.value(IMAGE_POSITION).split("\\")
raise "Invalid DICOM image: 3 basckslash-separated values expected for Image Position (Patient), got: #{image_position}" unless image_position.length == 3
@pos_x = image_position[0].to_f
@pos_y = image_position[1].to_f
spacing = dcm.value(SPACING).split("\\")
raise "Invalid DICOM image: 2 basckslash-separated values expected for Pixel Spacing, got: #{spacing}" unless spacing.length == 2
@col_spacing = spacing[1].to_f
@row_spacing = spacing[0].to_f
end
end | [
"def",
"load_pixel_data",
"(",
"dcm",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'dcm'. Expected DObject, got #{dcm.class}.\"",
"unless",
"dcm",
".",
"is_a?",
"(",
"DICOM",
"::",
"DObject",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'dcm'. Expected modality 'RTIMAGE', got #{dcm.value(MODALITY)}.\"",
"unless",
"dcm",
".",
"value",
"(",
"MODALITY",
")",
"==",
"'RTIMAGE'",
"# Set attributes common for all image modalities, i.e. CT, MR, RTDOSE & RTIMAGE:",
"@dcm",
"=",
"dcm",
"@narray",
"=",
"dcm",
".",
"narray",
"@date",
"=",
"dcm",
".",
"value",
"(",
"IMAGE_DATE",
")",
"@time",
"=",
"dcm",
".",
"value",
"(",
"IMAGE_TIME",
")",
"@columns",
"=",
"dcm",
".",
"value",
"(",
"COLUMNS",
")",
"@rows",
"=",
"dcm",
".",
"value",
"(",
"ROWS",
")",
"# Some difference in where we pick our values depending on if we have an",
"# RTIMAGE or another type (e.g. CR):",
"if",
"@series",
".",
"modality",
"==",
"'RTIMAGE'",
"image_position",
"=",
"dcm",
".",
"value",
"(",
"RT_IMAGE_POSITION",
")",
".",
"split",
"(",
"\"\\\\\"",
")",
"raise",
"\"Invalid DICOM image: 2 basckslash-separated values expected for RT Image Position (Patient), got: #{image_position}\"",
"unless",
"image_position",
".",
"length",
"==",
"2",
"@pos_x",
"=",
"image_position",
"[",
"0",
"]",
".",
"to_f",
"@pos_y",
"=",
"image_position",
"[",
"1",
"]",
".",
"to_f",
"spacing",
"=",
"dcm",
".",
"value",
"(",
"IMAGE_PLANE_SPACING",
")",
".",
"split",
"(",
"\"\\\\\"",
")",
"raise",
"\"Invalid DICOM image: 2 basckslash-separated values expected for Image Plane Pixel Spacing, got: #{spacing}\"",
"unless",
"spacing",
".",
"length",
"==",
"2",
"@col_spacing",
"=",
"spacing",
"[",
"1",
"]",
".",
"to_f",
"@row_spacing",
"=",
"spacing",
"[",
"0",
"]",
".",
"to_f",
"else",
"image_position",
"=",
"dcm",
".",
"value",
"(",
"IMAGE_POSITION",
")",
".",
"split",
"(",
"\"\\\\\"",
")",
"raise",
"\"Invalid DICOM image: 3 basckslash-separated values expected for Image Position (Patient), got: #{image_position}\"",
"unless",
"image_position",
".",
"length",
"==",
"3",
"@pos_x",
"=",
"image_position",
"[",
"0",
"]",
".",
"to_f",
"@pos_y",
"=",
"image_position",
"[",
"1",
"]",
".",
"to_f",
"spacing",
"=",
"dcm",
".",
"value",
"(",
"SPACING",
")",
".",
"split",
"(",
"\"\\\\\"",
")",
"raise",
"\"Invalid DICOM image: 2 basckslash-separated values expected for Pixel Spacing, got: #{spacing}\"",
"unless",
"spacing",
".",
"length",
"==",
"2",
"@col_spacing",
"=",
"spacing",
"[",
"1",
"]",
".",
"to_f",
"@row_spacing",
"=",
"spacing",
"[",
"0",
"]",
".",
"to_f",
"end",
"end"
] | Transfers the pixel data, as well as the related image properties and the
DObject instance itself, to the image instance.
@param [DICOM::DObject] dcm an instance of a DICOM object
@raise [ArgumentError] if the given dicom object doesn't have a projection image type modality | [
"Transfers",
"the",
"pixel",
"data",
"as",
"well",
"as",
"the",
"related",
"image",
"properties",
"and",
"the",
"DObject",
"instance",
"itself",
"to",
"the",
"image",
"instance",
"."
] | 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/projection_image.rb#L71-L102 |
22,877 | dicom/rtkit | lib/rtkit/projection_image.rb | RTKIT.ProjectionImage.create_projection_image_dicom_scaffold | def create_projection_image_dicom_scaffold
# Some tags are created/updated only if no DICOM object already exists:
unless @dcm
# Setup general image attributes:
create_general_dicom_image_scaffold
# Group 3002:
@dcm.add_element(RT_IMAGE_LABEL, @beam.description)
@dcm.add_element(RT_IMAGE_NAME, @beam.name)
@dcm.add_element(RT_IMAGE_DESCRIPTION, @beam.plan.name)
# Note: If support for image plane type 'NON_NORMAL' is added at some
# point, the RT Image Orientation tag (3002,0010) has to be added as well.
@dcm.add_element(RT_IMAGE_PLANE, 'NORMAL')
@dcm.add_element(X_RAY_IMAGE_RECEPTOR_TRANSLATION, '')
@dcm.add_element(X_RAY_IMAGE_RECEPTOR_ANGLE, '')
@dcm.add_element(RADIATION_MACHINE_NAME, @beam.machine)
@dcm.add_element(RADIATION_MACHINE_SAD, @beam.sad)
@dcm.add_element(RADIATION_MACHINE_SSD, @beam.sad)
@dcm.add_element(RT_IMAGE_SID, @beam.sad)
# FIXME: Add Exposure sequence as well (with Jaw and MLC position information)
# Group 300A:
@dcm.add_element(DOSIMETER_UNIT, @beam.unit)
@dcm.add_element(GANTRY_ANGLE, @beam.control_points[0].gantry_angle)
@dcm.add_element(COLL_ANGLE, @beam.control_points[0].collimator_angle)
@dcm.add_element(PEDESTAL_ANGLE, @beam.control_points[0].pedestal_angle)
@dcm.add_element(TABLE_TOP_ANGLE, @beam.control_points[0].table_top_angle)
@dcm.add_element(ISO_POS, @beam.control_points[0].iso.to_s)
@dcm.add_element(GANTRY_PITCH_ANGLE, '0.0')
# Group 300C:
s = @dcm.add_sequence(REF_PLAN_SQ)
i = s.add_item
i.add_element(REF_SOP_CLASS_UID, @beam.plan.class_uid)
i.add_element(REF_SOP_UID, @beam.plan.sop_uid)
@dcm.add_element(REF_BEAM_NUMBER, @beam.number)
end
end | ruby | def create_projection_image_dicom_scaffold
# Some tags are created/updated only if no DICOM object already exists:
unless @dcm
# Setup general image attributes:
create_general_dicom_image_scaffold
# Group 3002:
@dcm.add_element(RT_IMAGE_LABEL, @beam.description)
@dcm.add_element(RT_IMAGE_NAME, @beam.name)
@dcm.add_element(RT_IMAGE_DESCRIPTION, @beam.plan.name)
# Note: If support for image plane type 'NON_NORMAL' is added at some
# point, the RT Image Orientation tag (3002,0010) has to be added as well.
@dcm.add_element(RT_IMAGE_PLANE, 'NORMAL')
@dcm.add_element(X_RAY_IMAGE_RECEPTOR_TRANSLATION, '')
@dcm.add_element(X_RAY_IMAGE_RECEPTOR_ANGLE, '')
@dcm.add_element(RADIATION_MACHINE_NAME, @beam.machine)
@dcm.add_element(RADIATION_MACHINE_SAD, @beam.sad)
@dcm.add_element(RADIATION_MACHINE_SSD, @beam.sad)
@dcm.add_element(RT_IMAGE_SID, @beam.sad)
# FIXME: Add Exposure sequence as well (with Jaw and MLC position information)
# Group 300A:
@dcm.add_element(DOSIMETER_UNIT, @beam.unit)
@dcm.add_element(GANTRY_ANGLE, @beam.control_points[0].gantry_angle)
@dcm.add_element(COLL_ANGLE, @beam.control_points[0].collimator_angle)
@dcm.add_element(PEDESTAL_ANGLE, @beam.control_points[0].pedestal_angle)
@dcm.add_element(TABLE_TOP_ANGLE, @beam.control_points[0].table_top_angle)
@dcm.add_element(ISO_POS, @beam.control_points[0].iso.to_s)
@dcm.add_element(GANTRY_PITCH_ANGLE, '0.0')
# Group 300C:
s = @dcm.add_sequence(REF_PLAN_SQ)
i = s.add_item
i.add_element(REF_SOP_CLASS_UID, @beam.plan.class_uid)
i.add_element(REF_SOP_UID, @beam.plan.sop_uid)
@dcm.add_element(REF_BEAM_NUMBER, @beam.number)
end
end | [
"def",
"create_projection_image_dicom_scaffold",
"# Some tags are created/updated only if no DICOM object already exists:",
"unless",
"@dcm",
"# Setup general image attributes:",
"create_general_dicom_image_scaffold",
"# Group 3002:",
"@dcm",
".",
"add_element",
"(",
"RT_IMAGE_LABEL",
",",
"@beam",
".",
"description",
")",
"@dcm",
".",
"add_element",
"(",
"RT_IMAGE_NAME",
",",
"@beam",
".",
"name",
")",
"@dcm",
".",
"add_element",
"(",
"RT_IMAGE_DESCRIPTION",
",",
"@beam",
".",
"plan",
".",
"name",
")",
"# Note: If support for image plane type 'NON_NORMAL' is added at some",
"# point, the RT Image Orientation tag (3002,0010) has to be added as well.",
"@dcm",
".",
"add_element",
"(",
"RT_IMAGE_PLANE",
",",
"'NORMAL'",
")",
"@dcm",
".",
"add_element",
"(",
"X_RAY_IMAGE_RECEPTOR_TRANSLATION",
",",
"''",
")",
"@dcm",
".",
"add_element",
"(",
"X_RAY_IMAGE_RECEPTOR_ANGLE",
",",
"''",
")",
"@dcm",
".",
"add_element",
"(",
"RADIATION_MACHINE_NAME",
",",
"@beam",
".",
"machine",
")",
"@dcm",
".",
"add_element",
"(",
"RADIATION_MACHINE_SAD",
",",
"@beam",
".",
"sad",
")",
"@dcm",
".",
"add_element",
"(",
"RADIATION_MACHINE_SSD",
",",
"@beam",
".",
"sad",
")",
"@dcm",
".",
"add_element",
"(",
"RT_IMAGE_SID",
",",
"@beam",
".",
"sad",
")",
"# FIXME: Add Exposure sequence as well (with Jaw and MLC position information)",
"# Group 300A:",
"@dcm",
".",
"add_element",
"(",
"DOSIMETER_UNIT",
",",
"@beam",
".",
"unit",
")",
"@dcm",
".",
"add_element",
"(",
"GANTRY_ANGLE",
",",
"@beam",
".",
"control_points",
"[",
"0",
"]",
".",
"gantry_angle",
")",
"@dcm",
".",
"add_element",
"(",
"COLL_ANGLE",
",",
"@beam",
".",
"control_points",
"[",
"0",
"]",
".",
"collimator_angle",
")",
"@dcm",
".",
"add_element",
"(",
"PEDESTAL_ANGLE",
",",
"@beam",
".",
"control_points",
"[",
"0",
"]",
".",
"pedestal_angle",
")",
"@dcm",
".",
"add_element",
"(",
"TABLE_TOP_ANGLE",
",",
"@beam",
".",
"control_points",
"[",
"0",
"]",
".",
"table_top_angle",
")",
"@dcm",
".",
"add_element",
"(",
"ISO_POS",
",",
"@beam",
".",
"control_points",
"[",
"0",
"]",
".",
"iso",
".",
"to_s",
")",
"@dcm",
".",
"add_element",
"(",
"GANTRY_PITCH_ANGLE",
",",
"'0.0'",
")",
"# Group 300C:",
"s",
"=",
"@dcm",
".",
"add_sequence",
"(",
"REF_PLAN_SQ",
")",
"i",
"=",
"s",
".",
"add_item",
"i",
".",
"add_element",
"(",
"REF_SOP_CLASS_UID",
",",
"@beam",
".",
"plan",
".",
"class_uid",
")",
"i",
".",
"add_element",
"(",
"REF_SOP_UID",
",",
"@beam",
".",
"plan",
".",
"sop_uid",
")",
"@dcm",
".",
"add_element",
"(",
"REF_BEAM_NUMBER",
",",
"@beam",
".",
"number",
")",
"end",
"end"
] | Creates a new DICOM object with a set of basic attributes needed
for a valid DICOM file of modality RTIMAGE. | [
"Creates",
"a",
"new",
"DICOM",
"object",
"with",
"a",
"set",
"of",
"basic",
"attributes",
"needed",
"for",
"a",
"valid",
"DICOM",
"file",
"of",
"modality",
"RTIMAGE",
"."
] | 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/projection_image.rb#L152-L186 |
22,878 | dicom/rtkit | lib/rtkit/dose_distribution.rb | RTKIT.DoseDistribution.d | def d(percent)
raise RangeError, "Argument 'percent' must be in the range [0-100]." if percent.to_f < 0 or percent.to_f > 100
d_index = ((@doses.length - 1) * (1 - percent.to_f * 0.01)).round
return @doses[d_index]
end | ruby | def d(percent)
raise RangeError, "Argument 'percent' must be in the range [0-100]." if percent.to_f < 0 or percent.to_f > 100
d_index = ((@doses.length - 1) * (1 - percent.to_f * 0.01)).round
return @doses[d_index]
end | [
"def",
"d",
"(",
"percent",
")",
"raise",
"RangeError",
",",
"\"Argument 'percent' must be in the range [0-100].\"",
"if",
"percent",
".",
"to_f",
"<",
"0",
"or",
"percent",
".",
"to_f",
">",
"100",
"d_index",
"=",
"(",
"(",
"@doses",
".",
"length",
"-",
"1",
")",
"*",
"(",
"1",
"-",
"percent",
".",
"to_f",
"*",
"0.01",
")",
")",
".",
"round",
"return",
"@doses",
"[",
"d_index",
"]",
"end"
] | Calculates the dose that at least the specified
percentage of the volume receives.
@param [#to_f] percent a percentage (number in the range 0-100)
@return [Float] the corresponding dose (in units of Gy)
@example Calculate the near minimum dose (e.g. up to 2 % of the volume receives a dose less than this):
near_min = ptv_distribution.d(98)
@example Calculate the near maximum dose (e.g. at most 2 % of the volume receives a dose higher than this):
near_max = ptv_distribution.d(2) | [
"Calculates",
"the",
"dose",
"that",
"at",
"least",
"the",
"specified",
"percentage",
"of",
"the",
"volume",
"receives",
"."
] | 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/dose_distribution.rb#L80-L84 |
22,879 | dicom/rtkit | lib/rtkit/dose_distribution.rb | RTKIT.DoseDistribution.v | def v(dose)
raise RangeError, "Argument 'dose' cannot be negative." if dose.to_f < 0
# How many dose values are higher than the threshold?
num_above = (@doses.ge dose.to_f).where.length
# Divide by total number of elements and convert to percentage:
return num_above / @doses.length.to_f * 100
end | ruby | def v(dose)
raise RangeError, "Argument 'dose' cannot be negative." if dose.to_f < 0
# How many dose values are higher than the threshold?
num_above = (@doses.ge dose.to_f).where.length
# Divide by total number of elements and convert to percentage:
return num_above / @doses.length.to_f * 100
end | [
"def",
"v",
"(",
"dose",
")",
"raise",
"RangeError",
",",
"\"Argument 'dose' cannot be negative.\"",
"if",
"dose",
".",
"to_f",
"<",
"0",
"# How many dose values are higher than the threshold?",
"num_above",
"=",
"(",
"@doses",
".",
"ge",
"dose",
".",
"to_f",
")",
".",
"where",
".",
"length",
"# Divide by total number of elements and convert to percentage:",
"return",
"num_above",
"/",
"@doses",
".",
"length",
".",
"to_f",
"*",
"100",
"end"
] | Calculates the percentage of the volume that receives a dose higher than
or equal to the specified dose.
@param [#to_f] dose the dose threshold value to apply to the dose distribution (in units of Gy)
@return [Float] the corresponding percentage
@example Calculate the low dose spread (e.g. the percentage of the lung that receives a dose higher than 5 Gy):
coverage_low = lung_distribution.v(5)
@example Calculate the high dose spread (e.g. the percentage of the lung that receives a dose higher than 20 Gy):
coverage_high = lung_distribution.v(20) | [
"Calculates",
"the",
"percentage",
"of",
"the",
"volume",
"that",
"receives",
"a",
"dose",
"higher",
"than",
"or",
"equal",
"to",
"the",
"specified",
"dose",
"."
] | 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/dose_distribution.rb#L203-L209 |
22,880 | slagyr/limelight | ruby/lib/limelight/stage.rb | Limelight.Stage.size= | def size=(*values)
values = values[0] if values.size == 1 && values[0].is_a?(Array)
@peer.set_size_styles(values[0], values[1])
end | ruby | def size=(*values)
values = values[0] if values.size == 1 && values[0].is_a?(Array)
@peer.set_size_styles(values[0], values[1])
end | [
"def",
"size",
"=",
"(",
"*",
"values",
")",
"values",
"=",
"values",
"[",
"0",
"]",
"if",
"values",
".",
"size",
"==",
"1",
"&&",
"values",
"[",
"0",
"]",
".",
"is_a?",
"(",
"Array",
")",
"@peer",
".",
"set_size_styles",
"(",
"values",
"[",
"0",
"]",
",",
"values",
"[",
"1",
"]",
")",
"end"
] | Sets the width and height styles of the Stage.
state.size = [100, 200]
state.size = ["50%", "100%"] # consuming 50% of the width and 100% of the height of the screen | [
"Sets",
"the",
"width",
"and",
"height",
"styles",
"of",
"the",
"Stage",
"."
] | 2e8db684771587422d55a9329e895481e9b56a26 | https://github.com/slagyr/limelight/blob/2e8db684771587422d55a9329e895481e9b56a26/ruby/lib/limelight/stage.rb#L76-L79 |
22,881 | slagyr/limelight | ruby/lib/limelight/stage.rb | Limelight.Stage.location= | def location=(*values)
values = values[0] if values.size == 1 && values[0].is_a?(Array)
@peer.set_location_styles(values[0], values[1])
end | ruby | def location=(*values)
values = values[0] if values.size == 1 && values[0].is_a?(Array)
@peer.set_location_styles(values[0], values[1])
end | [
"def",
"location",
"=",
"(",
"*",
"values",
")",
"values",
"=",
"values",
"[",
"0",
"]",
"if",
"values",
".",
"size",
"==",
"1",
"&&",
"values",
"[",
"0",
"]",
".",
"is_a?",
"(",
"Array",
")",
"@peer",
".",
"set_location_styles",
"(",
"values",
"[",
"0",
"]",
",",
"values",
"[",
"1",
"]",
")",
"end"
] | Sets the location styles of the Stage.
stage.location = [500, 200] | [
"Sets",
"the",
"location",
"styles",
"of",
"the",
"Stage",
"."
] | 2e8db684771587422d55a9329e895481e9b56a26 | https://github.com/slagyr/limelight/blob/2e8db684771587422d55a9329e895481e9b56a26/ruby/lib/limelight/stage.rb#L93-L96 |
22,882 | slagyr/limelight | ruby/lib/limelight/stage.rb | Limelight.Stage.alert | def alert(message)
Thread.new do
begin
Java::limelight.Context.instance.studio.utilities_production.alert(message)
rescue StandardError => e
puts "Error on alert: #{e}"
end
end
end | ruby | def alert(message)
Thread.new do
begin
Java::limelight.Context.instance.studio.utilities_production.alert(message)
rescue StandardError => e
puts "Error on alert: #{e}"
end
end
end | [
"def",
"alert",
"(",
"message",
")",
"Thread",
".",
"new",
"do",
"begin",
"Java",
"::",
"limelight",
".",
"Context",
".",
"instance",
".",
"studio",
".",
"utilities_production",
".",
"alert",
"(",
"message",
")",
"rescue",
"StandardError",
"=>",
"e",
"puts",
"\"Error on alert: #{e}\"",
"end",
"end",
"end"
] | Pops up a simple modal dialog with the provided message. | [
"Pops",
"up",
"a",
"simple",
"modal",
"dialog",
"with",
"the",
"provided",
"message",
"."
] | 2e8db684771587422d55a9329e895481e9b56a26 | https://github.com/slagyr/limelight/blob/2e8db684771587422d55a9329e895481e9b56a26/ruby/lib/limelight/stage.rb#L234-L242 |
22,883 | dicom/rtkit | lib/rtkit/image_series.rb | RTKIT.ImageSeries.add_image | def add_image(image)
raise ArgumentError, "Invalid argument 'image'. Expected Image, got #{image.class}." unless image.is_a?(Image)
@images << image unless @frame.image(image.uid)
@slices[image.uid] = image.pos_slice
@image_positions[image.pos_slice.round(2)] = image
@sop_uids[image.pos_slice] = image.uid
# The link between image uid and image instance is kept in the Frame, instead of the ImageSeries:
@frame.add_image(image) unless @frame.image(image.uid)
end | ruby | def add_image(image)
raise ArgumentError, "Invalid argument 'image'. Expected Image, got #{image.class}." unless image.is_a?(Image)
@images << image unless @frame.image(image.uid)
@slices[image.uid] = image.pos_slice
@image_positions[image.pos_slice.round(2)] = image
@sop_uids[image.pos_slice] = image.uid
# The link between image uid and image instance is kept in the Frame, instead of the ImageSeries:
@frame.add_image(image) unless @frame.image(image.uid)
end | [
"def",
"add_image",
"(",
"image",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'image'. Expected Image, got #{image.class}.\"",
"unless",
"image",
".",
"is_a?",
"(",
"Image",
")",
"@images",
"<<",
"image",
"unless",
"@frame",
".",
"image",
"(",
"image",
".",
"uid",
")",
"@slices",
"[",
"image",
".",
"uid",
"]",
"=",
"image",
".",
"pos_slice",
"@image_positions",
"[",
"image",
".",
"pos_slice",
".",
"round",
"(",
"2",
")",
"]",
"=",
"image",
"@sop_uids",
"[",
"image",
".",
"pos_slice",
"]",
"=",
"image",
".",
"uid",
"# The link between image uid and image instance is kept in the Frame, instead of the ImageSeries:",
"@frame",
".",
"add_image",
"(",
"image",
")",
"unless",
"@frame",
".",
"image",
"(",
"image",
".",
"uid",
")",
"end"
] | Adds an Image to this ImageSeries.
@param [Image] image an image instance to be associated with this image series | [
"Adds",
"an",
"Image",
"to",
"this",
"ImageSeries",
"."
] | 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/image_series.rb#L119-L127 |
22,884 | dicom/rtkit | lib/rtkit/image_series.rb | RTKIT.ImageSeries.add_struct | def add_struct(struct)
raise ArgumentError, "Invalid argument 'struct'. Expected StructureSet, got #{struct.class}." unless struct.is_a?(StructureSet)
# Do not add it again if the struct already belongs to this instance:
@structs << struct unless @associated_structs[struct.uid]
@associated_structs[struct.uid] = struct
end | ruby | def add_struct(struct)
raise ArgumentError, "Invalid argument 'struct'. Expected StructureSet, got #{struct.class}." unless struct.is_a?(StructureSet)
# Do not add it again if the struct already belongs to this instance:
@structs << struct unless @associated_structs[struct.uid]
@associated_structs[struct.uid] = struct
end | [
"def",
"add_struct",
"(",
"struct",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'struct'. Expected StructureSet, got #{struct.class}.\"",
"unless",
"struct",
".",
"is_a?",
"(",
"StructureSet",
")",
"# Do not add it again if the struct already belongs to this instance:",
"@structs",
"<<",
"struct",
"unless",
"@associated_structs",
"[",
"struct",
".",
"uid",
"]",
"@associated_structs",
"[",
"struct",
".",
"uid",
"]",
"=",
"struct",
"end"
] | Adds a StructureSet to this ImageSeries.
@param [Image] struct a structure set instance to be associated with this image series | [
"Adds",
"a",
"StructureSet",
"to",
"this",
"ImageSeries",
"."
] | 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/image_series.rb#L133-L138 |
22,885 | dicom/rtkit | lib/rtkit/image_series.rb | RTKIT.ImageSeries.match_image | def match_image(plane)
raise ArgumentError, "Invalid argument 'plane'. Expected Plane, got #{plane.class}." unless plane.is_a?(Plane)
matching_image = nil
planes_in_series = Array.new
@images.each do |image|
# Get three coordinates from the image:
col_indices = NArray.to_na([0,image.columns/2, image.columns-1])
row_indices = NArray.to_na([image.rows/2, image.rows-1, 0])
x, y, z = image.coordinates_from_indices(col_indices, row_indices)
coordinates = Array.new
x.length.times do |i|
coordinates << Coordinate.new(x[i], y[i], z[i])
end
# Determine the image plane:
planes_in_series << Plane.calculate(coordinates[0], coordinates[1], coordinates[2])
end
# Search for a match amongst the planes of this series:
index = plane.match(planes_in_series)
matching_image = @images[index] if index
return matching_image
end | ruby | def match_image(plane)
raise ArgumentError, "Invalid argument 'plane'. Expected Plane, got #{plane.class}." unless plane.is_a?(Plane)
matching_image = nil
planes_in_series = Array.new
@images.each do |image|
# Get three coordinates from the image:
col_indices = NArray.to_na([0,image.columns/2, image.columns-1])
row_indices = NArray.to_na([image.rows/2, image.rows-1, 0])
x, y, z = image.coordinates_from_indices(col_indices, row_indices)
coordinates = Array.new
x.length.times do |i|
coordinates << Coordinate.new(x[i], y[i], z[i])
end
# Determine the image plane:
planes_in_series << Plane.calculate(coordinates[0], coordinates[1], coordinates[2])
end
# Search for a match amongst the planes of this series:
index = plane.match(planes_in_series)
matching_image = @images[index] if index
return matching_image
end | [
"def",
"match_image",
"(",
"plane",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'plane'. Expected Plane, got #{plane.class}.\"",
"unless",
"plane",
".",
"is_a?",
"(",
"Plane",
")",
"matching_image",
"=",
"nil",
"planes_in_series",
"=",
"Array",
".",
"new",
"@images",
".",
"each",
"do",
"|",
"image",
"|",
"# Get three coordinates from the image:",
"col_indices",
"=",
"NArray",
".",
"to_na",
"(",
"[",
"0",
",",
"image",
".",
"columns",
"/",
"2",
",",
"image",
".",
"columns",
"-",
"1",
"]",
")",
"row_indices",
"=",
"NArray",
".",
"to_na",
"(",
"[",
"image",
".",
"rows",
"/",
"2",
",",
"image",
".",
"rows",
"-",
"1",
",",
"0",
"]",
")",
"x",
",",
"y",
",",
"z",
"=",
"image",
".",
"coordinates_from_indices",
"(",
"col_indices",
",",
"row_indices",
")",
"coordinates",
"=",
"Array",
".",
"new",
"x",
".",
"length",
".",
"times",
"do",
"|",
"i",
"|",
"coordinates",
"<<",
"Coordinate",
".",
"new",
"(",
"x",
"[",
"i",
"]",
",",
"y",
"[",
"i",
"]",
",",
"z",
"[",
"i",
"]",
")",
"end",
"# Determine the image plane:",
"planes_in_series",
"<<",
"Plane",
".",
"calculate",
"(",
"coordinates",
"[",
"0",
"]",
",",
"coordinates",
"[",
"1",
"]",
",",
"coordinates",
"[",
"2",
"]",
")",
"end",
"# Search for a match amongst the planes of this series:",
"index",
"=",
"plane",
".",
"match",
"(",
"planes_in_series",
")",
"matching_image",
"=",
"@images",
"[",
"index",
"]",
"if",
"index",
"return",
"matching_image",
"end"
] | Analyses the images belonging to this ImageSeries to determine if there
is any image with a geometry that matches the specified plane.
@param [Plane] plane an image plane to be compared against the associated images
@return [SliceImage, NilClass] the matched image (or nil if no image is matched) | [
"Analyses",
"the",
"images",
"belonging",
"to",
"this",
"ImageSeries",
"to",
"determine",
"if",
"there",
"is",
"any",
"image",
"with",
"a",
"geometry",
"that",
"matches",
"the",
"specified",
"plane",
"."
] | 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/image_series.rb#L213-L233 |
22,886 | dicom/rtkit | lib/rtkit/image_series.rb | RTKIT.ImageSeries.set_resolution | def set_resolution(columns, rows, options={})
@images.each do |img|
img.set_resolution(columns, rows, options)
end
end | ruby | def set_resolution(columns, rows, options={})
@images.each do |img|
img.set_resolution(columns, rows, options)
end
end | [
"def",
"set_resolution",
"(",
"columns",
",",
"rows",
",",
"options",
"=",
"{",
"}",
")",
"@images",
".",
"each",
"do",
"|",
"img",
"|",
"img",
".",
"set_resolution",
"(",
"columns",
",",
"rows",
",",
"options",
")",
"end",
"end"
] | Sets the resolution of the associated images. The images will either be
expanded or cropped depending on whether the specified resolution is
bigger or smaller than the existing one.
@param [Integer] columns the number of columns in the resized images
@param [Integer] rows the number of rows in the resized images
@param [Hash] options the options to use for changing the image resolution
@option options [Float] :hor the side (in the horisontal image direction) at which to apply the crop/border operation (:left, :right or :even (default))
@option options [Float] :ver the side (in the vertical image direction) at which to apply the crop/border operation (:bottom, :top or :even (default)) | [
"Sets",
"the",
"resolution",
"of",
"the",
"associated",
"images",
".",
"The",
"images",
"will",
"either",
"be",
"expanded",
"or",
"cropped",
"depending",
"on",
"whether",
"the",
"specified",
"resolution",
"is",
"bigger",
"or",
"smaller",
"than",
"the",
"existing",
"one",
"."
] | 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/image_series.rb#L245-L249 |
22,887 | dicom/rtkit | lib/rtkit/image_series.rb | RTKIT.ImageSeries.struct | def struct(*args)
raise ArgumentError, "Expected one or none arguments, got #{args.length}." unless [0, 1].include?(args.length)
if args.length == 1
raise ArgumentError, "Expected String (or nil), got #{args.first.class}." unless [String, NilClass].include?(args.first.class)
return @associated_structs[args.first]
else
# No argument used, therefore we return the first StructureSet instance:
return @structs.first
end
end | ruby | def struct(*args)
raise ArgumentError, "Expected one or none arguments, got #{args.length}." unless [0, 1].include?(args.length)
if args.length == 1
raise ArgumentError, "Expected String (or nil), got #{args.first.class}." unless [String, NilClass].include?(args.first.class)
return @associated_structs[args.first]
else
# No argument used, therefore we return the first StructureSet instance:
return @structs.first
end
end | [
"def",
"struct",
"(",
"*",
"args",
")",
"raise",
"ArgumentError",
",",
"\"Expected one or none arguments, got #{args.length}.\"",
"unless",
"[",
"0",
",",
"1",
"]",
".",
"include?",
"(",
"args",
".",
"length",
")",
"if",
"args",
".",
"length",
"==",
"1",
"raise",
"ArgumentError",
",",
"\"Expected String (or nil), got #{args.first.class}.\"",
"unless",
"[",
"String",
",",
"NilClass",
"]",
".",
"include?",
"(",
"args",
".",
"first",
".",
"class",
")",
"return",
"@associated_structs",
"[",
"args",
".",
"first",
"]",
"else",
"# No argument used, therefore we return the first StructureSet instance:",
"return",
"@structs",
".",
"first",
"end",
"end"
] | Gives the StructureSet instance mathcing the specified UID.
@overload struct(uid)
@param [String] uid the structure set SOP instance UID
@return [StructureSet, NilClass] the matched structure set (or nil if no structure set is matched)
@overload struct
@return [StructureSet, NilClass] the first structure set of this instance (or nil if no child structure sets exists) | [
"Gives",
"the",
"StructureSet",
"instance",
"mathcing",
"the",
"specified",
"UID",
"."
] | 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/image_series.rb#L259-L268 |
22,888 | dicom/rtkit | lib/rtkit/drr/pixel_space.rb | RTKIT.PixelSpace.coordinate | def coordinate(i, j)
x = @pos.x + (i * @delta_col * @cosines[0]) + (j * @delta_row * @cosines[3])
y = @pos.y + (i * @delta_col * @cosines[1]) + (j * @delta_row * @cosines[4])
z = @pos.z + (i * @delta_col * @cosines[2]) + (j * @delta_row * @cosines[5])
Coordinate.new(x, y, z)
end | ruby | def coordinate(i, j)
x = @pos.x + (i * @delta_col * @cosines[0]) + (j * @delta_row * @cosines[3])
y = @pos.y + (i * @delta_col * @cosines[1]) + (j * @delta_row * @cosines[4])
z = @pos.z + (i * @delta_col * @cosines[2]) + (j * @delta_row * @cosines[5])
Coordinate.new(x, y, z)
end | [
"def",
"coordinate",
"(",
"i",
",",
"j",
")",
"x",
"=",
"@pos",
".",
"x",
"+",
"(",
"i",
"*",
"@delta_col",
"*",
"@cosines",
"[",
"0",
"]",
")",
"+",
"(",
"j",
"*",
"@delta_row",
"*",
"@cosines",
"[",
"3",
"]",
")",
"y",
"=",
"@pos",
".",
"y",
"+",
"(",
"i",
"*",
"@delta_col",
"*",
"@cosines",
"[",
"1",
"]",
")",
"+",
"(",
"j",
"*",
"@delta_row",
"*",
"@cosines",
"[",
"4",
"]",
")",
"z",
"=",
"@pos",
".",
"z",
"+",
"(",
"i",
"*",
"@delta_col",
"*",
"@cosines",
"[",
"2",
"]",
")",
"+",
"(",
"j",
"*",
"@delta_row",
"*",
"@cosines",
"[",
"5",
"]",
")",
"Coordinate",
".",
"new",
"(",
"x",
",",
"y",
",",
"z",
")",
"end"
] | Calculates the cartesian coordinate of the given pixel index pair.
@param [Integer] i the image column index
@param [Integer] j the image row index
@return [Coordinate] the cartesian coordinate of the pixel | [
"Calculates",
"the",
"cartesian",
"coordinate",
"of",
"the",
"given",
"pixel",
"index",
"pair",
"."
] | 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/drr/pixel_space.rb#L118-L123 |
22,889 | dicom/rtkit | lib/rtkit/drr/pixel_space.rb | RTKIT.PixelSpace.cosines= | def cosines=(array)
raise ArgumentError, "Invalid parameter 'array'. Exactly 6 elements needed, got #{array.length}" unless array.length == 6
@cosines = array.collect {|val| val.to_f}
end | ruby | def cosines=(array)
raise ArgumentError, "Invalid parameter 'array'. Exactly 6 elements needed, got #{array.length}" unless array.length == 6
@cosines = array.collect {|val| val.to_f}
end | [
"def",
"cosines",
"=",
"(",
"array",
")",
"raise",
"ArgumentError",
",",
"\"Invalid parameter 'array'. Exactly 6 elements needed, got #{array.length}\"",
"unless",
"array",
".",
"length",
"==",
"6",
"@cosines",
"=",
"array",
".",
"collect",
"{",
"|",
"val",
"|",
"val",
".",
"to_f",
"}",
"end"
] | Sets the cosines attribute.
@param [Array<Float>] array the 6 directional cosines which describes the orientation of the image | [
"Sets",
"the",
"cosines",
"attribute",
"."
] | 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/drr/pixel_space.rb#L129-L132 |
22,890 | dicom/rtkit | lib/rtkit/slice_image.rb | RTKIT.SliceImage.binary_image | def binary_image(coords_x, coords_y, coords_z)
# FIXME: Should we test whether the coordinates go outside the bounds of this image, and
# give a descriptive warning/error instead of letting the code crash with a more cryptic error?!
raise ArgumentError, "Invalid argument 'coords_x'. Expected at least 3 elements, got #{coords_x.length}" unless coords_x.length >= 3
raise ArgumentError, "Invalid argument 'coords_y'. Expected at least 3 elements, got #{coords_y.length}" unless coords_y.length >= 3
raise ArgumentError, "Invalid argument 'coords_z'. Expected at least 3 elements, got #{coords_z.length}" unless coords_z.length >= 3
# Values that will be used for image geometry:
empty_value = 0
line_value = 1
fill_value = 2
# Convert physical coordinates to image indices:
column_indices, row_indices = coordinates_to_indices(NArray.to_na(coords_x), NArray.to_na(coords_y), NArray.to_na(coords_z))
# Create an empty array and fill in the gathered points:
empty_array = NArray.byte(@columns, @rows)
delineated_array = draw_lines(column_indices.to_a, row_indices.to_a, empty_array, line_value)
# Establish starting point indices for the coming flood fill algorithm:
# (Using a rather simple approach by finding the average column and row index among the selection of indices)
start_col = column_indices.mean
start_row = row_indices.mean
# Perform a flood fill to enable us to extract all pixels contained in a specific ROI:
filled_array = flood_fill(start_col, start_row, delineated_array, fill_value)
# Extract the indices of 'ROI pixels':
if filled_array[0,0] != fill_value
# ROI has been filled as expected. Extract indices of value line_value and fill_value:
filled_array[(filled_array.eq line_value).where] = fill_value
indices = (filled_array.eq fill_value).where
else
# An inversion has occured. The entire image except our ROI has been filled. Extract indices of value line_value and empty_value:
filled_array[(filled_array.eq line_value).where] = empty_value
indices = (filled_array.eq empty_value).where
end
# Create binary image:
bin_image = NArray.byte(@columns, @rows)
bin_image[indices] = 1
return bin_image
end | ruby | def binary_image(coords_x, coords_y, coords_z)
# FIXME: Should we test whether the coordinates go outside the bounds of this image, and
# give a descriptive warning/error instead of letting the code crash with a more cryptic error?!
raise ArgumentError, "Invalid argument 'coords_x'. Expected at least 3 elements, got #{coords_x.length}" unless coords_x.length >= 3
raise ArgumentError, "Invalid argument 'coords_y'. Expected at least 3 elements, got #{coords_y.length}" unless coords_y.length >= 3
raise ArgumentError, "Invalid argument 'coords_z'. Expected at least 3 elements, got #{coords_z.length}" unless coords_z.length >= 3
# Values that will be used for image geometry:
empty_value = 0
line_value = 1
fill_value = 2
# Convert physical coordinates to image indices:
column_indices, row_indices = coordinates_to_indices(NArray.to_na(coords_x), NArray.to_na(coords_y), NArray.to_na(coords_z))
# Create an empty array and fill in the gathered points:
empty_array = NArray.byte(@columns, @rows)
delineated_array = draw_lines(column_indices.to_a, row_indices.to_a, empty_array, line_value)
# Establish starting point indices for the coming flood fill algorithm:
# (Using a rather simple approach by finding the average column and row index among the selection of indices)
start_col = column_indices.mean
start_row = row_indices.mean
# Perform a flood fill to enable us to extract all pixels contained in a specific ROI:
filled_array = flood_fill(start_col, start_row, delineated_array, fill_value)
# Extract the indices of 'ROI pixels':
if filled_array[0,0] != fill_value
# ROI has been filled as expected. Extract indices of value line_value and fill_value:
filled_array[(filled_array.eq line_value).where] = fill_value
indices = (filled_array.eq fill_value).where
else
# An inversion has occured. The entire image except our ROI has been filled. Extract indices of value line_value and empty_value:
filled_array[(filled_array.eq line_value).where] = empty_value
indices = (filled_array.eq empty_value).where
end
# Create binary image:
bin_image = NArray.byte(@columns, @rows)
bin_image[indices] = 1
return bin_image
end | [
"def",
"binary_image",
"(",
"coords_x",
",",
"coords_y",
",",
"coords_z",
")",
"# FIXME: Should we test whether the coordinates go outside the bounds of this image, and",
"# give a descriptive warning/error instead of letting the code crash with a more cryptic error?!",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'coords_x'. Expected at least 3 elements, got #{coords_x.length}\"",
"unless",
"coords_x",
".",
"length",
">=",
"3",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'coords_y'. Expected at least 3 elements, got #{coords_y.length}\"",
"unless",
"coords_y",
".",
"length",
">=",
"3",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'coords_z'. Expected at least 3 elements, got #{coords_z.length}\"",
"unless",
"coords_z",
".",
"length",
">=",
"3",
"# Values that will be used for image geometry:",
"empty_value",
"=",
"0",
"line_value",
"=",
"1",
"fill_value",
"=",
"2",
"# Convert physical coordinates to image indices:",
"column_indices",
",",
"row_indices",
"=",
"coordinates_to_indices",
"(",
"NArray",
".",
"to_na",
"(",
"coords_x",
")",
",",
"NArray",
".",
"to_na",
"(",
"coords_y",
")",
",",
"NArray",
".",
"to_na",
"(",
"coords_z",
")",
")",
"# Create an empty array and fill in the gathered points:",
"empty_array",
"=",
"NArray",
".",
"byte",
"(",
"@columns",
",",
"@rows",
")",
"delineated_array",
"=",
"draw_lines",
"(",
"column_indices",
".",
"to_a",
",",
"row_indices",
".",
"to_a",
",",
"empty_array",
",",
"line_value",
")",
"# Establish starting point indices for the coming flood fill algorithm:",
"# (Using a rather simple approach by finding the average column and row index among the selection of indices)",
"start_col",
"=",
"column_indices",
".",
"mean",
"start_row",
"=",
"row_indices",
".",
"mean",
"# Perform a flood fill to enable us to extract all pixels contained in a specific ROI:",
"filled_array",
"=",
"flood_fill",
"(",
"start_col",
",",
"start_row",
",",
"delineated_array",
",",
"fill_value",
")",
"# Extract the indices of 'ROI pixels':",
"if",
"filled_array",
"[",
"0",
",",
"0",
"]",
"!=",
"fill_value",
"# ROI has been filled as expected. Extract indices of value line_value and fill_value:",
"filled_array",
"[",
"(",
"filled_array",
".",
"eq",
"line_value",
")",
".",
"where",
"]",
"=",
"fill_value",
"indices",
"=",
"(",
"filled_array",
".",
"eq",
"fill_value",
")",
".",
"where",
"else",
"# An inversion has occured. The entire image except our ROI has been filled. Extract indices of value line_value and empty_value:",
"filled_array",
"[",
"(",
"filled_array",
".",
"eq",
"line_value",
")",
".",
"where",
"]",
"=",
"empty_value",
"indices",
"=",
"(",
"filled_array",
".",
"eq",
"empty_value",
")",
".",
"where",
"end",
"# Create binary image:",
"bin_image",
"=",
"NArray",
".",
"byte",
"(",
"@columns",
",",
"@rows",
")",
"bin_image",
"[",
"indices",
"]",
"=",
"1",
"return",
"bin_image",
"end"
] | Creates a new SliceImage instance. The SOP Instance UID tag value is
used to uniquely identify an image.
@param [String] sop_uid the SOP Instance UID value
@param [String] pos_slice the slice position of this image
@param [Series] series the Series instance which this SliceImage is associated with
@raise [ArgumentError] if the referenced series doesn't have a slice image type modality
Creates a filled, binary NArray image ('segmented' image) based on the
provided contour coordinates.
@param [Array, NArray] coords_x the contour's x coordinates
@param [Array, NArray] coords_y the contour's y coordinates
@param [Array, NArray] coords_z the contour's z coordinates
@return [BinImage] a filled, binary image
@raise [ArgumentError] if any of the coordinate arrays have less than 3 elements | [
"Creates",
"a",
"new",
"SliceImage",
"instance",
".",
"The",
"SOP",
"Instance",
"UID",
"tag",
"value",
"is",
"used",
"to",
"uniquely",
"identify",
"an",
"image",
"."
] | 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/slice_image.rb#L68-L103 |
22,891 | dicom/rtkit | lib/rtkit/slice_image.rb | RTKIT.SliceImage.to_dcm | def to_dcm
# Setup general dicom image attributes:
create_slice_image_dicom_scaffold
update_dicom_image
# Add/update tags that are specific for the slice image type:
@dcm.add_element(IMAGE_POSITION, [@pos_x, @pos_y, @pos_slice].join("\\"))
@dcm.add_element(SPACING, [@row_spacing, @col_spacing].join("\\"))
@dcm.add_element(IMAGE_ORIENTATION, [@cosines].join("\\"))
@dcm
end | ruby | def to_dcm
# Setup general dicom image attributes:
create_slice_image_dicom_scaffold
update_dicom_image
# Add/update tags that are specific for the slice image type:
@dcm.add_element(IMAGE_POSITION, [@pos_x, @pos_y, @pos_slice].join("\\"))
@dcm.add_element(SPACING, [@row_spacing, @col_spacing].join("\\"))
@dcm.add_element(IMAGE_ORIENTATION, [@cosines].join("\\"))
@dcm
end | [
"def",
"to_dcm",
"# Setup general dicom image attributes:",
"create_slice_image_dicom_scaffold",
"update_dicom_image",
"# Add/update tags that are specific for the slice image type:",
"@dcm",
".",
"add_element",
"(",
"IMAGE_POSITION",
",",
"[",
"@pos_x",
",",
"@pos_y",
",",
"@pos_slice",
"]",
".",
"join",
"(",
"\"\\\\\"",
")",
")",
"@dcm",
".",
"add_element",
"(",
"SPACING",
",",
"[",
"@row_spacing",
",",
"@col_spacing",
"]",
".",
"join",
"(",
"\"\\\\\"",
")",
")",
"@dcm",
".",
"add_element",
"(",
"IMAGE_ORIENTATION",
",",
"[",
"@cosines",
"]",
".",
"join",
"(",
"\"\\\\\"",
")",
")",
"@dcm",
"end"
] | Converts the Image instance to a DICOM object.
@note This method uses the image's original DICOM object (if present),
and updates it with attributes from the image instance.
@return [DICOM::DObject] the processed DICOM object | [
"Converts",
"the",
"Image",
"instance",
"to",
"a",
"DICOM",
"object",
"."
] | 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/slice_image.rb#L170-L179 |
22,892 | dicom/rtkit | lib/rtkit/bin_volume.rb | RTKIT.BinVolume.to_roi | def to_roi(struct, options={})
raise ArgumentError, "Invalid argument 'struct'. Expected StructureSet, got #{struct.class}." unless struct.is_a?(StructureSet)
# Set values:
algorithm = options[:algorithm]
name = options[:name] || 'BinVolume'
number = options[:number]
interpreter = options[:interpreter]
type = options[:type]
# Create the ROI:
roi = struct.create_roi(@series.frame, :algorithm => algorithm, :name => name, :number => number, :interpreter => interpreter, :type => type)
# Create Slices:
@bin_images.each do |bin_image|
bin_image.to_slice(roi)
end
return roi
end | ruby | def to_roi(struct, options={})
raise ArgumentError, "Invalid argument 'struct'. Expected StructureSet, got #{struct.class}." unless struct.is_a?(StructureSet)
# Set values:
algorithm = options[:algorithm]
name = options[:name] || 'BinVolume'
number = options[:number]
interpreter = options[:interpreter]
type = options[:type]
# Create the ROI:
roi = struct.create_roi(@series.frame, :algorithm => algorithm, :name => name, :number => number, :interpreter => interpreter, :type => type)
# Create Slices:
@bin_images.each do |bin_image|
bin_image.to_slice(roi)
end
return roi
end | [
"def",
"to_roi",
"(",
"struct",
",",
"options",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'struct'. Expected StructureSet, got #{struct.class}.\"",
"unless",
"struct",
".",
"is_a?",
"(",
"StructureSet",
")",
"# Set values:",
"algorithm",
"=",
"options",
"[",
":algorithm",
"]",
"name",
"=",
"options",
"[",
":name",
"]",
"||",
"'BinVolume'",
"number",
"=",
"options",
"[",
":number",
"]",
"interpreter",
"=",
"options",
"[",
":interpreter",
"]",
"type",
"=",
"options",
"[",
":type",
"]",
"# Create the ROI:",
"roi",
"=",
"struct",
".",
"create_roi",
"(",
"@series",
".",
"frame",
",",
":algorithm",
"=>",
"algorithm",
",",
":name",
"=>",
"name",
",",
":number",
"=>",
"number",
",",
":interpreter",
"=>",
"interpreter",
",",
":type",
"=>",
"type",
")",
"# Create Slices:",
"@bin_images",
".",
"each",
"do",
"|",
"bin_image",
"|",
"bin_image",
".",
"to_slice",
"(",
"roi",
")",
"end",
"return",
"roi",
"end"
] | Creates a ROI instance from the segmentation of this BinVolume.
@param [StructureSet] struct the structure set instance which the created ROI will be associated with
@param [Hash] options the options to use for creating the ROI
@option options [String] :algorithm the ROI generation algorithm (defaults to 'STATIC')
@option options [String] :name the ROI name (defaults to 'BinVolume')
@option options [Integer] :number the ROI number (defaults to the first available ROI Number in the StructureSet)
@option options [String] :interpreter the ROI interpreter (defaults to 'RTKIT')
@option options [String] :type the ROI interpreted type (defaults to 'CONTROL')
@return [ROI] the created ROI instance (including slice references from the associated binary images) | [
"Creates",
"a",
"ROI",
"instance",
"from",
"the",
"segmentation",
"of",
"this",
"BinVolume",
"."
] | 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/bin_volume.rb#L250-L265 |
22,893 | dicom/rtkit | lib/rtkit/bin_image.rb | RTKIT.BinImage.narray= | def narray=(image)
raise ArgumentError, "Invalid argument 'image'. Expected NArray, got #{image.class}." unless image.is_a?(NArray)
raise ArgumentError, "Invalid argument 'image'. Expected two-dimensional NArray, got #{image.shape.length} dimensions." unless image.shape.length == 2
raise ArgumentError, "Invalid argument 'image'. Expected NArray of element size 1 byte, got #{image.element_size} bytes (per element)." unless image.element_size == 1
raise ArgumentError, "Invalid argument 'image'. Expected binary NArray with max value 1, got #{image.max} as max." if image.max > 1
@narray = image
# Create a corresponding array of the image indices (used in image processing):
@narray_indices = NArray.int(columns, rows).indgen!
end | ruby | def narray=(image)
raise ArgumentError, "Invalid argument 'image'. Expected NArray, got #{image.class}." unless image.is_a?(NArray)
raise ArgumentError, "Invalid argument 'image'. Expected two-dimensional NArray, got #{image.shape.length} dimensions." unless image.shape.length == 2
raise ArgumentError, "Invalid argument 'image'. Expected NArray of element size 1 byte, got #{image.element_size} bytes (per element)." unless image.element_size == 1
raise ArgumentError, "Invalid argument 'image'. Expected binary NArray with max value 1, got #{image.max} as max." if image.max > 1
@narray = image
# Create a corresponding array of the image indices (used in image processing):
@narray_indices = NArray.int(columns, rows).indgen!
end | [
"def",
"narray",
"=",
"(",
"image",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'image'. Expected NArray, got #{image.class}.\"",
"unless",
"image",
".",
"is_a?",
"(",
"NArray",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'image'. Expected two-dimensional NArray, got #{image.shape.length} dimensions.\"",
"unless",
"image",
".",
"shape",
".",
"length",
"==",
"2",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'image'. Expected NArray of element size 1 byte, got #{image.element_size} bytes (per element).\"",
"unless",
"image",
".",
"element_size",
"==",
"1",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'image'. Expected binary NArray with max value 1, got #{image.max} as max.\"",
"if",
"image",
".",
"max",
">",
"1",
"@narray",
"=",
"image",
"# Create a corresponding array of the image indices (used in image processing):",
"@narray_indices",
"=",
"NArray",
".",
"int",
"(",
"columns",
",",
"rows",
")",
".",
"indgen!",
"end"
] | Sets a new binary array for this BinImage instance.
@param [NArray] image a binary two-dimensional array | [
"Sets",
"a",
"new",
"binary",
"array",
"for",
"this",
"BinImage",
"instance",
"."
] | 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/bin_image.rb#L207-L215 |
22,894 | dicom/rtkit | lib/rtkit/bin_image.rb | RTKIT.BinImage.to_contours | def to_contours(slice)
raise ArgumentError, "Invalid argument 'slice. Expected Slice, got #{slice.class}." unless slice.is_a?(Slice)
contours = Array.new
# Iterate the extracted collection of contour indices and convert to Contour instances:
contour_indices.each do |contour|
# Convert column and row indices to X, Y and Z coordinates:
x, y, z = coordinates_from_indices(NArray.to_na(contour.columns), NArray.to_na(contour.rows))
# Convert NArray to Array and round the coordinate floats:
x = x.to_a.collect {|f| f.round(1)}
y = y.to_a.collect {|f| f.round(1)}
z = z.to_a.collect {|f| f.round(3)}
contours << Contour.create_from_coordinates(x, y, z, slice)
end
return contours
end | ruby | def to_contours(slice)
raise ArgumentError, "Invalid argument 'slice. Expected Slice, got #{slice.class}." unless slice.is_a?(Slice)
contours = Array.new
# Iterate the extracted collection of contour indices and convert to Contour instances:
contour_indices.each do |contour|
# Convert column and row indices to X, Y and Z coordinates:
x, y, z = coordinates_from_indices(NArray.to_na(contour.columns), NArray.to_na(contour.rows))
# Convert NArray to Array and round the coordinate floats:
x = x.to_a.collect {|f| f.round(1)}
y = y.to_a.collect {|f| f.round(1)}
z = z.to_a.collect {|f| f.round(3)}
contours << Contour.create_from_coordinates(x, y, z, slice)
end
return contours
end | [
"def",
"to_contours",
"(",
"slice",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'slice. Expected Slice, got #{slice.class}.\"",
"unless",
"slice",
".",
"is_a?",
"(",
"Slice",
")",
"contours",
"=",
"Array",
".",
"new",
"# Iterate the extracted collection of contour indices and convert to Contour instances:",
"contour_indices",
".",
"each",
"do",
"|",
"contour",
"|",
"# Convert column and row indices to X, Y and Z coordinates:",
"x",
",",
"y",
",",
"z",
"=",
"coordinates_from_indices",
"(",
"NArray",
".",
"to_na",
"(",
"contour",
".",
"columns",
")",
",",
"NArray",
".",
"to_na",
"(",
"contour",
".",
"rows",
")",
")",
"# Convert NArray to Array and round the coordinate floats:",
"x",
"=",
"x",
".",
"to_a",
".",
"collect",
"{",
"|",
"f",
"|",
"f",
".",
"round",
"(",
"1",
")",
"}",
"y",
"=",
"y",
".",
"to_a",
".",
"collect",
"{",
"|",
"f",
"|",
"f",
".",
"round",
"(",
"1",
")",
"}",
"z",
"=",
"z",
".",
"to_a",
".",
"collect",
"{",
"|",
"f",
"|",
"f",
".",
"round",
"(",
"3",
")",
"}",
"contours",
"<<",
"Contour",
".",
"create_from_coordinates",
"(",
"x",
",",
"y",
",",
"z",
",",
"slice",
")",
"end",
"return",
"contours",
"end"
] | Creates an array of Contour instances from the segmentation of this BinImage.
@param [Slice] slice the Slice instance which the created contours will be associated with
@return [Array<Contour>] an array of contour instances (or an empty array if no contours are created) | [
"Creates",
"an",
"array",
"of",
"Contour",
"instances",
"from",
"the",
"segmentation",
"of",
"this",
"BinImage",
"."
] | 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/bin_image.rb#L291-L305 |
22,895 | dicom/rtkit | lib/rtkit/bin_image.rb | RTKIT.BinImage.to_dcm | def to_dcm
# Use the original DICOM object as a starting point (keeping all non-sequence elements):
# Note: Something like dcm.dup doesn't work here because that only performs a shallow copy on the DObject instance.
dcm = DICOM::DObject.new
@image.dcm.each_element do |element|
# A bit of a hack to regenerate the DICOM elements:
begin
if element.value
# ATM this fails for tags with integer values converted to a backslash-separated string:
DICOM::Element.new(element.tag, element.value, :parent => dcm)
else
# Transfer the binary content as long as it is not the pixel data string:
DICOM::Element.new(element.tag, element.bin, :encoded => true, :parent => dcm)
end
rescue
DICOM::Element.new(element.tag, element.value.split("\\").collect {|val| val.to_i}, :parent => dcm) if element.value
end
end
dcm.delete_group('0002')
# Format the DICOM image ensure good contrast amongst the binary pixel values:
# Window Center:
DICOM::Element.new('0028,1050', '128', :parent => dcm)
# Window Width:
DICOM::Element.new('0028,1051', '256', :parent => dcm)
# Rescale Intercept:
DICOM::Element.new('0028,1052', '0', :parent => dcm)
# Rescale Slope:
DICOM::Element.new('0028,1053', '1', :parent => dcm)
# Pixel data:
dcm.pixels = @narray*255
return dcm
end | ruby | def to_dcm
# Use the original DICOM object as a starting point (keeping all non-sequence elements):
# Note: Something like dcm.dup doesn't work here because that only performs a shallow copy on the DObject instance.
dcm = DICOM::DObject.new
@image.dcm.each_element do |element|
# A bit of a hack to regenerate the DICOM elements:
begin
if element.value
# ATM this fails for tags with integer values converted to a backslash-separated string:
DICOM::Element.new(element.tag, element.value, :parent => dcm)
else
# Transfer the binary content as long as it is not the pixel data string:
DICOM::Element.new(element.tag, element.bin, :encoded => true, :parent => dcm)
end
rescue
DICOM::Element.new(element.tag, element.value.split("\\").collect {|val| val.to_i}, :parent => dcm) if element.value
end
end
dcm.delete_group('0002')
# Format the DICOM image ensure good contrast amongst the binary pixel values:
# Window Center:
DICOM::Element.new('0028,1050', '128', :parent => dcm)
# Window Width:
DICOM::Element.new('0028,1051', '256', :parent => dcm)
# Rescale Intercept:
DICOM::Element.new('0028,1052', '0', :parent => dcm)
# Rescale Slope:
DICOM::Element.new('0028,1053', '1', :parent => dcm)
# Pixel data:
dcm.pixels = @narray*255
return dcm
end | [
"def",
"to_dcm",
"# Use the original DICOM object as a starting point (keeping all non-sequence elements):",
"# Note: Something like dcm.dup doesn't work here because that only performs a shallow copy on the DObject instance.",
"dcm",
"=",
"DICOM",
"::",
"DObject",
".",
"new",
"@image",
".",
"dcm",
".",
"each_element",
"do",
"|",
"element",
"|",
"# A bit of a hack to regenerate the DICOM elements:",
"begin",
"if",
"element",
".",
"value",
"# ATM this fails for tags with integer values converted to a backslash-separated string:",
"DICOM",
"::",
"Element",
".",
"new",
"(",
"element",
".",
"tag",
",",
"element",
".",
"value",
",",
":parent",
"=>",
"dcm",
")",
"else",
"# Transfer the binary content as long as it is not the pixel data string:",
"DICOM",
"::",
"Element",
".",
"new",
"(",
"element",
".",
"tag",
",",
"element",
".",
"bin",
",",
":encoded",
"=>",
"true",
",",
":parent",
"=>",
"dcm",
")",
"end",
"rescue",
"DICOM",
"::",
"Element",
".",
"new",
"(",
"element",
".",
"tag",
",",
"element",
".",
"value",
".",
"split",
"(",
"\"\\\\\"",
")",
".",
"collect",
"{",
"|",
"val",
"|",
"val",
".",
"to_i",
"}",
",",
":parent",
"=>",
"dcm",
")",
"if",
"element",
".",
"value",
"end",
"end",
"dcm",
".",
"delete_group",
"(",
"'0002'",
")",
"# Format the DICOM image ensure good contrast amongst the binary pixel values:",
"# Window Center:",
"DICOM",
"::",
"Element",
".",
"new",
"(",
"'0028,1050'",
",",
"'128'",
",",
":parent",
"=>",
"dcm",
")",
"# Window Width:",
"DICOM",
"::",
"Element",
".",
"new",
"(",
"'0028,1051'",
",",
"'256'",
",",
":parent",
"=>",
"dcm",
")",
"# Rescale Intercept:",
"DICOM",
"::",
"Element",
".",
"new",
"(",
"'0028,1052'",
",",
"'0'",
",",
":parent",
"=>",
"dcm",
")",
"# Rescale Slope:",
"DICOM",
"::",
"Element",
".",
"new",
"(",
"'0028,1053'",
",",
"'1'",
",",
":parent",
"=>",
"dcm",
")",
"# Pixel data:",
"dcm",
".",
"pixels",
"=",
"@narray",
"255",
"return",
"dcm",
"end"
] | Creates a DICOM object from the BinImage instance. This is achieved by
copying the elements of the DICOM object of the Image instance
referenced by this BinImage, and replacing its pixel data with the
NArray of this instance.
@return [DICOM::DObject] the created DICOM object | [
"Creates",
"a",
"DICOM",
"object",
"from",
"the",
"BinImage",
"instance",
".",
"This",
"is",
"achieved",
"by",
"copying",
"the",
"elements",
"of",
"the",
"DICOM",
"object",
"of",
"the",
"Image",
"instance",
"referenced",
"by",
"this",
"BinImage",
"and",
"replacing",
"its",
"pixel",
"data",
"with",
"the",
"NArray",
"of",
"this",
"instance",
"."
] | 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/bin_image.rb#L314-L345 |
22,896 | dicom/rtkit | lib/rtkit/bin_image.rb | RTKIT.BinImage.to_slice | def to_slice(roi)
raise ArgumentError, "Invalid argument 'roi'. Expected ROI, got #{roi.class}." unless roi.is_a?(ROI)
# Create the Slice:
s = Slice.new(@image.uid, roi)
# Create Contours:
to_contours(s)
return s
end | ruby | def to_slice(roi)
raise ArgumentError, "Invalid argument 'roi'. Expected ROI, got #{roi.class}." unless roi.is_a?(ROI)
# Create the Slice:
s = Slice.new(@image.uid, roi)
# Create Contours:
to_contours(s)
return s
end | [
"def",
"to_slice",
"(",
"roi",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'roi'. Expected ROI, got #{roi.class}.\"",
"unless",
"roi",
".",
"is_a?",
"(",
"ROI",
")",
"# Create the Slice:",
"s",
"=",
"Slice",
".",
"new",
"(",
"@image",
".",
"uid",
",",
"roi",
")",
"# Create Contours:",
"to_contours",
"(",
"s",
")",
"return",
"s",
"end"
] | Creates a Slice instance from the segmentation of this BinImage.
@param [ROI] roi the ROI instance which the created Slice will be associated with
@return [Slice] the created slice instance (including contour references if the binary image is segmented) | [
"Creates",
"a",
"Slice",
"instance",
"from",
"the",
"segmentation",
"of",
"this",
"BinImage",
"."
] | 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/bin_image.rb#L352-L359 |
22,897 | dicom/rtkit | lib/rtkit/bin_image.rb | RTKIT.BinImage.external_contour | def external_contour
start_index = (@narray > 0).where[0] - 1
s_col, s_row = indices_general_to_specific(start_index, columns)
col, row = s_col, s_row
row_indices = Array.new(1, row)
col_indices = Array.new(1, col)
last_dir = :north # on first step, pretend we came from the south (going north)
directions = {
:north => {:dir => [:east, :north, :west, :south], :col => [1, 0, -1, 0], :row => [0, -1, 0, 1]},
:east => {:dir => [:south, :east, :north, :west], :col => [0, 1, 0, -1], :row => [1, 0, -1, 0]},
:south => {:dir => [:west, :south, :east, :north], :col => [-1, 0, 1, 0], :row => [0, 1, 0, -1]},
:west => {:dir => [:north, :west, :south, :east], :col => [0, -1, 0, 1], :row => [-1, 0, 1, 0]},
}
loop = true
while loop do
# Probe the neighbourhood pixels in a CCW order:
map = directions[last_dir]
4.times do |i|
# Find the first 'free' (zero) pixel, and make that index
# the next pixel of our external contour:
if @narray[col + map[:col][i], row + map[:row][i]] == 0
last_dir = map[:dir][i]
col = col + map[:col][i]
row = row + map[:row][i]
col_indices << col
row_indices << row
break
end
end
loop = false if col == s_col and row == s_row
end
return Selection.create_from_array(indices_specific_to_general(col_indices, row_indices, columns), self)
end | ruby | def external_contour
start_index = (@narray > 0).where[0] - 1
s_col, s_row = indices_general_to_specific(start_index, columns)
col, row = s_col, s_row
row_indices = Array.new(1, row)
col_indices = Array.new(1, col)
last_dir = :north # on first step, pretend we came from the south (going north)
directions = {
:north => {:dir => [:east, :north, :west, :south], :col => [1, 0, -1, 0], :row => [0, -1, 0, 1]},
:east => {:dir => [:south, :east, :north, :west], :col => [0, 1, 0, -1], :row => [1, 0, -1, 0]},
:south => {:dir => [:west, :south, :east, :north], :col => [-1, 0, 1, 0], :row => [0, 1, 0, -1]},
:west => {:dir => [:north, :west, :south, :east], :col => [0, -1, 0, 1], :row => [-1, 0, 1, 0]},
}
loop = true
while loop do
# Probe the neighbourhood pixels in a CCW order:
map = directions[last_dir]
4.times do |i|
# Find the first 'free' (zero) pixel, and make that index
# the next pixel of our external contour:
if @narray[col + map[:col][i], row + map[:row][i]] == 0
last_dir = map[:dir][i]
col = col + map[:col][i]
row = row + map[:row][i]
col_indices << col
row_indices << row
break
end
end
loop = false if col == s_col and row == s_row
end
return Selection.create_from_array(indices_specific_to_general(col_indices, row_indices, columns), self)
end | [
"def",
"external_contour",
"start_index",
"=",
"(",
"@narray",
">",
"0",
")",
".",
"where",
"[",
"0",
"]",
"-",
"1",
"s_col",
",",
"s_row",
"=",
"indices_general_to_specific",
"(",
"start_index",
",",
"columns",
")",
"col",
",",
"row",
"=",
"s_col",
",",
"s_row",
"row_indices",
"=",
"Array",
".",
"new",
"(",
"1",
",",
"row",
")",
"col_indices",
"=",
"Array",
".",
"new",
"(",
"1",
",",
"col",
")",
"last_dir",
"=",
":north",
"# on first step, pretend we came from the south (going north)",
"directions",
"=",
"{",
":north",
"=>",
"{",
":dir",
"=>",
"[",
":east",
",",
":north",
",",
":west",
",",
":south",
"]",
",",
":col",
"=>",
"[",
"1",
",",
"0",
",",
"-",
"1",
",",
"0",
"]",
",",
":row",
"=>",
"[",
"0",
",",
"-",
"1",
",",
"0",
",",
"1",
"]",
"}",
",",
":east",
"=>",
"{",
":dir",
"=>",
"[",
":south",
",",
":east",
",",
":north",
",",
":west",
"]",
",",
":col",
"=>",
"[",
"0",
",",
"1",
",",
"0",
",",
"-",
"1",
"]",
",",
":row",
"=>",
"[",
"1",
",",
"0",
",",
"-",
"1",
",",
"0",
"]",
"}",
",",
":south",
"=>",
"{",
":dir",
"=>",
"[",
":west",
",",
":south",
",",
":east",
",",
":north",
"]",
",",
":col",
"=>",
"[",
"-",
"1",
",",
"0",
",",
"1",
",",
"0",
"]",
",",
":row",
"=>",
"[",
"0",
",",
"1",
",",
"0",
",",
"-",
"1",
"]",
"}",
",",
":west",
"=>",
"{",
":dir",
"=>",
"[",
":north",
",",
":west",
",",
":south",
",",
":east",
"]",
",",
":col",
"=>",
"[",
"0",
",",
"-",
"1",
",",
"0",
",",
"1",
"]",
",",
":row",
"=>",
"[",
"-",
"1",
",",
"0",
",",
"1",
",",
"0",
"]",
"}",
",",
"}",
"loop",
"=",
"true",
"while",
"loop",
"do",
"# Probe the neighbourhood pixels in a CCW order:",
"map",
"=",
"directions",
"[",
"last_dir",
"]",
"4",
".",
"times",
"do",
"|",
"i",
"|",
"# Find the first 'free' (zero) pixel, and make that index",
"# the next pixel of our external contour:",
"if",
"@narray",
"[",
"col",
"+",
"map",
"[",
":col",
"]",
"[",
"i",
"]",
",",
"row",
"+",
"map",
"[",
":row",
"]",
"[",
"i",
"]",
"]",
"==",
"0",
"last_dir",
"=",
"map",
"[",
":dir",
"]",
"[",
"i",
"]",
"col",
"=",
"col",
"+",
"map",
"[",
":col",
"]",
"[",
"i",
"]",
"row",
"=",
"row",
"+",
"map",
"[",
":row",
"]",
"[",
"i",
"]",
"col_indices",
"<<",
"col",
"row_indices",
"<<",
"row",
"break",
"end",
"end",
"loop",
"=",
"false",
"if",
"col",
"==",
"s_col",
"and",
"row",
"==",
"s_row",
"end",
"return",
"Selection",
".",
"create_from_array",
"(",
"indices_specific_to_general",
"(",
"col_indices",
",",
"row_indices",
",",
"columns",
")",
",",
"self",
")",
"end"
] | Determines a set of pixel indices which enclose the structure.
@see This implementation uses Roman Khudeevs algorithm:
A New Flood-Fill Algorithm for Closed Contour.
https://docs.google.com/viewer?a=v&q=cache:UZ6bo7pXRoIJ:file.lw23.com/file1/01611214.pdf+flood+fill+from+contour+coordinate&hl=no&gl=no&pid=bl&srcid=ADGEEShV4gbKYYq8cDagjT7poT677cIL44K0QW8SR0ODanFy-CD1CHEQi2RvHF8MND7_PXPGYRJMJAcMJO-NEXkM-vU4iA2rNljVetbzuARWuHtKLJKMTNjd3vaDWrIeSU4rKLCVwvff&sig=AHIEtbSAnH6fp584c0_Krv298n-tgpNcJw&pli=1
@return [Selection] the contour's indices | [
"Determines",
"a",
"set",
"of",
"pixel",
"indices",
"which",
"enclose",
"the",
"structure",
"."
] | 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/bin_image.rb#L373-L405 |
22,898 | dicom/rtkit | lib/rtkit/bin_image.rb | RTKIT.BinImage.extract_contours | def extract_contours
contours = Array.new
if @narray.segmented?
# Get contours:
corners, continuous = extract_single_contour
# If we dont get at least 3 indices, there is no area to fill.
if continuous.indices.length < 3
# In this case we remove the pixels and do not record the contour indices:
roi = continuous
else
# Record the indices and get all indices of the structure:
contours << corners
# Flood fill the image to determine all pixels contained by the contoured structure:
roi = roi_indices(continuous)
# A precaution:
raise "Unexpected result: #{roi.indices.length}. Raising an error to avoid an infinite recursion!" if roi.indices.length < 3
end
# Reset the pixels belonging to the contoured structure from the image:
@narray[roi.indices] = 0
# Repeat with the 'cleaned' image to get any additional contours present:
contours += extract_contours
end
return contours
end | ruby | def extract_contours
contours = Array.new
if @narray.segmented?
# Get contours:
corners, continuous = extract_single_contour
# If we dont get at least 3 indices, there is no area to fill.
if continuous.indices.length < 3
# In this case we remove the pixels and do not record the contour indices:
roi = continuous
else
# Record the indices and get all indices of the structure:
contours << corners
# Flood fill the image to determine all pixels contained by the contoured structure:
roi = roi_indices(continuous)
# A precaution:
raise "Unexpected result: #{roi.indices.length}. Raising an error to avoid an infinite recursion!" if roi.indices.length < 3
end
# Reset the pixels belonging to the contoured structure from the image:
@narray[roi.indices] = 0
# Repeat with the 'cleaned' image to get any additional contours present:
contours += extract_contours
end
return contours
end | [
"def",
"extract_contours",
"contours",
"=",
"Array",
".",
"new",
"if",
"@narray",
".",
"segmented?",
"# Get contours:",
"corners",
",",
"continuous",
"=",
"extract_single_contour",
"# If we dont get at least 3 indices, there is no area to fill.",
"if",
"continuous",
".",
"indices",
".",
"length",
"<",
"3",
"# In this case we remove the pixels and do not record the contour indices:",
"roi",
"=",
"continuous",
"else",
"# Record the indices and get all indices of the structure:",
"contours",
"<<",
"corners",
"# Flood fill the image to determine all pixels contained by the contoured structure:",
"roi",
"=",
"roi_indices",
"(",
"continuous",
")",
"# A precaution:",
"raise",
"\"Unexpected result: #{roi.indices.length}. Raising an error to avoid an infinite recursion!\"",
"if",
"roi",
".",
"indices",
".",
"length",
"<",
"3",
"end",
"# Reset the pixels belonging to the contoured structure from the image:",
"@narray",
"[",
"roi",
".",
"indices",
"]",
"=",
"0",
"# Repeat with the 'cleaned' image to get any additional contours present:",
"contours",
"+=",
"extract_contours",
"end",
"return",
"contours",
"end"
] | This is a recursive method which extracts a contour, determines all pixels
belonging to this contour, removes them from the binary image, then
repeats collecting contours until there are no more pixels left.
@return [Array<Selection>] an array of indices for all the contours derived from the segmented image | [
"This",
"is",
"a",
"recursive",
"method",
"which",
"extracts",
"a",
"contour",
"determines",
"all",
"pixels",
"belonging",
"to",
"this",
"contour",
"removes",
"them",
"from",
"the",
"binary",
"image",
"then",
"repeats",
"collecting",
"contours",
"until",
"there",
"are",
"no",
"more",
"pixels",
"left",
"."
] | 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/bin_image.rb#L413-L436 |
22,899 | dicom/rtkit | lib/rtkit/bin_image.rb | RTKIT.BinImage.initialize_contour_reorder_structures | def initialize_contour_reorder_structures
@reorder = Hash.new
@reorder[:west] = NArray[0,1,2,5,8,7,6,3]
@reorder[:nw] = NArray[1,2,5,8,7,6,3,0]
@reorder[:north] = NArray[2,5,8,7,6,3,0,1]
@reorder[:ne] = NArray[5,8,7,6,3,0,1,2]
@reorder[:east] = NArray[8,7,6,3,0,1,2,5]
@reorder[:se] = NArray[7,6,3,0,1,2,5,8]
@reorder[:south] = NArray[6,3,0,1,2,5,8,7]
@reorder[:sw] = NArray[3,0,1,2,5,8,7,6]
@arrived_from_directions = Hash.new
@arrived_from_directions[0] = :se
@arrived_from_directions[1] = :south
@arrived_from_directions[2] = :sw
@arrived_from_directions[3] = :east
@arrived_from_directions[5] = :west
@arrived_from_directions[6] = :ne
@arrived_from_directions[7] = :north
@arrived_from_directions[8] = :nw
# Set up the index of pixels in a neighborhood image extract:
@relative_indices = NArray.int(3, 3).indgen!
end | ruby | def initialize_contour_reorder_structures
@reorder = Hash.new
@reorder[:west] = NArray[0,1,2,5,8,7,6,3]
@reorder[:nw] = NArray[1,2,5,8,7,6,3,0]
@reorder[:north] = NArray[2,5,8,7,6,3,0,1]
@reorder[:ne] = NArray[5,8,7,6,3,0,1,2]
@reorder[:east] = NArray[8,7,6,3,0,1,2,5]
@reorder[:se] = NArray[7,6,3,0,1,2,5,8]
@reorder[:south] = NArray[6,3,0,1,2,5,8,7]
@reorder[:sw] = NArray[3,0,1,2,5,8,7,6]
@arrived_from_directions = Hash.new
@arrived_from_directions[0] = :se
@arrived_from_directions[1] = :south
@arrived_from_directions[2] = :sw
@arrived_from_directions[3] = :east
@arrived_from_directions[5] = :west
@arrived_from_directions[6] = :ne
@arrived_from_directions[7] = :north
@arrived_from_directions[8] = :nw
# Set up the index of pixels in a neighborhood image extract:
@relative_indices = NArray.int(3, 3).indgen!
end | [
"def",
"initialize_contour_reorder_structures",
"@reorder",
"=",
"Hash",
".",
"new",
"@reorder",
"[",
":west",
"]",
"=",
"NArray",
"[",
"0",
",",
"1",
",",
"2",
",",
"5",
",",
"8",
",",
"7",
",",
"6",
",",
"3",
"]",
"@reorder",
"[",
":nw",
"]",
"=",
"NArray",
"[",
"1",
",",
"2",
",",
"5",
",",
"8",
",",
"7",
",",
"6",
",",
"3",
",",
"0",
"]",
"@reorder",
"[",
":north",
"]",
"=",
"NArray",
"[",
"2",
",",
"5",
",",
"8",
",",
"7",
",",
"6",
",",
"3",
",",
"0",
",",
"1",
"]",
"@reorder",
"[",
":ne",
"]",
"=",
"NArray",
"[",
"5",
",",
"8",
",",
"7",
",",
"6",
",",
"3",
",",
"0",
",",
"1",
",",
"2",
"]",
"@reorder",
"[",
":east",
"]",
"=",
"NArray",
"[",
"8",
",",
"7",
",",
"6",
",",
"3",
",",
"0",
",",
"1",
",",
"2",
",",
"5",
"]",
"@reorder",
"[",
":se",
"]",
"=",
"NArray",
"[",
"7",
",",
"6",
",",
"3",
",",
"0",
",",
"1",
",",
"2",
",",
"5",
",",
"8",
"]",
"@reorder",
"[",
":south",
"]",
"=",
"NArray",
"[",
"6",
",",
"3",
",",
"0",
",",
"1",
",",
"2",
",",
"5",
",",
"8",
",",
"7",
"]",
"@reorder",
"[",
":sw",
"]",
"=",
"NArray",
"[",
"3",
",",
"0",
",",
"1",
",",
"2",
",",
"5",
",",
"8",
",",
"7",
",",
"6",
"]",
"@arrived_from_directions",
"=",
"Hash",
".",
"new",
"@arrived_from_directions",
"[",
"0",
"]",
"=",
":se",
"@arrived_from_directions",
"[",
"1",
"]",
"=",
":south",
"@arrived_from_directions",
"[",
"2",
"]",
"=",
":sw",
"@arrived_from_directions",
"[",
"3",
"]",
"=",
":east",
"@arrived_from_directions",
"[",
"5",
"]",
"=",
":west",
"@arrived_from_directions",
"[",
"6",
"]",
"=",
":ne",
"@arrived_from_directions",
"[",
"7",
"]",
"=",
":north",
"@arrived_from_directions",
"[",
"8",
"]",
"=",
":nw",
"# Set up the index of pixels in a neighborhood image extract:",
"@relative_indices",
"=",
"NArray",
".",
"int",
"(",
"3",
",",
"3",
")",
".",
"indgen!",
"end"
] | Initializes a couple of instance variables containing directional information, which are used by the contour algorithm.
The directional vectors of indices are used for extracting a vector of neighbour pixels from a 3*3 pixel array,
where the resulting vector contains 7 neighbour pixels (the previous pixel is removed), in a clockwise order,
where the first pixel is the neighbour pixel that is next to the previous pixel, following a clockwise rotation. | [
"Initializes",
"a",
"couple",
"of",
"instance",
"variables",
"containing",
"directional",
"information",
"which",
"are",
"used",
"by",
"the",
"contour",
"algorithm",
"."
] | 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/bin_image.rb#L525-L546 |
Subsets and Splits