_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q22800 | Layer.Conversation.contents | train | 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 | {
"resource": ""
} |
q22801 | Layer.Conversation.delete | train | def delete(options = {})
options = { mode: :my_devices }.merge(options)
client.delete(url, {}, { params: options })
end | ruby | {
"resource": ""
} |
q22802 | Dante.Runner.execute | train | 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 | {
"resource": ""
} |
q22803 | Dante.Runner.stop | train | 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 | {
"resource": ""
} |
q22804 | Dante.Runner.daemon_running? | train | 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 | {
"resource": ""
} |
q22805 | Grack.GitAdapter.handle_pack | train | 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 | {
"resource": ""
} |
q22806 | Grack.GitAdapter.command | train | 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 | {
"resource": ""
} |
q22807 | Grack.App.route | train | 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 | {
"resource": ""
} |
q22808 | Grack.App.handle_pack | train | 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 | {
"resource": ""
} |
q22809 | Grack.App.info_refs | train | 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 | {
"resource": ""
} |
q22810 | Grack.App.send_file | train | 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 | {
"resource": ""
} |
q22811 | Grack.App.exchange_pack | train | 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 | {
"resource": ""
} |
q22812 | Grack.App.bad_uri? | train | def bad_uri?(path)
invalid_segments = %w{. ..}
path.split('/').any? { |segment| invalid_segments.include?(segment) }
end | ruby | {
"resource": ""
} |
q22813 | OxfordDictionary.Request.search_endpoint_url | train | 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 | {
"resource": ""
} |
q22814 | Danger.DangerCheckstyleFormat.report | train | 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 | {
"resource": ""
} |
q22815 | Danger.DangerCheckstyleFormat.report_by_text | train | 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 | {
"resource": ""
} |
q22816 | Mobvious.Manager.call | train | 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 | {
"resource": ""
} |
q22817 | Aviator.Session.authenticate | train | 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 | {
"resource": ""
} |
q22818 | CachedResource.Configuration.sample_range | train | def sample_range(range, seed=nil)
srand seed if seed
rand * (range.end - range.begin) + range.begin
end | ruby | {
"resource": ""
} |
q22819 | Twitter.JSONStream.receive_stream_data | train | 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 | {
"resource": ""
} |
q22820 | Twitter.JSONStream.oauth_header | train | 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 | {
"resource": ""
} |
q22821 | Twitter.JSONStream.params | train | 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 | {
"resource": ""
} |
q22822 | Crowdin.API.add_file | train | 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 | {
"resource": ""
} |
q22823 | Crowdin.API.update_file | train | 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 | {
"resource": ""
} |
q22824 | Crowdin.API.upload_translation | train | 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 | {
"resource": ""
} |
q22825 | Crowdin.API.request | train | 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 | {
"resource": ""
} |
q22826 | Heartcheck.App.call | train | 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 | {
"resource": ""
} |
q22827 | Heartcheck.App.dispatch_action | train | 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 | {
"resource": ""
} |
q22828 | RedisPagination.Paginator.paginate | train | 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 | {
"resource": ""
} |
q22829 | Heartcheck.CachingApp.call | train | 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 | {
"resource": ""
} |
q22830 | Mork.GridOMR.rx | train | 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 | {
"resource": ""
} |
q22831 | Mork.GridPDF.qnum_xy | train | def qnum_xy(q)
[
item_x(q).mm - qnum_width - qnum_margin,
item_y(q).mm
]
end | ruby | {
"resource": ""
} |
q22832 | Mork.SheetOMR.marked_letters | train | def marked_letters
return if not_registered
marked_choices.map do |q|
q.map { |cho| (65+cho).chr }
end
end | ruby | {
"resource": ""
} |
q22833 | Sprockets.Redirect.redirect_to_digest_version | train | 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 | {
"resource": ""
} |
q22834 | Mork.Mimage.register | train | def register
each_corner { |c| @rm[c] = rm_centroid_on c }
@rm.all? { |k,v| v[:status] == :ok }
end | ruby | {
"resource": ""
} |
q22835 | Mork.Mimage.rm_centroid_on | train | 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 | {
"resource": ""
} |
q22836 | ExceptionNotifier.ExceptionTrackNotifier.headers_for_env | train | 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 | {
"resource": ""
} |
q22837 | Yardstick.RuleConfig.exclude? | train | def exclude?(path)
exclude.include?(path) ||
exclude.include?(path.split(METHOD_SEPARATOR).first)
end | ruby | {
"resource": ""
} |
q22838 | Yardstick.DocumentSet.measure | train | def measure(config)
reduce(MeasurementSet.new) do |set, document|
set.merge(Document.measure(document, config))
end
end | ruby | {
"resource": ""
} |
q22839 | Yardstick.Config.for_rule | train | 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 | {
"resource": ""
} |
q22840 | Yardstick.Config.defaults= | train | 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 | {
"resource": ""
} |
q22841 | S3Sync.Node.compare_small_comparators | train | 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 | {
"resource": ""
} |
q22842 | Statistics.HasStats.define_calculated_statistic | train | 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 | {
"resource": ""
} |
q22843 | Statistics.HasStats.statistics | train | 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 | {
"resource": ""
} |
q22844 | Keychain.Keychain.add_to_search_list | train | 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 | {
"resource": ""
} |
q22845 | Keychain.Keychain.import | train | 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 | {
"resource": ""
} |
q22846 | Keychain.Keychain.path | train | 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 | {
"resource": ""
} |
q22847 | Keychain.Keychain.unlock! | train | 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 | {
"resource": ""
} |
q22848 | Keychain.Item.password | train | 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 | {
"resource": ""
} |
q22849 | Keychain.Item.save! | train | 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 | {
"resource": ""
} |
q22850 | Net.DAV.propfind | train | 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 | {
"resource": ""
} |
q22851 | Net.DAV.cd | train | 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 | {
"resource": ""
} |
q22852 | Net.DAV.get | train | def get(path, &block)
path = @uri.merge(path).path
body = @handler.request_returning_body(:get, path, @headers, &block)
body
end | ruby | {
"resource": ""
} |
q22853 | Net.DAV.put | train | def put(path, stream, length)
path = @uri.merge(path).path
res = @handler.request_sending_stream(:put, path, stream, length, @headers)
res.body
end | ruby | {
"resource": ""
} |
q22854 | Net.DAV.put_string | train | def put_string(path, str)
path = @uri.merge(path).path
res = @handler.request_sending_body(:put, path, str, @headers)
res.body
end | ruby | {
"resource": ""
} |
q22855 | Net.DAV.move | train | 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 | {
"resource": ""
} |
q22856 | Net.DAV.proppatch | train | 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 | {
"resource": ""
} |
q22857 | Net.DAV.unlock | train | def unlock(path, locktoken)
headers = {'Lock-Token' => '<'+locktoken+'>'}
path = @uri.merge(path).path
res = @handler.request(:unlock, path, nil, headers.merge(@headers))
end | ruby | {
"resource": ""
} |
q22858 | Net.DAV.exists? | train | 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 | {
"resource": ""
} |
q22859 | Sec.Base.keychain | train | 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 | {
"resource": ""
} |
q22860 | ProcessShared.Mutex.sleep | train | def sleep(timeout = nil)
unlock
begin
timeout ? Kernel.sleep(timeout) : Kernel.sleep
ensure
lock
end
end | ruby | {
"resource": ""
} |
q22861 | Mach.Port.insert_right | train | 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 | {
"resource": ""
} |
q22862 | Mach.Port.send_right | train | 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 | {
"resource": ""
} |
q22863 | Mach.Port.receive_right | train | 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 | {
"resource": ""
} |
q22864 | Mach.Semaphore.destroy | train | def destroy(opts = {})
task = opts[:task] || ipc_space || mach_task_self
semaphore_destroy(task.to_i, port)
end | ruby | {
"resource": ""
} |
q22865 | RubyCards.Card.suit | train | 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 | {
"resource": ""
} |
q22866 | CQL.TagFilter.has_tags? | train | 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 | {
"resource": ""
} |
q22867 | CQL.ContentMatchFilter.content_match? | train | def content_match?(content)
if pattern.is_a?(String)
content.any? { |thing| thing == pattern }
else
content.any? { |thing| thing =~ pattern }
end
end | ruby | {
"resource": ""
} |
q22868 | CQL.TypeCountFilter.execute | train | def execute(input, negate)
method = negate ? :reject : :select
input.send(method) do |object|
type_count(object).send(comparison.operator, comparison.amount)
end
end | ruby | {
"resource": ""
} |
q22869 | Bolognese.DoiUtils.get_doi_ra | train | 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 | {
"resource": ""
} |
q22870 | EmailHunter.Api.search | train | def search(domain, params = {})
EmailHunter::Search.new(domain, self.key, params).hunt
end | ruby | {
"resource": ""
} |
q22871 | EmailHunter.Api.finder | train | def finder(domain, first_name, last_name)
EmailHunter::Finder.new(domain, first_name, last_name, self.key).hunt
end | ruby | {
"resource": ""
} |
q22872 | Bolognese.MetadataUtils.raw | train | 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 | {
"resource": ""
} |
q22873 | Bolognese.AuthorUtils.get_authors | train | def get_authors(authors)
Array.wrap(authors).map { |author| get_one_author(author) }.compact
end | ruby | {
"resource": ""
} |
q22874 | DCell.Directory.find | train | def find(id)
return nil unless id
meta = DCell.registry.get_node(id)
DirectoryMeta.new(id, meta)
end | ruby | {
"resource": ""
} |
q22875 | RTKIT.ControlPoint.add_collimator | train | 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 | {
"resource": ""
} |
q22876 | RTKIT.ProjectionImage.load_pixel_data | train | 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 | {
"resource": ""
} |
q22877 | RTKIT.ProjectionImage.create_projection_image_dicom_scaffold | train | 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 | {
"resource": ""
} |
q22878 | RTKIT.DoseDistribution.d | train | 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 | {
"resource": ""
} |
q22879 | RTKIT.DoseDistribution.v | train | 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 | {
"resource": ""
} |
q22880 | Limelight.Stage.size= | train | 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 | {
"resource": ""
} |
q22881 | Limelight.Stage.location= | train | 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 | {
"resource": ""
} |
q22882 | Limelight.Stage.alert | train | 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 | {
"resource": ""
} |
q22883 | RTKIT.ImageSeries.add_image | train | 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 | {
"resource": ""
} |
q22884 | RTKIT.ImageSeries.add_struct | train | 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 | {
"resource": ""
} |
q22885 | RTKIT.ImageSeries.match_image | train | 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 | {
"resource": ""
} |
q22886 | RTKIT.ImageSeries.set_resolution | train | def set_resolution(columns, rows, options={})
@images.each do |img|
img.set_resolution(columns, rows, options)
end
end | ruby | {
"resource": ""
} |
q22887 | RTKIT.ImageSeries.struct | train | 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 | {
"resource": ""
} |
q22888 | RTKIT.PixelSpace.coordinate | train | 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 | {
"resource": ""
} |
q22889 | RTKIT.PixelSpace.cosines= | train | 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 | {
"resource": ""
} |
q22890 | RTKIT.SliceImage.binary_image | train | 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 | {
"resource": ""
} |
q22891 | RTKIT.SliceImage.to_dcm | train | 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 | {
"resource": ""
} |
q22892 | RTKIT.BinVolume.to_roi | train | 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 | {
"resource": ""
} |
q22893 | RTKIT.BinImage.narray= | train | 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 | {
"resource": ""
} |
q22894 | RTKIT.BinImage.to_contours | train | 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 | {
"resource": ""
} |
q22895 | RTKIT.BinImage.to_dcm | train | 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 | {
"resource": ""
} |
q22896 | RTKIT.BinImage.to_slice | train | 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 | {
"resource": ""
} |
q22897 | RTKIT.BinImage.external_contour | train | 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 | {
"resource": ""
} |
q22898 | RTKIT.BinImage.extract_contours | train | 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 | {
"resource": ""
} |
q22899 | RTKIT.BinImage.initialize_contour_reorder_structures | train | 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 | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.