repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
dicom/ruby-dicom | lib/dicom/image_item.rb | DICOM.ImageItem.encode_pixels | def encode_pixels(pixels, stream=@stream)
raise ArgumentError, "Expected Array, got #{pixels.class}." unless pixels.is_a?(Array)
bin = false
# We need to know what kind of bith depth and integer type the pixel data is saved with:
bit_depth_element = self['0028,0100']
pixel_representation_element = self['0028,0103']
if bit_depth_element and pixel_representation_element
template = template_string(bit_depth_element.value.to_i)
bin = stream.encode(pixels, template) if template
else
raise "The Element specifying Bit Depth (0028,0100) is missing. Unable to encode the pixel data." unless bit_depth_element
raise "The Element specifying Pixel Representation (0028,0103) is missing. Unable to encode the pixel data." unless pixel_representation_element
end
return bin
end | ruby | def encode_pixels(pixels, stream=@stream)
raise ArgumentError, "Expected Array, got #{pixels.class}." unless pixels.is_a?(Array)
bin = false
# We need to know what kind of bith depth and integer type the pixel data is saved with:
bit_depth_element = self['0028,0100']
pixel_representation_element = self['0028,0103']
if bit_depth_element and pixel_representation_element
template = template_string(bit_depth_element.value.to_i)
bin = stream.encode(pixels, template) if template
else
raise "The Element specifying Bit Depth (0028,0100) is missing. Unable to encode the pixel data." unless bit_depth_element
raise "The Element specifying Pixel Representation (0028,0103) is missing. Unable to encode the pixel data." unless pixel_representation_element
end
return bin
end | [
"def",
"encode_pixels",
"(",
"pixels",
",",
"stream",
"=",
"@stream",
")",
"raise",
"ArgumentError",
",",
"\"Expected Array, got #{pixels.class}.\"",
"unless",
"pixels",
".",
"is_a?",
"(",
"Array",
")",
"bin",
"=",
"false",
"bit_depth_element",
"=",
"self",
"[",
"'0028,0100'",
"]",
"pixel_representation_element",
"=",
"self",
"[",
"'0028,0103'",
"]",
"if",
"bit_depth_element",
"and",
"pixel_representation_element",
"template",
"=",
"template_string",
"(",
"bit_depth_element",
".",
"value",
".",
"to_i",
")",
"bin",
"=",
"stream",
".",
"encode",
"(",
"pixels",
",",
"template",
")",
"if",
"template",
"else",
"raise",
"\"The Element specifying Bit Depth (0028,0100) is missing. Unable to encode the pixel data.\"",
"unless",
"bit_depth_element",
"raise",
"\"The Element specifying Pixel Representation (0028,0103) is missing. Unable to encode the pixel data.\"",
"unless",
"pixel_representation_element",
"end",
"return",
"bin",
"end"
]
| Packs a pixel value array to a binary pixel string. The encoding is performed
using values defined in the image related elements of the DObject instance.
@param [Array<Integer>] pixels an array containing the pixel values to be encoded
@param [Stream] stream a Stream instance to be used for encoding the pixels (optional)
@return [String] encoded pixel string | [
"Packs",
"a",
"pixel",
"value",
"array",
"to",
"a",
"binary",
"pixel",
"string",
".",
"The",
"encoding",
"is",
"performed",
"using",
"values",
"defined",
"in",
"the",
"image",
"related",
"elements",
"of",
"the",
"DObject",
"instance",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/image_item.rb#L101-L115 | train |
dicom/ruby-dicom | lib/dicom/image_item.rb | DICOM.ImageItem.images | def images(options={})
images = Array.new
if exists?(PIXEL_TAG)
# Gather the pixel data strings, and pick a single frame if indicated by options:
strings = image_strings(split_to_frames=true)
strings = [strings[options[:frame]]] if options[:frame]
if compression?
# Decompress, either to numbers (RLE) or to an image object (image based compressions):
if [TXS_RLE].include?(transfer_syntax)
pixel_frames = Array.new
strings.each {|string| pixel_frames << decode_rle(num_cols, num_rows, string)}
else
images = decompress(strings) || Array.new
logger.warn("Decompressing pixel values has failed (unsupported transfer syntax: '#{transfer_syntax}' - #{LIBRARY.uid(transfer_syntax) ? LIBRARY.uid(transfer_syntax).name : 'Unknown transfer syntax!'})") unless images.length > 0
end
else
# Uncompressed: Decode to numbers.
pixel_frames = Array.new
strings.each {|string| pixel_frames << decode_pixels(string)}
end
if pixel_frames
images = Array.new
pixel_frames.each do |pixels|
# Pixel values and pixel order may need to be rearranged if we have color data:
pixels = process_colors(pixels) if color?
if pixels
images << read_image(pixels, num_cols, num_rows, options)
else
logger.warn("Processing pixel values for this particular color mode failed, unable to construct image(s).")
end
end
end
end
return images
end | ruby | def images(options={})
images = Array.new
if exists?(PIXEL_TAG)
# Gather the pixel data strings, and pick a single frame if indicated by options:
strings = image_strings(split_to_frames=true)
strings = [strings[options[:frame]]] if options[:frame]
if compression?
# Decompress, either to numbers (RLE) or to an image object (image based compressions):
if [TXS_RLE].include?(transfer_syntax)
pixel_frames = Array.new
strings.each {|string| pixel_frames << decode_rle(num_cols, num_rows, string)}
else
images = decompress(strings) || Array.new
logger.warn("Decompressing pixel values has failed (unsupported transfer syntax: '#{transfer_syntax}' - #{LIBRARY.uid(transfer_syntax) ? LIBRARY.uid(transfer_syntax).name : 'Unknown transfer syntax!'})") unless images.length > 0
end
else
# Uncompressed: Decode to numbers.
pixel_frames = Array.new
strings.each {|string| pixel_frames << decode_pixels(string)}
end
if pixel_frames
images = Array.new
pixel_frames.each do |pixels|
# Pixel values and pixel order may need to be rearranged if we have color data:
pixels = process_colors(pixels) if color?
if pixels
images << read_image(pixels, num_cols, num_rows, options)
else
logger.warn("Processing pixel values for this particular color mode failed, unable to construct image(s).")
end
end
end
end
return images
end | [
"def",
"images",
"(",
"options",
"=",
"{",
"}",
")",
"images",
"=",
"Array",
".",
"new",
"if",
"exists?",
"(",
"PIXEL_TAG",
")",
"strings",
"=",
"image_strings",
"(",
"split_to_frames",
"=",
"true",
")",
"strings",
"=",
"[",
"strings",
"[",
"options",
"[",
":frame",
"]",
"]",
"]",
"if",
"options",
"[",
":frame",
"]",
"if",
"compression?",
"if",
"[",
"TXS_RLE",
"]",
".",
"include?",
"(",
"transfer_syntax",
")",
"pixel_frames",
"=",
"Array",
".",
"new",
"strings",
".",
"each",
"{",
"|",
"string",
"|",
"pixel_frames",
"<<",
"decode_rle",
"(",
"num_cols",
",",
"num_rows",
",",
"string",
")",
"}",
"else",
"images",
"=",
"decompress",
"(",
"strings",
")",
"||",
"Array",
".",
"new",
"logger",
".",
"warn",
"(",
"\"Decompressing pixel values has failed (unsupported transfer syntax: '#{transfer_syntax}' - #{LIBRARY.uid(transfer_syntax) ? LIBRARY.uid(transfer_syntax).name : 'Unknown transfer syntax!'})\"",
")",
"unless",
"images",
".",
"length",
">",
"0",
"end",
"else",
"pixel_frames",
"=",
"Array",
".",
"new",
"strings",
".",
"each",
"{",
"|",
"string",
"|",
"pixel_frames",
"<<",
"decode_pixels",
"(",
"string",
")",
"}",
"end",
"if",
"pixel_frames",
"images",
"=",
"Array",
".",
"new",
"pixel_frames",
".",
"each",
"do",
"|",
"pixels",
"|",
"pixels",
"=",
"process_colors",
"(",
"pixels",
")",
"if",
"color?",
"if",
"pixels",
"images",
"<<",
"read_image",
"(",
"pixels",
",",
"num_cols",
",",
"num_rows",
",",
"options",
")",
"else",
"logger",
".",
"warn",
"(",
"\"Processing pixel values for this particular color mode failed, unable to construct image(s).\"",
")",
"end",
"end",
"end",
"end",
"return",
"images",
"end"
]
| Extracts an array of image objects, created from the encoded pixel data using
the image related elements in the DICOM object.
@note Creates an array of image objects in accordance with the selected image processor. Available processors are :rmagick and :mini_magick.
@param [Hash] options the options to use for extracting the images
@option options [Integer] :frame makes the method return an array containing only the image object corresponding to the specified frame number
@option options [TrueClass, Array<Integer>] :level if true, window leveling is performed using default values from the DICOM object, or if an array ([center, width]) is specified, these custom values are used instead
@option options [Boolean] :narray if true, forces the use of NArray for the pixel remap process (for faster execution)
@option options [Boolean] :remap if true, the returned pixel values are remapped to presentation values
@return [Array<MagickImage, NilClass>] an array of image objects, alternatively an empty array (if no image present or image decode failed)
@example Retrieve the pixel data as RMagick image objects
images = dcm.images
@example Retrieve the pixel data as RMagick image objects, remapped to presentation values (but without any leveling)
images = dcm.images(:remap => true)
@example Retrieve the pixel data as RMagick image objects, remapped to presentation values and leveled using the default center/width values in the DICOM object
images = dcm.images(:level => true)
@example Retrieve the pixel data as RMagick image objects, remapped to presentation values, leveled with the specified center/width values and using numerical array for the rescaling (~twice as fast)
images = dcm.images(:level => [-200,1000], :narray => true) | [
"Extracts",
"an",
"array",
"of",
"image",
"objects",
"created",
"from",
"the",
"encoded",
"pixel",
"data",
"using",
"the",
"image",
"related",
"elements",
"in",
"the",
"DICOM",
"object",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/image_item.rb#L164-L198 | train |
dicom/ruby-dicom | lib/dicom/image_item.rb | DICOM.ImageItem.image_to_file | def image_to_file(file)
raise ArgumentError, "Expected #{String}, got #{file.class}." unless file.is_a?(String)
# Split the file name in case of multiple fragments:
parts = file.split('.')
if parts.length > 1
base = parts[0..-2].join
extension = '.' + parts.last
else
base = file
extension = ''
end
# Get the binary image strings and dump them to the file(s):
images = image_strings
images.each_index do |i|
if images.length == 1
f = File.new(file, 'wb')
else
f = File.new("#{base}-#{i}#{extension}", 'wb')
end
f.write(images[i])
f.close
end
end | ruby | def image_to_file(file)
raise ArgumentError, "Expected #{String}, got #{file.class}." unless file.is_a?(String)
# Split the file name in case of multiple fragments:
parts = file.split('.')
if parts.length > 1
base = parts[0..-2].join
extension = '.' + parts.last
else
base = file
extension = ''
end
# Get the binary image strings and dump them to the file(s):
images = image_strings
images.each_index do |i|
if images.length == 1
f = File.new(file, 'wb')
else
f = File.new("#{base}-#{i}#{extension}", 'wb')
end
f.write(images[i])
f.close
end
end | [
"def",
"image_to_file",
"(",
"file",
")",
"raise",
"ArgumentError",
",",
"\"Expected #{String}, got #{file.class}.\"",
"unless",
"file",
".",
"is_a?",
"(",
"String",
")",
"parts",
"=",
"file",
".",
"split",
"(",
"'.'",
")",
"if",
"parts",
".",
"length",
">",
"1",
"base",
"=",
"parts",
"[",
"0",
"..",
"-",
"2",
"]",
".",
"join",
"extension",
"=",
"'.'",
"+",
"parts",
".",
"last",
"else",
"base",
"=",
"file",
"extension",
"=",
"''",
"end",
"images",
"=",
"image_strings",
"images",
".",
"each_index",
"do",
"|",
"i",
"|",
"if",
"images",
".",
"length",
"==",
"1",
"f",
"=",
"File",
".",
"new",
"(",
"file",
",",
"'wb'",
")",
"else",
"f",
"=",
"File",
".",
"new",
"(",
"\"#{base}-#{i}#{extension}\"",
",",
"'wb'",
")",
"end",
"f",
".",
"write",
"(",
"images",
"[",
"i",
"]",
")",
"f",
".",
"close",
"end",
"end"
]
| Dumps the binary content of the Pixel Data element to the specified file.
If the DICOM object contains multi-fragment pixel data, each fragment
will be dumped to separate files (e.q. 'fragment-0.dat', 'fragment-1.dat').
@param [String] file a string which specifies the file path to use when dumping the pixel data
@example Dumping the pixel data to a file
dcm.image_to_file("exported_image.dat") | [
"Dumps",
"the",
"binary",
"content",
"of",
"the",
"Pixel",
"Data",
"element",
"to",
"the",
"specified",
"file",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/image_item.rb#L251-L273 | train |
dicom/ruby-dicom | lib/dicom/image_item.rb | DICOM.ImageItem.pixels | def pixels(options={})
pixels = nil
if exists?(PIXEL_TAG)
# For now we only support returning pixel data of the first frame, if the image is located in multiple pixel data items:
if compression?
pixels = decompress(image_strings.first)
else
pixels = decode_pixels(image_strings.first)
end
if pixels
# Remap the image from pixel values to presentation values if the user has requested this:
if options[:remap] or options[:level]
if options[:narray]
# Use numerical array (faster):
pixels = process_presentation_values_narray(pixels, -65535, 65535, options[:level]).to_a
else
# Use standard Ruby array (slower):
pixels = process_presentation_values(pixels, -65535, 65535, options[:level])
end
end
else
logger.warn("Decompressing the Pixel Data failed. Pixel values can not be extracted.")
end
end
return pixels
end | ruby | def pixels(options={})
pixels = nil
if exists?(PIXEL_TAG)
# For now we only support returning pixel data of the first frame, if the image is located in multiple pixel data items:
if compression?
pixels = decompress(image_strings.first)
else
pixels = decode_pixels(image_strings.first)
end
if pixels
# Remap the image from pixel values to presentation values if the user has requested this:
if options[:remap] or options[:level]
if options[:narray]
# Use numerical array (faster):
pixels = process_presentation_values_narray(pixels, -65535, 65535, options[:level]).to_a
else
# Use standard Ruby array (slower):
pixels = process_presentation_values(pixels, -65535, 65535, options[:level])
end
end
else
logger.warn("Decompressing the Pixel Data failed. Pixel values can not be extracted.")
end
end
return pixels
end | [
"def",
"pixels",
"(",
"options",
"=",
"{",
"}",
")",
"pixels",
"=",
"nil",
"if",
"exists?",
"(",
"PIXEL_TAG",
")",
"if",
"compression?",
"pixels",
"=",
"decompress",
"(",
"image_strings",
".",
"first",
")",
"else",
"pixels",
"=",
"decode_pixels",
"(",
"image_strings",
".",
"first",
")",
"end",
"if",
"pixels",
"if",
"options",
"[",
":remap",
"]",
"or",
"options",
"[",
":level",
"]",
"if",
"options",
"[",
":narray",
"]",
"pixels",
"=",
"process_presentation_values_narray",
"(",
"pixels",
",",
"-",
"65535",
",",
"65535",
",",
"options",
"[",
":level",
"]",
")",
".",
"to_a",
"else",
"pixels",
"=",
"process_presentation_values",
"(",
"pixels",
",",
"-",
"65535",
",",
"65535",
",",
"options",
"[",
":level",
"]",
")",
"end",
"end",
"else",
"logger",
".",
"warn",
"(",
"\"Decompressing the Pixel Data failed. Pixel values can not be extracted.\"",
")",
"end",
"end",
"return",
"pixels",
"end"
]
| Extracts the Pixel Data values in an ordinary Ruby Array.
Returns nil if no pixel data is present, and false if it fails to retrieve pixel data which is present.
The returned array does not carry the dimensions of the pixel data:
It is put in a one dimensional Array (vector).
@param [Hash] options the options to use for extracting the pixel data
@option options [TrueClass, Array<Integer>] :level if true, window leveling is performed using default values from the DICOM object, or if an array ([center, width]) is specified, these custom values are used instead
@option options [Boolean] :narray if true, forces the use of NArray for the pixel remap process (for faster execution)
@option options [Boolean] :remap if true, the returned pixel values are remapped to presentation values
@return [Array, NilClass, FalseClass] an Array of pixel values, alternatively nil (if no image present) or false (if image decode failed)
@example Simply retrieve the pixel data
pixels = dcm.pixels
@example Retrieve the pixel data remapped to presentation values according to window center/width settings
pixels = dcm.pixels(:remap => true)
@example Retrieve the remapped pixel data while using numerical array (~twice as fast)
pixels = dcm.pixels(:remap => true, :narray => true) | [
"Extracts",
"the",
"Pixel",
"Data",
"values",
"in",
"an",
"ordinary",
"Ruby",
"Array",
".",
"Returns",
"nil",
"if",
"no",
"pixel",
"data",
"is",
"present",
"and",
"false",
"if",
"it",
"fails",
"to",
"retrieve",
"pixel",
"data",
"which",
"is",
"present",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/image_item.rb#L392-L417 | train |
dicom/ruby-dicom | lib/dicom/image_item.rb | DICOM.ImageItem.decode_rle | def decode_rle(cols, rows, string)
# FIXME: Remove cols and rows (were only added for debugging).
pixels = Array.new
# RLE header specifying the number of segments:
header = string[0...64].unpack('L*')
image_segments = Array.new
# Extracting all start and endpoints of the different segments:
header.each_index do |n|
if n == 0
# This one need no processing.
elsif n == header[0]
# It's the last one
image_segments << [header[n], -1]
break
else
image_segments << [header[n], header[n + 1] - 1]
end
end
# Iterate over each segment and extract pixel data:
image_segments.each do |range|
segment_data = Array.new
next_bytes = -1
next_multiplier = 0
# Iterate this segment's pixel string:
string[range[0]..range[1]].each_byte do |b|
if next_multiplier > 0
next_multiplier.times { segment_data << b }
next_multiplier = 0
elsif next_bytes > 0
segment_data << b
next_bytes -= 1
elsif b <= 127
next_bytes = b + 1
else
# Explaining the 257 at this point is a little bit complicate. Basically it has something
# to do with the algorithm described in the DICOM standard and that the value -1 as uint8 is 255.
# TODO: Is this architectur safe or does it only work on Intel systems???
next_multiplier = 257 - b
end
end
# Verify that the RLE decoding has executed properly:
throw "Size mismatch #{segment_data.size} != #{rows * cols}" if segment_data.size != rows * cols
pixels += segment_data
end
return pixels
end | ruby | def decode_rle(cols, rows, string)
# FIXME: Remove cols and rows (were only added for debugging).
pixels = Array.new
# RLE header specifying the number of segments:
header = string[0...64].unpack('L*')
image_segments = Array.new
# Extracting all start and endpoints of the different segments:
header.each_index do |n|
if n == 0
# This one need no processing.
elsif n == header[0]
# It's the last one
image_segments << [header[n], -1]
break
else
image_segments << [header[n], header[n + 1] - 1]
end
end
# Iterate over each segment and extract pixel data:
image_segments.each do |range|
segment_data = Array.new
next_bytes = -1
next_multiplier = 0
# Iterate this segment's pixel string:
string[range[0]..range[1]].each_byte do |b|
if next_multiplier > 0
next_multiplier.times { segment_data << b }
next_multiplier = 0
elsif next_bytes > 0
segment_data << b
next_bytes -= 1
elsif b <= 127
next_bytes = b + 1
else
# Explaining the 257 at this point is a little bit complicate. Basically it has something
# to do with the algorithm described in the DICOM standard and that the value -1 as uint8 is 255.
# TODO: Is this architectur safe or does it only work on Intel systems???
next_multiplier = 257 - b
end
end
# Verify that the RLE decoding has executed properly:
throw "Size mismatch #{segment_data.size} != #{rows * cols}" if segment_data.size != rows * cols
pixels += segment_data
end
return pixels
end | [
"def",
"decode_rle",
"(",
"cols",
",",
"rows",
",",
"string",
")",
"pixels",
"=",
"Array",
".",
"new",
"header",
"=",
"string",
"[",
"0",
"...",
"64",
"]",
".",
"unpack",
"(",
"'L*'",
")",
"image_segments",
"=",
"Array",
".",
"new",
"header",
".",
"each_index",
"do",
"|",
"n",
"|",
"if",
"n",
"==",
"0",
"elsif",
"n",
"==",
"header",
"[",
"0",
"]",
"image_segments",
"<<",
"[",
"header",
"[",
"n",
"]",
",",
"-",
"1",
"]",
"break",
"else",
"image_segments",
"<<",
"[",
"header",
"[",
"n",
"]",
",",
"header",
"[",
"n",
"+",
"1",
"]",
"-",
"1",
"]",
"end",
"end",
"image_segments",
".",
"each",
"do",
"|",
"range",
"|",
"segment_data",
"=",
"Array",
".",
"new",
"next_bytes",
"=",
"-",
"1",
"next_multiplier",
"=",
"0",
"string",
"[",
"range",
"[",
"0",
"]",
"..",
"range",
"[",
"1",
"]",
"]",
".",
"each_byte",
"do",
"|",
"b",
"|",
"if",
"next_multiplier",
">",
"0",
"next_multiplier",
".",
"times",
"{",
"segment_data",
"<<",
"b",
"}",
"next_multiplier",
"=",
"0",
"elsif",
"next_bytes",
">",
"0",
"segment_data",
"<<",
"b",
"next_bytes",
"-=",
"1",
"elsif",
"b",
"<=",
"127",
"next_bytes",
"=",
"b",
"+",
"1",
"else",
"next_multiplier",
"=",
"257",
"-",
"b",
"end",
"end",
"throw",
"\"Size mismatch #{segment_data.size} != #{rows * cols}\"",
"if",
"segment_data",
".",
"size",
"!=",
"rows",
"*",
"cols",
"pixels",
"+=",
"segment_data",
"end",
"return",
"pixels",
"end"
]
| Performs a run length decoding on the input stream.
@note For details on RLE encoding, refer to the DICOM standard, PS3.5, Section 8.2.2 as well as Annex G.
@param [Integer] cols number of colums of the encoded image
@param [Integer] rows number of rows of the encoded image
@param [Integer] string the encoded pixel string
@return [Array<Integer>] the decoded pixel values | [
"Performs",
"a",
"run",
"length",
"decoding",
"on",
"the",
"input",
"stream",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/image_item.rb#L491-L536 | train |
dicom/ruby-dicom | lib/dicom/image_item.rb | DICOM.ImageItem.process_presentation_values | def process_presentation_values(pixel_data, min_allowed, max_allowed, level=nil)
# Process pixel data for presentation according to the image information in the DICOM object:
center, width, intercept, slope = window_level_values
# Have image leveling been requested?
if level
# If custom values are specified in an array, use those. If not, the default values from the DICOM object are used:
if level.is_a?(Array)
center = level[0]
width = level[1]
end
else
center, width = false, false
end
# PixelOutput = slope * pixel_values + intercept
if intercept != 0 or slope != 1
pixel_data.collect!{|x| (slope * x) + intercept}
end
# Contrast enhancement by black and white thresholding:
if center and width
low = center - width/2
high = center + width/2
pixel_data.each_index do |i|
if pixel_data[i] < low
pixel_data[i] = low
elsif pixel_data[i] > high
pixel_data[i] = high
end
end
end
# Need to introduce an offset?
min_pixel_value = pixel_data.min
if min_allowed
if min_pixel_value < min_allowed
offset = min_pixel_value.abs
pixel_data.collect!{|x| x + offset}
end
end
# Downscale pixel range?
max_pixel_value = pixel_data.max
if max_allowed
if max_pixel_value > max_allowed
factor = (max_pixel_value.to_f/max_allowed.to_f).ceil
pixel_data.collect!{|x| x / factor}
end
end
return pixel_data
end | ruby | def process_presentation_values(pixel_data, min_allowed, max_allowed, level=nil)
# Process pixel data for presentation according to the image information in the DICOM object:
center, width, intercept, slope = window_level_values
# Have image leveling been requested?
if level
# If custom values are specified in an array, use those. If not, the default values from the DICOM object are used:
if level.is_a?(Array)
center = level[0]
width = level[1]
end
else
center, width = false, false
end
# PixelOutput = slope * pixel_values + intercept
if intercept != 0 or slope != 1
pixel_data.collect!{|x| (slope * x) + intercept}
end
# Contrast enhancement by black and white thresholding:
if center and width
low = center - width/2
high = center + width/2
pixel_data.each_index do |i|
if pixel_data[i] < low
pixel_data[i] = low
elsif pixel_data[i] > high
pixel_data[i] = high
end
end
end
# Need to introduce an offset?
min_pixel_value = pixel_data.min
if min_allowed
if min_pixel_value < min_allowed
offset = min_pixel_value.abs
pixel_data.collect!{|x| x + offset}
end
end
# Downscale pixel range?
max_pixel_value = pixel_data.max
if max_allowed
if max_pixel_value > max_allowed
factor = (max_pixel_value.to_f/max_allowed.to_f).ceil
pixel_data.collect!{|x| x / factor}
end
end
return pixel_data
end | [
"def",
"process_presentation_values",
"(",
"pixel_data",
",",
"min_allowed",
",",
"max_allowed",
",",
"level",
"=",
"nil",
")",
"center",
",",
"width",
",",
"intercept",
",",
"slope",
"=",
"window_level_values",
"if",
"level",
"if",
"level",
".",
"is_a?",
"(",
"Array",
")",
"center",
"=",
"level",
"[",
"0",
"]",
"width",
"=",
"level",
"[",
"1",
"]",
"end",
"else",
"center",
",",
"width",
"=",
"false",
",",
"false",
"end",
"if",
"intercept",
"!=",
"0",
"or",
"slope",
"!=",
"1",
"pixel_data",
".",
"collect!",
"{",
"|",
"x",
"|",
"(",
"slope",
"*",
"x",
")",
"+",
"intercept",
"}",
"end",
"if",
"center",
"and",
"width",
"low",
"=",
"center",
"-",
"width",
"/",
"2",
"high",
"=",
"center",
"+",
"width",
"/",
"2",
"pixel_data",
".",
"each_index",
"do",
"|",
"i",
"|",
"if",
"pixel_data",
"[",
"i",
"]",
"<",
"low",
"pixel_data",
"[",
"i",
"]",
"=",
"low",
"elsif",
"pixel_data",
"[",
"i",
"]",
">",
"high",
"pixel_data",
"[",
"i",
"]",
"=",
"high",
"end",
"end",
"end",
"min_pixel_value",
"=",
"pixel_data",
".",
"min",
"if",
"min_allowed",
"if",
"min_pixel_value",
"<",
"min_allowed",
"offset",
"=",
"min_pixel_value",
".",
"abs",
"pixel_data",
".",
"collect!",
"{",
"|",
"x",
"|",
"x",
"+",
"offset",
"}",
"end",
"end",
"max_pixel_value",
"=",
"pixel_data",
".",
"max",
"if",
"max_allowed",
"if",
"max_pixel_value",
">",
"max_allowed",
"factor",
"=",
"(",
"max_pixel_value",
".",
"to_f",
"/",
"max_allowed",
".",
"to_f",
")",
".",
"ceil",
"pixel_data",
".",
"collect!",
"{",
"|",
"x",
"|",
"x",
"/",
"factor",
"}",
"end",
"end",
"return",
"pixel_data",
"end"
]
| Converts original pixel data values to presentation values.
@param [Array<Integer>] pixel_data an array of pixel values (integers)
@param [Integer] min_allowed the minimum value allowed in the pixel data
@param [Integer] max_allowed the maximum value allowed in the pixel data
@param [Boolean, Array<Integer>] level if true, window leveling is performed using default values from the DICOM object, or if an array ([center, width]) is specified, these custom values are used instead
@return [Array<Integer>] presentation values | [
"Converts",
"original",
"pixel",
"data",
"values",
"to",
"presentation",
"values",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/image_item.rb#L609-L655 | train |
dicom/ruby-dicom | lib/dicom/image_item.rb | DICOM.ImageItem.process_presentation_values_narray | def process_presentation_values_narray(pixel_data, min_allowed, max_allowed, level=nil)
# Process pixel data for presentation according to the image information in the DICOM object:
center, width, intercept, slope = window_level_values
# Have image leveling been requested?
if level
# If custom values are specified in an array, use those. If not, the default values from the DICOM object are used:
if level.is_a?(Array)
center = level[0]
width = level[1]
end
else
center, width = false, false
end
# Need to convert to NArray?
if pixel_data.is_a?(Array)
n_arr = Numo::NArray[*pixel_data]
else
n_arr = pixel_data
end
# Remap:
# PixelOutput = slope * pixel_values + intercept
if intercept != 0 or slope != 1
n_arr = slope * n_arr + intercept
end
# Contrast enhancement by black and white thresholding:
if center and width
low = center - width/2
high = center + width/2
n_arr[n_arr < low] = low
n_arr[n_arr > high] = high
end
# Need to introduce an offset?
min_pixel_value = n_arr.min
if min_allowed
if min_pixel_value < min_allowed
offset = min_pixel_value.abs
n_arr = n_arr + offset
end
end
# Downscale pixel range?
max_pixel_value = n_arr.max
if max_allowed
if max_pixel_value > max_allowed
factor = (max_pixel_value.to_f/max_allowed.to_f).ceil
n_arr = n_arr / factor
end
end
return n_arr
end | ruby | def process_presentation_values_narray(pixel_data, min_allowed, max_allowed, level=nil)
# Process pixel data for presentation according to the image information in the DICOM object:
center, width, intercept, slope = window_level_values
# Have image leveling been requested?
if level
# If custom values are specified in an array, use those. If not, the default values from the DICOM object are used:
if level.is_a?(Array)
center = level[0]
width = level[1]
end
else
center, width = false, false
end
# Need to convert to NArray?
if pixel_data.is_a?(Array)
n_arr = Numo::NArray[*pixel_data]
else
n_arr = pixel_data
end
# Remap:
# PixelOutput = slope * pixel_values + intercept
if intercept != 0 or slope != 1
n_arr = slope * n_arr + intercept
end
# Contrast enhancement by black and white thresholding:
if center and width
low = center - width/2
high = center + width/2
n_arr[n_arr < low] = low
n_arr[n_arr > high] = high
end
# Need to introduce an offset?
min_pixel_value = n_arr.min
if min_allowed
if min_pixel_value < min_allowed
offset = min_pixel_value.abs
n_arr = n_arr + offset
end
end
# Downscale pixel range?
max_pixel_value = n_arr.max
if max_allowed
if max_pixel_value > max_allowed
factor = (max_pixel_value.to_f/max_allowed.to_f).ceil
n_arr = n_arr / factor
end
end
return n_arr
end | [
"def",
"process_presentation_values_narray",
"(",
"pixel_data",
",",
"min_allowed",
",",
"max_allowed",
",",
"level",
"=",
"nil",
")",
"center",
",",
"width",
",",
"intercept",
",",
"slope",
"=",
"window_level_values",
"if",
"level",
"if",
"level",
".",
"is_a?",
"(",
"Array",
")",
"center",
"=",
"level",
"[",
"0",
"]",
"width",
"=",
"level",
"[",
"1",
"]",
"end",
"else",
"center",
",",
"width",
"=",
"false",
",",
"false",
"end",
"if",
"pixel_data",
".",
"is_a?",
"(",
"Array",
")",
"n_arr",
"=",
"Numo",
"::",
"NArray",
"[",
"*",
"pixel_data",
"]",
"else",
"n_arr",
"=",
"pixel_data",
"end",
"if",
"intercept",
"!=",
"0",
"or",
"slope",
"!=",
"1",
"n_arr",
"=",
"slope",
"*",
"n_arr",
"+",
"intercept",
"end",
"if",
"center",
"and",
"width",
"low",
"=",
"center",
"-",
"width",
"/",
"2",
"high",
"=",
"center",
"+",
"width",
"/",
"2",
"n_arr",
"[",
"n_arr",
"<",
"low",
"]",
"=",
"low",
"n_arr",
"[",
"n_arr",
">",
"high",
"]",
"=",
"high",
"end",
"min_pixel_value",
"=",
"n_arr",
".",
"min",
"if",
"min_allowed",
"if",
"min_pixel_value",
"<",
"min_allowed",
"offset",
"=",
"min_pixel_value",
".",
"abs",
"n_arr",
"=",
"n_arr",
"+",
"offset",
"end",
"end",
"max_pixel_value",
"=",
"n_arr",
".",
"max",
"if",
"max_allowed",
"if",
"max_pixel_value",
">",
"max_allowed",
"factor",
"=",
"(",
"max_pixel_value",
".",
"to_f",
"/",
"max_allowed",
".",
"to_f",
")",
".",
"ceil",
"n_arr",
"=",
"n_arr",
"/",
"factor",
"end",
"end",
"return",
"n_arr",
"end"
]
| Converts original pixel data values to presentation values, using the efficient NArray library.
@note If a Ruby Array is supplied, the method returns a one-dimensional NArray object (i.e. no columns & rows).
@note If a NArray is supplied, the NArray is returned with its original dimensions.
@param [Array<Integer>, NArray] pixel_data pixel values
@param [Integer] min_allowed the minimum value allowed in the pixel data
@param [Integer] max_allowed the maximum value allowed in the pixel data
@param [Boolean, Array<Integer>] level if true, window leveling is performed using default values from the DICOM object, or if an array ([center, width]) is specified, these custom values are used instead
@return [Array<Integer>, NArray] presentation values | [
"Converts",
"original",
"pixel",
"data",
"values",
"to",
"presentation",
"values",
"using",
"the",
"efficient",
"NArray",
"library",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/image_item.rb#L668-L716 | train |
dicom/ruby-dicom | lib/dicom/image_item.rb | DICOM.ImageItem.read_image | def read_image(pixel_data, columns, rows, options={})
raise ArgumentError, "Expected Array for pixel_data, got #{pixel_data.class}" unless pixel_data.is_a?(Array)
raise ArgumentError, "Expected Integer for columns, got #{columns.class}" unless columns.is_a?(Integer)
raise ArgumentError, "Expected Rows for columns, got #{rows.class}" unless rows.is_a?(Integer)
raise ArgumentError, "Size of pixel_data must be at least equal to columns*rows. Got #{columns}*#{rows}=#{columns*rows}, which is less than the array size #{pixel_data.length}" if columns * rows > pixel_data.length
# Remap the image from pixel values to presentation values if the user has requested this:
if options[:remap] or options[:level]
# How to perform the remapping? NArray (fast) or Ruby Array (slow)?
if options[:narray] == true
pixel_data = process_presentation_values_narray(pixel_data, 0, 65535, options[:level]).to_a
else
pixel_data = process_presentation_values(pixel_data, 0, 65535, options[:level])
end
else
# No remapping, but make sure that we pass on unsigned pixel values to the image processor:
pixel_data = pixel_data.to_unsigned(bit_depth) if signed_pixels?
end
image = import_pixels(pixel_data.to_blob(actual_bit_depth), columns, rows, actual_bit_depth, photometry)
return image
end | ruby | def read_image(pixel_data, columns, rows, options={})
raise ArgumentError, "Expected Array for pixel_data, got #{pixel_data.class}" unless pixel_data.is_a?(Array)
raise ArgumentError, "Expected Integer for columns, got #{columns.class}" unless columns.is_a?(Integer)
raise ArgumentError, "Expected Rows for columns, got #{rows.class}" unless rows.is_a?(Integer)
raise ArgumentError, "Size of pixel_data must be at least equal to columns*rows. Got #{columns}*#{rows}=#{columns*rows}, which is less than the array size #{pixel_data.length}" if columns * rows > pixel_data.length
# Remap the image from pixel values to presentation values if the user has requested this:
if options[:remap] or options[:level]
# How to perform the remapping? NArray (fast) or Ruby Array (slow)?
if options[:narray] == true
pixel_data = process_presentation_values_narray(pixel_data, 0, 65535, options[:level]).to_a
else
pixel_data = process_presentation_values(pixel_data, 0, 65535, options[:level])
end
else
# No remapping, but make sure that we pass on unsigned pixel values to the image processor:
pixel_data = pixel_data.to_unsigned(bit_depth) if signed_pixels?
end
image = import_pixels(pixel_data.to_blob(actual_bit_depth), columns, rows, actual_bit_depth, photometry)
return image
end | [
"def",
"read_image",
"(",
"pixel_data",
",",
"columns",
",",
"rows",
",",
"options",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"\"Expected Array for pixel_data, got #{pixel_data.class}\"",
"unless",
"pixel_data",
".",
"is_a?",
"(",
"Array",
")",
"raise",
"ArgumentError",
",",
"\"Expected Integer for columns, got #{columns.class}\"",
"unless",
"columns",
".",
"is_a?",
"(",
"Integer",
")",
"raise",
"ArgumentError",
",",
"\"Expected Rows for columns, got #{rows.class}\"",
"unless",
"rows",
".",
"is_a?",
"(",
"Integer",
")",
"raise",
"ArgumentError",
",",
"\"Size of pixel_data must be at least equal to columns*rows. Got #{columns}*#{rows}=#{columns*rows}, which is less than the array size #{pixel_data.length}\"",
"if",
"columns",
"*",
"rows",
">",
"pixel_data",
".",
"length",
"if",
"options",
"[",
":remap",
"]",
"or",
"options",
"[",
":level",
"]",
"if",
"options",
"[",
":narray",
"]",
"==",
"true",
"pixel_data",
"=",
"process_presentation_values_narray",
"(",
"pixel_data",
",",
"0",
",",
"65535",
",",
"options",
"[",
":level",
"]",
")",
".",
"to_a",
"else",
"pixel_data",
"=",
"process_presentation_values",
"(",
"pixel_data",
",",
"0",
",",
"65535",
",",
"options",
"[",
":level",
"]",
")",
"end",
"else",
"pixel_data",
"=",
"pixel_data",
".",
"to_unsigned",
"(",
"bit_depth",
")",
"if",
"signed_pixels?",
"end",
"image",
"=",
"import_pixels",
"(",
"pixel_data",
".",
"to_blob",
"(",
"actual_bit_depth",
")",
",",
"columns",
",",
"rows",
",",
"actual_bit_depth",
",",
"photometry",
")",
"return",
"image",
"end"
]
| Creates an image object from the specified pixel value array, performing
presentation value processing if requested.
@note Definitions for Window Center and Width can be found in the DICOM standard, PS 3.3 C.11.2.1.2
@param [Array<Integer>] pixel_data an array of pixel values
@param [Integer] columns the number of columns in the pixel data
@param [Integer] rows the number of rows in the pixel data
@param [Hash] options the options to use for reading the image
@option options [Boolean] :remap if true, pixel values are remapped to presentation values (using intercept and slope values from the DICOM object)
@option options [Boolean, Array<Integer>] :level if true, window leveling is performed using default values from the DICOM object, or if an array ([center, width]) is specified, these custom values are used instead
@option options [Boolean] :narray if true, forces the use of NArray for the pixel remap process (for faster execution)
@return [MagickImage] the extracted image object | [
"Creates",
"an",
"image",
"object",
"from",
"the",
"specified",
"pixel",
"value",
"array",
"performing",
"presentation",
"value",
"processing",
"if",
"requested",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/image_item.rb#L732-L751 | train |
dicom/ruby-dicom | lib/dicom/image_item.rb | DICOM.ImageItem.window_level_values | def window_level_values
center = (self['0028,1050'].is_a?(Element) == true ? self['0028,1050'].value.to_i : nil)
width = (self['0028,1051'].is_a?(Element) == true ? self['0028,1051'].value.to_i : nil)
intercept = (self['0028,1052'].is_a?(Element) == true ? self['0028,1052'].value.to_i : 0)
slope = (self['0028,1053'].is_a?(Element) == true ? self['0028,1053'].value.to_i : 1)
return center, width, intercept, slope
end | ruby | def window_level_values
center = (self['0028,1050'].is_a?(Element) == true ? self['0028,1050'].value.to_i : nil)
width = (self['0028,1051'].is_a?(Element) == true ? self['0028,1051'].value.to_i : nil)
intercept = (self['0028,1052'].is_a?(Element) == true ? self['0028,1052'].value.to_i : 0)
slope = (self['0028,1053'].is_a?(Element) == true ? self['0028,1053'].value.to_i : 1)
return center, width, intercept, slope
end | [
"def",
"window_level_values",
"center",
"=",
"(",
"self",
"[",
"'0028,1050'",
"]",
".",
"is_a?",
"(",
"Element",
")",
"==",
"true",
"?",
"self",
"[",
"'0028,1050'",
"]",
".",
"value",
".",
"to_i",
":",
"nil",
")",
"width",
"=",
"(",
"self",
"[",
"'0028,1051'",
"]",
".",
"is_a?",
"(",
"Element",
")",
"==",
"true",
"?",
"self",
"[",
"'0028,1051'",
"]",
".",
"value",
".",
"to_i",
":",
"nil",
")",
"intercept",
"=",
"(",
"self",
"[",
"'0028,1052'",
"]",
".",
"is_a?",
"(",
"Element",
")",
"==",
"true",
"?",
"self",
"[",
"'0028,1052'",
"]",
".",
"value",
".",
"to_i",
":",
"0",
")",
"slope",
"=",
"(",
"self",
"[",
"'0028,1053'",
"]",
".",
"is_a?",
"(",
"Element",
")",
"==",
"true",
"?",
"self",
"[",
"'0028,1053'",
"]",
".",
"value",
".",
"to_i",
":",
"1",
")",
"return",
"center",
",",
"width",
",",
"intercept",
",",
"slope",
"end"
]
| Collects the window level values needed to convert the original pixel
values to presentation values.
@note If some of these values are missing in the DObject instance,
default values are used instead for intercept and slope, while center
and width are set to nil. No errors are raised.
@return [Array<Integer, NilClass>] center, width, intercept and slope | [
"Collects",
"the",
"window",
"level",
"values",
"needed",
"to",
"convert",
"the",
"original",
"pixel",
"values",
"to",
"presentation",
"values",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/image_item.rb#L813-L819 | train |
dicom/ruby-dicom | lib/dicom/image_item.rb | DICOM.ImageItem.write_pixels | def write_pixels(bin)
if self.exists?(PIXEL_TAG)
# Update existing Data Element:
self[PIXEL_TAG].bin = bin
else
# Create new Data Element:
pixel_element = Element.new(PIXEL_TAG, bin, :encoded => true, :parent => self)
end
end | ruby | def write_pixels(bin)
if self.exists?(PIXEL_TAG)
# Update existing Data Element:
self[PIXEL_TAG].bin = bin
else
# Create new Data Element:
pixel_element = Element.new(PIXEL_TAG, bin, :encoded => true, :parent => self)
end
end | [
"def",
"write_pixels",
"(",
"bin",
")",
"if",
"self",
".",
"exists?",
"(",
"PIXEL_TAG",
")",
"self",
"[",
"PIXEL_TAG",
"]",
".",
"bin",
"=",
"bin",
"else",
"pixel_element",
"=",
"Element",
".",
"new",
"(",
"PIXEL_TAG",
",",
"bin",
",",
":encoded",
"=>",
"true",
",",
":parent",
"=>",
"self",
")",
"end",
"end"
]
| Transfers a pre-encoded binary string to the pixel data element, either by
overwriting the existing element value, or creating a new "Pixel Data" element.
@param [String] bin a binary string containing encoded pixel data | [
"Transfers",
"a",
"pre",
"-",
"encoded",
"binary",
"string",
"to",
"the",
"pixel",
"data",
"element",
"either",
"by",
"overwriting",
"the",
"existing",
"element",
"value",
"or",
"creating",
"a",
"new",
"Pixel",
"Data",
"element",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/image_item.rb#L826-L834 | train |
dicom/ruby-dicom | lib/dicom/d_read.rb | DICOM.Parent.parse | def parse(bin, syntax, switched=false, explicit=true)
raise ArgumentError, "Invalid argument 'bin'. Expected String, got #{bin.class}." unless bin.is_a?(String)
raise ArgumentError, "Invalid argument 'syntax'. Expected String, got #{syntax.class}." unless syntax.is_a?(String)
read(bin, signature=false, :syntax => syntax, :switched => switched, :explicit => explicit)
end | ruby | def parse(bin, syntax, switched=false, explicit=true)
raise ArgumentError, "Invalid argument 'bin'. Expected String, got #{bin.class}." unless bin.is_a?(String)
raise ArgumentError, "Invalid argument 'syntax'. Expected String, got #{syntax.class}." unless syntax.is_a?(String)
read(bin, signature=false, :syntax => syntax, :switched => switched, :explicit => explicit)
end | [
"def",
"parse",
"(",
"bin",
",",
"syntax",
",",
"switched",
"=",
"false",
",",
"explicit",
"=",
"true",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'bin'. Expected String, got #{bin.class}.\"",
"unless",
"bin",
".",
"is_a?",
"(",
"String",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'syntax'. Expected String, got #{syntax.class}.\"",
"unless",
"syntax",
".",
"is_a?",
"(",
"String",
")",
"read",
"(",
"bin",
",",
"signature",
"=",
"false",
",",
":syntax",
"=>",
"syntax",
",",
":switched",
"=>",
"switched",
",",
":explicit",
"=>",
"explicit",
")",
"end"
]
| Loads data from an encoded DICOM string and creates
items and elements which are linked to this instance.
@param [String] bin an encoded binary string containing DICOM information
@param [String] syntax the transfer syntax to use when decoding the DICOM string
@param [Boolean] switched indicating whether the transfer syntax 'switch' has occured in the data stream of this object | [
"Loads",
"data",
"from",
"an",
"encoded",
"DICOM",
"string",
"and",
"creates",
"items",
"and",
"elements",
"which",
"are",
"linked",
"to",
"this",
"instance",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/d_read.rb#L12-L16 | train |
dicom/ruby-dicom | lib/dicom/d_read.rb | DICOM.Parent.check_duplicate | def check_duplicate(tag, elemental)
if @current_parent[tag]
gp = @current_parent.parent ? "#{@current_parent.parent.representation} => " : ''
p = @current_parent.representation
logger.warn("Duplicate #{elemental} (#{tag}) detected at level: #{gp}#{p}")
end
end | ruby | def check_duplicate(tag, elemental)
if @current_parent[tag]
gp = @current_parent.parent ? "#{@current_parent.parent.representation} => " : ''
p = @current_parent.representation
logger.warn("Duplicate #{elemental} (#{tag}) detected at level: #{gp}#{p}")
end
end | [
"def",
"check_duplicate",
"(",
"tag",
",",
"elemental",
")",
"if",
"@current_parent",
"[",
"tag",
"]",
"gp",
"=",
"@current_parent",
".",
"parent",
"?",
"\"#{@current_parent.parent.representation} => \"",
":",
"''",
"p",
"=",
"@current_parent",
".",
"representation",
"logger",
".",
"warn",
"(",
"\"Duplicate #{elemental} (#{tag}) detected at level: #{gp}#{p}\"",
")",
"end",
"end"
]
| Checks whether the given tag is a duplicate of an existing tag with this parent.
@param [String] tag the tag of the candidate duplicate elemental
@param [String] elemental the duplicate elemental type (e.g. Sequence, Element) | [
"Checks",
"whether",
"the",
"given",
"tag",
"is",
"a",
"duplicate",
"of",
"an",
"existing",
"tag",
"with",
"this",
"parent",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/d_read.rb#L27-L33 | train |
dicom/ruby-dicom | lib/dicom/d_read.rb | DICOM.Parent.check_header | def check_header
# According to the official DICOM standard, a DICOM file shall contain 128 consequtive (zero) bytes,
# followed by 4 bytes that spell the string 'DICM'. Apparently, some providers seems to skip this in their DICOM files.
# Check that the string is long enough to contain a valid header:
if @str.length < 132
# This does not seem to be a valid DICOM string and so we return.
return nil
else
@stream.skip(128)
# Next 4 bytes should spell "DICM":
identifier = @stream.decode(4, "STR")
@header_length += 132
if identifier != "DICM" then
# Header signature is not valid (we will still try to parse it is a DICOM string though):
logger.warn("This string does not contain the expected DICOM header. Will try to parse the string anyway (assuming a missing header).")
# As the string is not conforming to the DICOM standard, it is possible that it does not contain a
# transfer syntax element, and as such, we attempt to choose the most probable encoding values here:
@explicit = false
return false
else
# Header signature is valid:
@signature = true
return true
end
end
end | ruby | def check_header
# According to the official DICOM standard, a DICOM file shall contain 128 consequtive (zero) bytes,
# followed by 4 bytes that spell the string 'DICM'. Apparently, some providers seems to skip this in their DICOM files.
# Check that the string is long enough to contain a valid header:
if @str.length < 132
# This does not seem to be a valid DICOM string and so we return.
return nil
else
@stream.skip(128)
# Next 4 bytes should spell "DICM":
identifier = @stream.decode(4, "STR")
@header_length += 132
if identifier != "DICM" then
# Header signature is not valid (we will still try to parse it is a DICOM string though):
logger.warn("This string does not contain the expected DICOM header. Will try to parse the string anyway (assuming a missing header).")
# As the string is not conforming to the DICOM standard, it is possible that it does not contain a
# transfer syntax element, and as such, we attempt to choose the most probable encoding values here:
@explicit = false
return false
else
# Header signature is valid:
@signature = true
return true
end
end
end | [
"def",
"check_header",
"if",
"@str",
".",
"length",
"<",
"132",
"return",
"nil",
"else",
"@stream",
".",
"skip",
"(",
"128",
")",
"identifier",
"=",
"@stream",
".",
"decode",
"(",
"4",
",",
"\"STR\"",
")",
"@header_length",
"+=",
"132",
"if",
"identifier",
"!=",
"\"DICM\"",
"then",
"logger",
".",
"warn",
"(",
"\"This string does not contain the expected DICOM header. Will try to parse the string anyway (assuming a missing header).\"",
")",
"@explicit",
"=",
"false",
"return",
"false",
"else",
"@signature",
"=",
"true",
"return",
"true",
"end",
"end",
"end"
]
| Checks for the official DICOM header signature.
@return [Boolean] true if the proper signature is present, false if not, and nil if the string was shorter then the length of the DICOM signature | [
"Checks",
"for",
"the",
"official",
"DICOM",
"header",
"signature",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/d_read.rb#L39-L64 | train |
dicom/ruby-dicom | lib/dicom/d_read.rb | DICOM.Parent.process_data_element | def process_data_element
# FIXME: This method has grown a bit messy and isn't very pleasant to read. Cleanup possible?
# After having been into a possible unknown sequence with undefined length, we may need to reset
# explicitness from implicit to explicit:
if !@original_explicit.nil? && @explicitness_reset_parent == @current_parent
@explicit = @original_explicit
end
# STEP 1:
# Attempt to read data element tag:
tag = read_tag
# Return nil if we have (naturally) reached the end of the data string.
return nil unless tag
# STEP 2:
# Access library to retrieve the data element name and VR from the tag we just read:
# (Note: VR will be overwritten in the next step if the DICOM string contains VR (explicit encoding))
name, vr = LIBRARY.name_and_vr(tag)
# STEP 3:
# Read VR (if it exists) and the length value:
vr, length = read_vr_length(vr,tag)
level_vr = vr
# STEP 4:
# Reading value of data element.
# Special handling needed for items in encapsulated image data:
if @enc_image and tag == ITEM_TAG
# The first item appearing after the image element is a 'normal' item, the rest hold image data.
# Note that the first item will contain data if there are multiple images, and so must be read.
vr = "OW" # how about alternatives like OB?
# Modify name of item if this is an item that holds pixel data:
if @current_element.tag != PIXEL_TAG
name = PIXEL_ITEM_NAME
end
end
# Read the binary string of the element:
bin = read_bin(length) if length > 0
# Read the value of the element (if it contains data, and it is not a sequence or ordinary item):
if length > 0 and vr != "SQ" and tag != ITEM_TAG
# Read the element's processed value:
value = read_value(vr, length)
else
# Data element has no value (data).
value = nil
# Special case: Check if pixel data element is sequenced:
if tag == PIXEL_TAG
# Change name and vr of pixel data element if it does not contain data itself:
name = ENCAPSULATED_PIXEL_NAME
level_vr = "SQ"
@enc_image = true
end
end
# Create an Element from the gathered data:
# if vr is UN ("unknown") and length is -1, treat as a sequence (sec. 6.2.2 of DICOM standard)
if level_vr == "SQ" or tag == ITEM_TAG or (level_vr == "UN" and length == -1)
if level_vr == "SQ" or (level_vr == "UN" and length == -1)
check_duplicate(tag, 'Sequence')
# If we get an unknown sequence with undefined length, we must switch to implicit for decoding its content:
if level_vr == "UN" and length == -1
@original_explicit = @explicit
@explicit = false
@explicitness_reset_parent = @current_parent
end
unless @current_parent[tag] and !@overwrite
@current_element = Sequence.new(tag, :length => length, :name => name, :parent => @current_parent, :vr => vr)
else
# We have skipped a sequence. This means that any following children
# of this sequence must be skipped as well. We solve this by creating an 'orphaned'
# sequence that has a parent defined, but does not add itself to this parent:
@current_element = Sequence.new(tag, :length => length, :name => name, :vr => vr)
@current_element.set_parent(@current_parent)
end
elsif tag == ITEM_TAG
# Create an Item:
if @enc_image
@current_element = Item.new(:bin => bin, :length => length, :name => name, :parent => @current_parent, :vr => vr)
else
@current_element = Item.new(:length => length, :name => name, :parent => @current_parent, :vr => vr)
end
end
# Common operations on the two types of parent elements:
if length == 0 and @enc_image
# Set as parent. Exceptions when parent will not be set:
# Item/Sequence has zero length & Item is a pixel item (which contains pixels, not child elements).
@current_parent = @current_element
elsif length != 0
@current_parent = @current_element unless name == PIXEL_ITEM_NAME
end
# If length is specified (no delimitation items), load a new DRead instance to read these child elements
# and load them into the current sequence. The exception is when we have a pixel data item.
if length > 0 and not @enc_image
@current_element.parse(bin, @transfer_syntax, switched=@switched, @explicit)
@current_parent = @current_parent.parent
return false unless @read_success
end
elsif DELIMITER_TAGS.include?(tag)
# We do not create an element for the delimiter items.
# The occurance of such a tag indicates that a sequence or item has ended, and the parent must be changed:
@current_parent = @current_parent.parent
else
check_duplicate(tag, 'Element')
unless @current_parent[tag] and !@overwrite
@current_element = Element.new(tag, value, :bin => bin, :name => name, :parent => @current_parent, :vr => vr)
# Check that the data stream didn't end abruptly:
raise "The actual length of the value (#{@current_element.bin.length}) does not match its specified length (#{length}) for Data Element #{@current_element.tag}" if length != @current_element.bin.length
end
end
# Return true to indicate success:
return true
end | ruby | def process_data_element
# FIXME: This method has grown a bit messy and isn't very pleasant to read. Cleanup possible?
# After having been into a possible unknown sequence with undefined length, we may need to reset
# explicitness from implicit to explicit:
if !@original_explicit.nil? && @explicitness_reset_parent == @current_parent
@explicit = @original_explicit
end
# STEP 1:
# Attempt to read data element tag:
tag = read_tag
# Return nil if we have (naturally) reached the end of the data string.
return nil unless tag
# STEP 2:
# Access library to retrieve the data element name and VR from the tag we just read:
# (Note: VR will be overwritten in the next step if the DICOM string contains VR (explicit encoding))
name, vr = LIBRARY.name_and_vr(tag)
# STEP 3:
# Read VR (if it exists) and the length value:
vr, length = read_vr_length(vr,tag)
level_vr = vr
# STEP 4:
# Reading value of data element.
# Special handling needed for items in encapsulated image data:
if @enc_image and tag == ITEM_TAG
# The first item appearing after the image element is a 'normal' item, the rest hold image data.
# Note that the first item will contain data if there are multiple images, and so must be read.
vr = "OW" # how about alternatives like OB?
# Modify name of item if this is an item that holds pixel data:
if @current_element.tag != PIXEL_TAG
name = PIXEL_ITEM_NAME
end
end
# Read the binary string of the element:
bin = read_bin(length) if length > 0
# Read the value of the element (if it contains data, and it is not a sequence or ordinary item):
if length > 0 and vr != "SQ" and tag != ITEM_TAG
# Read the element's processed value:
value = read_value(vr, length)
else
# Data element has no value (data).
value = nil
# Special case: Check if pixel data element is sequenced:
if tag == PIXEL_TAG
# Change name and vr of pixel data element if it does not contain data itself:
name = ENCAPSULATED_PIXEL_NAME
level_vr = "SQ"
@enc_image = true
end
end
# Create an Element from the gathered data:
# if vr is UN ("unknown") and length is -1, treat as a sequence (sec. 6.2.2 of DICOM standard)
if level_vr == "SQ" or tag == ITEM_TAG or (level_vr == "UN" and length == -1)
if level_vr == "SQ" or (level_vr == "UN" and length == -1)
check_duplicate(tag, 'Sequence')
# If we get an unknown sequence with undefined length, we must switch to implicit for decoding its content:
if level_vr == "UN" and length == -1
@original_explicit = @explicit
@explicit = false
@explicitness_reset_parent = @current_parent
end
unless @current_parent[tag] and !@overwrite
@current_element = Sequence.new(tag, :length => length, :name => name, :parent => @current_parent, :vr => vr)
else
# We have skipped a sequence. This means that any following children
# of this sequence must be skipped as well. We solve this by creating an 'orphaned'
# sequence that has a parent defined, but does not add itself to this parent:
@current_element = Sequence.new(tag, :length => length, :name => name, :vr => vr)
@current_element.set_parent(@current_parent)
end
elsif tag == ITEM_TAG
# Create an Item:
if @enc_image
@current_element = Item.new(:bin => bin, :length => length, :name => name, :parent => @current_parent, :vr => vr)
else
@current_element = Item.new(:length => length, :name => name, :parent => @current_parent, :vr => vr)
end
end
# Common operations on the two types of parent elements:
if length == 0 and @enc_image
# Set as parent. Exceptions when parent will not be set:
# Item/Sequence has zero length & Item is a pixel item (which contains pixels, not child elements).
@current_parent = @current_element
elsif length != 0
@current_parent = @current_element unless name == PIXEL_ITEM_NAME
end
# If length is specified (no delimitation items), load a new DRead instance to read these child elements
# and load them into the current sequence. The exception is when we have a pixel data item.
if length > 0 and not @enc_image
@current_element.parse(bin, @transfer_syntax, switched=@switched, @explicit)
@current_parent = @current_parent.parent
return false unless @read_success
end
elsif DELIMITER_TAGS.include?(tag)
# We do not create an element for the delimiter items.
# The occurance of such a tag indicates that a sequence or item has ended, and the parent must be changed:
@current_parent = @current_parent.parent
else
check_duplicate(tag, 'Element')
unless @current_parent[tag] and !@overwrite
@current_element = Element.new(tag, value, :bin => bin, :name => name, :parent => @current_parent, :vr => vr)
# Check that the data stream didn't end abruptly:
raise "The actual length of the value (#{@current_element.bin.length}) does not match its specified length (#{length}) for Data Element #{@current_element.tag}" if length != @current_element.bin.length
end
end
# Return true to indicate success:
return true
end | [
"def",
"process_data_element",
"if",
"!",
"@original_explicit",
".",
"nil?",
"&&",
"@explicitness_reset_parent",
"==",
"@current_parent",
"@explicit",
"=",
"@original_explicit",
"end",
"tag",
"=",
"read_tag",
"return",
"nil",
"unless",
"tag",
"name",
",",
"vr",
"=",
"LIBRARY",
".",
"name_and_vr",
"(",
"tag",
")",
"vr",
",",
"length",
"=",
"read_vr_length",
"(",
"vr",
",",
"tag",
")",
"level_vr",
"=",
"vr",
"if",
"@enc_image",
"and",
"tag",
"==",
"ITEM_TAG",
"vr",
"=",
"\"OW\"",
"if",
"@current_element",
".",
"tag",
"!=",
"PIXEL_TAG",
"name",
"=",
"PIXEL_ITEM_NAME",
"end",
"end",
"bin",
"=",
"read_bin",
"(",
"length",
")",
"if",
"length",
">",
"0",
"if",
"length",
">",
"0",
"and",
"vr",
"!=",
"\"SQ\"",
"and",
"tag",
"!=",
"ITEM_TAG",
"value",
"=",
"read_value",
"(",
"vr",
",",
"length",
")",
"else",
"value",
"=",
"nil",
"if",
"tag",
"==",
"PIXEL_TAG",
"name",
"=",
"ENCAPSULATED_PIXEL_NAME",
"level_vr",
"=",
"\"SQ\"",
"@enc_image",
"=",
"true",
"end",
"end",
"if",
"level_vr",
"==",
"\"SQ\"",
"or",
"tag",
"==",
"ITEM_TAG",
"or",
"(",
"level_vr",
"==",
"\"UN\"",
"and",
"length",
"==",
"-",
"1",
")",
"if",
"level_vr",
"==",
"\"SQ\"",
"or",
"(",
"level_vr",
"==",
"\"UN\"",
"and",
"length",
"==",
"-",
"1",
")",
"check_duplicate",
"(",
"tag",
",",
"'Sequence'",
")",
"if",
"level_vr",
"==",
"\"UN\"",
"and",
"length",
"==",
"-",
"1",
"@original_explicit",
"=",
"@explicit",
"@explicit",
"=",
"false",
"@explicitness_reset_parent",
"=",
"@current_parent",
"end",
"unless",
"@current_parent",
"[",
"tag",
"]",
"and",
"!",
"@overwrite",
"@current_element",
"=",
"Sequence",
".",
"new",
"(",
"tag",
",",
":length",
"=>",
"length",
",",
":name",
"=>",
"name",
",",
":parent",
"=>",
"@current_parent",
",",
":vr",
"=>",
"vr",
")",
"else",
"@current_element",
"=",
"Sequence",
".",
"new",
"(",
"tag",
",",
":length",
"=>",
"length",
",",
":name",
"=>",
"name",
",",
":vr",
"=>",
"vr",
")",
"@current_element",
".",
"set_parent",
"(",
"@current_parent",
")",
"end",
"elsif",
"tag",
"==",
"ITEM_TAG",
"if",
"@enc_image",
"@current_element",
"=",
"Item",
".",
"new",
"(",
":bin",
"=>",
"bin",
",",
":length",
"=>",
"length",
",",
":name",
"=>",
"name",
",",
":parent",
"=>",
"@current_parent",
",",
":vr",
"=>",
"vr",
")",
"else",
"@current_element",
"=",
"Item",
".",
"new",
"(",
":length",
"=>",
"length",
",",
":name",
"=>",
"name",
",",
":parent",
"=>",
"@current_parent",
",",
":vr",
"=>",
"vr",
")",
"end",
"end",
"if",
"length",
"==",
"0",
"and",
"@enc_image",
"@current_parent",
"=",
"@current_element",
"elsif",
"length",
"!=",
"0",
"@current_parent",
"=",
"@current_element",
"unless",
"name",
"==",
"PIXEL_ITEM_NAME",
"end",
"if",
"length",
">",
"0",
"and",
"not",
"@enc_image",
"@current_element",
".",
"parse",
"(",
"bin",
",",
"@transfer_syntax",
",",
"switched",
"=",
"@switched",
",",
"@explicit",
")",
"@current_parent",
"=",
"@current_parent",
".",
"parent",
"return",
"false",
"unless",
"@read_success",
"end",
"elsif",
"DELIMITER_TAGS",
".",
"include?",
"(",
"tag",
")",
"@current_parent",
"=",
"@current_parent",
".",
"parent",
"else",
"check_duplicate",
"(",
"tag",
",",
"'Element'",
")",
"unless",
"@current_parent",
"[",
"tag",
"]",
"and",
"!",
"@overwrite",
"@current_element",
"=",
"Element",
".",
"new",
"(",
"tag",
",",
"value",
",",
":bin",
"=>",
"bin",
",",
":name",
"=>",
"name",
",",
":parent",
"=>",
"@current_parent",
",",
":vr",
"=>",
"vr",
")",
"raise",
"\"The actual length of the value (#{@current_element.bin.length}) does not match its specified length (#{length}) for Data Element #{@current_element.tag}\"",
"if",
"length",
"!=",
"@current_element",
".",
"bin",
".",
"length",
"end",
"end",
"return",
"true",
"end"
]
| Handles the process of reading a data element from the DICOM string, and
creating an element object from the parsed data.
@return [Boolean] nil if end of string has been reached (in an expected way), false if the element parse failed, and true if an element was parsed successfully | [
"Handles",
"the",
"process",
"of",
"reading",
"a",
"data",
"element",
"from",
"the",
"DICOM",
"string",
"and",
"creating",
"an",
"element",
"object",
"from",
"the",
"parsed",
"data",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/d_read.rb#L71-L177 | train |
dicom/ruby-dicom | lib/dicom/d_read.rb | DICOM.Parent.read | def read(string, signature=true, options={})
# (Re)Set variables:
@str = string
@overwrite = options[:overwrite]
# Presence of the official DICOM signature:
@signature = false
# Default explicitness of start of DICOM string (if undefined it defaults to true):
@explicit = options[:explicit].nil? ? true : options[:explicit]
# Default endianness of start of DICOM string is little endian:
@str_endian = false
# A switch of endianness may occur after the initial meta group, an this needs to be monitored:
@switched_endian = false
# Explicitness of the remaining groups after the initial 0002 group:
@rest_explicit = false
# Endianness of the remaining groups after the first group:
@rest_endian = false
# When the string switch from group 0002 to a later group we will update encoding values, and this switch will keep track of that:
@switched = options[:switched] ? options[:switched] : false
# Keeping track of the data element parent status while parsing the DICOM string:
@current_parent = self
# Keeping track of what is the current data element:
@current_element = self
# Items contained under the pixel data element may contain data directly, so we need a variable to keep track of this:
@enc_image = false
# Assume header size is zero bytes until otherwise is determined:
@header_length = 0
# Assume string will be read successfully and toggle it later if we experience otherwise:
@read_success = true
# Our encoding instance:
@stream = Stream.new(@str, @str_endian)
# If a transfer syntax has been specified as an option for a DICOM object,
# make sure that it makes it into the object:
if options[:syntax]
@transfer_syntax = options[:syntax]
Element.new("0002,0010", options[:syntax], :parent => self) if self.is_a?(DObject)
end
# Check for header information if indicated:
if signature
# Read and verify the DICOM header:
header = check_header
# If the string is without the expected header, we will attempt
# to read data elements from the very start of the string:
if header == false
@stream.skip(-132)
elsif header.nil?
# Not a valid DICOM string, return:
@read_success = false
return
end
end
# Run a loop which parses Data Elements, one by one, until the end of the data string is reached:
data_element = true
while data_element do
# Using a rescue clause since processing Data Elements can cause errors when parsing an invalid DICOM string.
begin
# Extracting Data element information (nil is returned if end of the string is encountered in a normal way).
data_element = process_data_element
rescue Exception => msg
# The parse algorithm crashed. Set data_element as false to break
# the loop and toggle the success boolean to indicate failure.
@read_success = false
data_element = false
# Output the raised message as a warning:
logger.warn(msg.to_s)
# Ouput the backtrace as debug information:
logger.debug(msg.backtrace)
# Explain the failure as an error:
logger.error("Parsing a Data Element has failed. This is likely caused by an invalid DICOM encoding.")
end
end
end | ruby | def read(string, signature=true, options={})
# (Re)Set variables:
@str = string
@overwrite = options[:overwrite]
# Presence of the official DICOM signature:
@signature = false
# Default explicitness of start of DICOM string (if undefined it defaults to true):
@explicit = options[:explicit].nil? ? true : options[:explicit]
# Default endianness of start of DICOM string is little endian:
@str_endian = false
# A switch of endianness may occur after the initial meta group, an this needs to be monitored:
@switched_endian = false
# Explicitness of the remaining groups after the initial 0002 group:
@rest_explicit = false
# Endianness of the remaining groups after the first group:
@rest_endian = false
# When the string switch from group 0002 to a later group we will update encoding values, and this switch will keep track of that:
@switched = options[:switched] ? options[:switched] : false
# Keeping track of the data element parent status while parsing the DICOM string:
@current_parent = self
# Keeping track of what is the current data element:
@current_element = self
# Items contained under the pixel data element may contain data directly, so we need a variable to keep track of this:
@enc_image = false
# Assume header size is zero bytes until otherwise is determined:
@header_length = 0
# Assume string will be read successfully and toggle it later if we experience otherwise:
@read_success = true
# Our encoding instance:
@stream = Stream.new(@str, @str_endian)
# If a transfer syntax has been specified as an option for a DICOM object,
# make sure that it makes it into the object:
if options[:syntax]
@transfer_syntax = options[:syntax]
Element.new("0002,0010", options[:syntax], :parent => self) if self.is_a?(DObject)
end
# Check for header information if indicated:
if signature
# Read and verify the DICOM header:
header = check_header
# If the string is without the expected header, we will attempt
# to read data elements from the very start of the string:
if header == false
@stream.skip(-132)
elsif header.nil?
# Not a valid DICOM string, return:
@read_success = false
return
end
end
# Run a loop which parses Data Elements, one by one, until the end of the data string is reached:
data_element = true
while data_element do
# Using a rescue clause since processing Data Elements can cause errors when parsing an invalid DICOM string.
begin
# Extracting Data element information (nil is returned if end of the string is encountered in a normal way).
data_element = process_data_element
rescue Exception => msg
# The parse algorithm crashed. Set data_element as false to break
# the loop and toggle the success boolean to indicate failure.
@read_success = false
data_element = false
# Output the raised message as a warning:
logger.warn(msg.to_s)
# Ouput the backtrace as debug information:
logger.debug(msg.backtrace)
# Explain the failure as an error:
logger.error("Parsing a Data Element has failed. This is likely caused by an invalid DICOM encoding.")
end
end
end | [
"def",
"read",
"(",
"string",
",",
"signature",
"=",
"true",
",",
"options",
"=",
"{",
"}",
")",
"@str",
"=",
"string",
"@overwrite",
"=",
"options",
"[",
":overwrite",
"]",
"@signature",
"=",
"false",
"@explicit",
"=",
"options",
"[",
":explicit",
"]",
".",
"nil?",
"?",
"true",
":",
"options",
"[",
":explicit",
"]",
"@str_endian",
"=",
"false",
"@switched_endian",
"=",
"false",
"@rest_explicit",
"=",
"false",
"@rest_endian",
"=",
"false",
"@switched",
"=",
"options",
"[",
":switched",
"]",
"?",
"options",
"[",
":switched",
"]",
":",
"false",
"@current_parent",
"=",
"self",
"@current_element",
"=",
"self",
"@enc_image",
"=",
"false",
"@header_length",
"=",
"0",
"@read_success",
"=",
"true",
"@stream",
"=",
"Stream",
".",
"new",
"(",
"@str",
",",
"@str_endian",
")",
"if",
"options",
"[",
":syntax",
"]",
"@transfer_syntax",
"=",
"options",
"[",
":syntax",
"]",
"Element",
".",
"new",
"(",
"\"0002,0010\"",
",",
"options",
"[",
":syntax",
"]",
",",
":parent",
"=>",
"self",
")",
"if",
"self",
".",
"is_a?",
"(",
"DObject",
")",
"end",
"if",
"signature",
"header",
"=",
"check_header",
"if",
"header",
"==",
"false",
"@stream",
".",
"skip",
"(",
"-",
"132",
")",
"elsif",
"header",
".",
"nil?",
"@read_success",
"=",
"false",
"return",
"end",
"end",
"data_element",
"=",
"true",
"while",
"data_element",
"do",
"begin",
"data_element",
"=",
"process_data_element",
"rescue",
"Exception",
"=>",
"msg",
"@read_success",
"=",
"false",
"data_element",
"=",
"false",
"logger",
".",
"warn",
"(",
"msg",
".",
"to_s",
")",
"logger",
".",
"debug",
"(",
"msg",
".",
"backtrace",
")",
"logger",
".",
"error",
"(",
"\"Parsing a Data Element has failed. This is likely caused by an invalid DICOM encoding.\"",
")",
"end",
"end",
"end"
]
| Builds a DICOM object by parsing an encoded DICOM string.
@param [String] string a binary DICOM string to be parsed
@param [Boolean] signature if true (default), the parsing algorithm will look for the DICOM header signature
@param [Hash] options the options to use for parsing the DICOM string
@option options [Boolean] :overwrite for the rare case of a DICOM file containing duplicate elements, setting this as true instructs the parsing algorithm to overwrite the original element with duplicates
@option options [String] :syntax if a syntax string is specified, the parsing algorithm is forced to use this transfer syntax when decoding the string | [
"Builds",
"a",
"DICOM",
"object",
"by",
"parsing",
"an",
"encoded",
"DICOM",
"string",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/d_read.rb#L187-L257 | train |
dicom/ruby-dicom | lib/dicom/d_write.rb | DICOM.Parent.add_with_segmentation | def add_with_segmentation(string)
# As the encoded DICOM string will be cut in multiple, smaller pieces, we need to monitor the length of our encoded strings:
if (string.length + @stream.length) > @max_size
split_and_add(string)
elsif (30 + @stream.length) > @max_size
# End the current segment, and start on a new segment for this string.
@segments << @stream.export
@stream.add_last(string)
else
# We are nowhere near the limit, simply add the string:
@stream.add_last(string)
end
end | ruby | def add_with_segmentation(string)
# As the encoded DICOM string will be cut in multiple, smaller pieces, we need to monitor the length of our encoded strings:
if (string.length + @stream.length) > @max_size
split_and_add(string)
elsif (30 + @stream.length) > @max_size
# End the current segment, and start on a new segment for this string.
@segments << @stream.export
@stream.add_last(string)
else
# We are nowhere near the limit, simply add the string:
@stream.add_last(string)
end
end | [
"def",
"add_with_segmentation",
"(",
"string",
")",
"if",
"(",
"string",
".",
"length",
"+",
"@stream",
".",
"length",
")",
">",
"@max_size",
"split_and_add",
"(",
"string",
")",
"elsif",
"(",
"30",
"+",
"@stream",
".",
"length",
")",
">",
"@max_size",
"@segments",
"<<",
"@stream",
".",
"export",
"@stream",
".",
"add_last",
"(",
"string",
")",
"else",
"@stream",
".",
"add_last",
"(",
"string",
")",
"end",
"end"
]
| Adds an encoded string to the output stream, while keeping track of the
accumulated size of the output stream, splitting it up as necessary, and
transferring the encoded string fragments to an array.
@param [String] string a pre-encoded string | [
"Adds",
"an",
"encoded",
"string",
"to",
"the",
"output",
"stream",
"while",
"keeping",
"track",
"of",
"the",
"accumulated",
"size",
"of",
"the",
"output",
"stream",
"splitting",
"it",
"up",
"as",
"necessary",
"and",
"transferring",
"the",
"encoded",
"string",
"fragments",
"to",
"an",
"array",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/d_write.rb#L31-L43 | train |
dicom/ruby-dicom | lib/dicom/d_write.rb | DICOM.Parent.check_encapsulated_image | def check_encapsulated_image(element)
# If DICOM object contains encapsulated pixel data, we need some special handling for its items:
if element.tag == PIXEL_TAG and element.parent.is_a?(DObject)
@enc_image = true if element.length <= 0
end
end | ruby | def check_encapsulated_image(element)
# If DICOM object contains encapsulated pixel data, we need some special handling for its items:
if element.tag == PIXEL_TAG and element.parent.is_a?(DObject)
@enc_image = true if element.length <= 0
end
end | [
"def",
"check_encapsulated_image",
"(",
"element",
")",
"if",
"element",
".",
"tag",
"==",
"PIXEL_TAG",
"and",
"element",
".",
"parent",
".",
"is_a?",
"(",
"DObject",
")",
"@enc_image",
"=",
"true",
"if",
"element",
".",
"length",
"<=",
"0",
"end",
"end"
]
| Toggles the status for enclosed pixel data.
@param [Element, Item, Sequence] element a data element | [
"Toggles",
"the",
"status",
"for",
"enclosed",
"pixel",
"data",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/d_write.rb#L49-L54 | train |
dicom/ruby-dicom | lib/dicom/d_write.rb | DICOM.Parent.encode_in_segments | def encode_in_segments(max_size, options={})
@max_size = max_size
@transfer_syntax = options[:syntax]
# Until a DICOM write has completed successfully the status is 'unsuccessful':
@write_success = false
# Default explicitness of start of DICOM file:
@explicit = true
# Default endianness of start of DICOM files (little endian):
@str_endian = false
# When the file switch from group 0002 to a later group we will update encoding values, and this switch will keep track of that:
@switched = false
# Items contained under the Pixel Data element needs some special attention to write correctly:
@enc_image = false
# Create a Stream instance to handle the encoding of content to a binary string:
@stream = Stream.new(nil, @str_endian)
@segments = Array.new
write_data_elements(children)
# Extract the remaining string in our stream instance to our array of strings:
@segments << @stream.export
# Mark this write session as successful:
@write_success = true
return @segments
end | ruby | def encode_in_segments(max_size, options={})
@max_size = max_size
@transfer_syntax = options[:syntax]
# Until a DICOM write has completed successfully the status is 'unsuccessful':
@write_success = false
# Default explicitness of start of DICOM file:
@explicit = true
# Default endianness of start of DICOM files (little endian):
@str_endian = false
# When the file switch from group 0002 to a later group we will update encoding values, and this switch will keep track of that:
@switched = false
# Items contained under the Pixel Data element needs some special attention to write correctly:
@enc_image = false
# Create a Stream instance to handle the encoding of content to a binary string:
@stream = Stream.new(nil, @str_endian)
@segments = Array.new
write_data_elements(children)
# Extract the remaining string in our stream instance to our array of strings:
@segments << @stream.export
# Mark this write session as successful:
@write_success = true
return @segments
end | [
"def",
"encode_in_segments",
"(",
"max_size",
",",
"options",
"=",
"{",
"}",
")",
"@max_size",
"=",
"max_size",
"@transfer_syntax",
"=",
"options",
"[",
":syntax",
"]",
"@write_success",
"=",
"false",
"@explicit",
"=",
"true",
"@str_endian",
"=",
"false",
"@switched",
"=",
"false",
"@enc_image",
"=",
"false",
"@stream",
"=",
"Stream",
".",
"new",
"(",
"nil",
",",
"@str_endian",
")",
"@segments",
"=",
"Array",
".",
"new",
"write_data_elements",
"(",
"children",
")",
"@segments",
"<<",
"@stream",
".",
"export",
"@write_success",
"=",
"true",
"return",
"@segments",
"end"
]
| Writes DICOM content to a series of size-limited binary strings, which is returned in an array.
This is typically used in preparation of transmitting DICOM objects through network connections.
@param [Integer] max_size the maximum segment string length
@param [Hash] options the options to use for encoding the DICOM strings
@option options [String] :syntax the transfer syntax used for the encoding settings of the post-meta part of the DICOM string
@return [Array<String>] the encoded DICOM strings | [
"Writes",
"DICOM",
"content",
"to",
"a",
"series",
"of",
"size",
"-",
"limited",
"binary",
"strings",
"which",
"is",
"returned",
"in",
"an",
"array",
".",
"This",
"is",
"typically",
"used",
"in",
"preparation",
"of",
"transmitting",
"DICOM",
"objects",
"through",
"network",
"connections",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/d_write.rb#L64-L86 | train |
dicom/ruby-dicom | lib/dicom/d_write.rb | DICOM.Parent.split_and_add | def split_and_add(string)
# Duplicate the string as not to ruin the binary of the data element with our slicing:
segment = string.dup
append = segment.slice!(0, @[email protected])
# Clear out the stream along with a small part of the string:
@segments << @stream.export + append
if (30 + segment.length) > @max_size
# The remaining part of the string is bigger than the max limit, fill up more segments:
# How many full segments will this string fill?
number = (segment.length/@max_size.to_f).floor
start_index = 0
number.times {
@segments << segment.slice(start_index, @max_size)
start_index += @max_size
}
# The remaining part is added to the stream:
@stream.add_last(segment.slice(start_index, segment.length - start_index))
else
# The rest of the string is small enough that it can be added to the stream:
@stream.add_last(segment)
end
end | ruby | def split_and_add(string)
# Duplicate the string as not to ruin the binary of the data element with our slicing:
segment = string.dup
append = segment.slice!(0, @[email protected])
# Clear out the stream along with a small part of the string:
@segments << @stream.export + append
if (30 + segment.length) > @max_size
# The remaining part of the string is bigger than the max limit, fill up more segments:
# How many full segments will this string fill?
number = (segment.length/@max_size.to_f).floor
start_index = 0
number.times {
@segments << segment.slice(start_index, @max_size)
start_index += @max_size
}
# The remaining part is added to the stream:
@stream.add_last(segment.slice(start_index, segment.length - start_index))
else
# The rest of the string is small enough that it can be added to the stream:
@stream.add_last(segment)
end
end | [
"def",
"split_and_add",
"(",
"string",
")",
"segment",
"=",
"string",
".",
"dup",
"append",
"=",
"segment",
".",
"slice!",
"(",
"0",
",",
"@max_size",
"-",
"@stream",
".",
"length",
")",
"@segments",
"<<",
"@stream",
".",
"export",
"+",
"append",
"if",
"(",
"30",
"+",
"segment",
".",
"length",
")",
">",
"@max_size",
"number",
"=",
"(",
"segment",
".",
"length",
"/",
"@max_size",
".",
"to_f",
")",
".",
"floor",
"start_index",
"=",
"0",
"number",
".",
"times",
"{",
"@segments",
"<<",
"segment",
".",
"slice",
"(",
"start_index",
",",
"@max_size",
")",
"start_index",
"+=",
"@max_size",
"}",
"@stream",
".",
"add_last",
"(",
"segment",
".",
"slice",
"(",
"start_index",
",",
"segment",
".",
"length",
"-",
"start_index",
")",
")",
"else",
"@stream",
".",
"add_last",
"(",
"segment",
")",
"end",
"end"
]
| Splits a pre-encoded string in parts and adds it to the segments instance
array.
@param [String] string a pre-encoded string | [
"Splits",
"a",
"pre",
"-",
"encoded",
"string",
"in",
"parts",
"and",
"adds",
"it",
"to",
"the",
"segments",
"instance",
"array",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/d_write.rb#L127-L148 | train |
dicom/ruby-dicom | lib/dicom/d_write.rb | DICOM.Parent.write_data_element | def write_data_element(element)
# Step 1: Write tag:
write_tag(element.tag)
# Step 2: Write [VR] and value length:
write_vr_length(element.tag, element.vr, element.length)
# Step 3: Write value (Insert the already encoded binary string):
write_value(element.bin)
check_encapsulated_image(element)
end | ruby | def write_data_element(element)
# Step 1: Write tag:
write_tag(element.tag)
# Step 2: Write [VR] and value length:
write_vr_length(element.tag, element.vr, element.length)
# Step 3: Write value (Insert the already encoded binary string):
write_value(element.bin)
check_encapsulated_image(element)
end | [
"def",
"write_data_element",
"(",
"element",
")",
"write_tag",
"(",
"element",
".",
"tag",
")",
"write_vr_length",
"(",
"element",
".",
"tag",
",",
"element",
".",
"vr",
",",
"element",
".",
"length",
")",
"write_value",
"(",
"element",
".",
"bin",
")",
"check_encapsulated_image",
"(",
"element",
")",
"end"
]
| Encodes and writes a single data element.
@param [Element, Item, Sequence] element a data element | [
"Encodes",
"and",
"writes",
"a",
"single",
"data",
"element",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/d_write.rb#L154-L162 | train |
dicom/ruby-dicom | lib/dicom/d_write.rb | DICOM.Parent.write_delimiter | def write_delimiter(element)
delimiter_tag = (element.tag == ITEM_TAG ? ITEM_DELIMITER : SEQUENCE_DELIMITER)
write_tag(delimiter_tag)
write_vr_length(delimiter_tag, ITEM_VR, 0)
end | ruby | def write_delimiter(element)
delimiter_tag = (element.tag == ITEM_TAG ? ITEM_DELIMITER : SEQUENCE_DELIMITER)
write_tag(delimiter_tag)
write_vr_length(delimiter_tag, ITEM_VR, 0)
end | [
"def",
"write_delimiter",
"(",
"element",
")",
"delimiter_tag",
"=",
"(",
"element",
".",
"tag",
"==",
"ITEM_TAG",
"?",
"ITEM_DELIMITER",
":",
"SEQUENCE_DELIMITER",
")",
"write_tag",
"(",
"delimiter_tag",
")",
"write_vr_length",
"(",
"delimiter_tag",
",",
"ITEM_VR",
",",
"0",
")",
"end"
]
| Encodes and writes an Item or Sequence delimiter.
@param [Item, Sequence] element a parent element | [
"Encodes",
"and",
"writes",
"an",
"Item",
"or",
"Sequence",
"delimiter",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/d_write.rb#L212-L216 | train |
dicom/ruby-dicom | lib/dicom/d_write.rb | DICOM.Parent.write_elements | def write_elements(options={})
# Check if we are able to create given file:
open_file(options[:file_name])
# Go ahead and write if the file was opened successfully:
if @file
# Initiate necessary variables:
@transfer_syntax = options[:syntax]
# Until a DICOM write has completed successfully the status is 'unsuccessful':
@write_success = false
# Default explicitness of start of DICOM file:
@explicit = true
# Default endianness of start of DICOM files (little endian):
@str_endian = false
# When the file switch from group 0002 to a later group we will update encoding values, and this switch will keep track of that:
@switched = false
# Items contained under the Pixel Data element needs some special attention to write correctly:
@enc_image = false
# Create a Stream instance to handle the encoding of content to a binary string:
@stream = Stream.new(nil, @str_endian)
# Tell the Stream instance which file to write to:
@stream.set_file(@file)
# Write the DICOM signature:
write_signature if options[:signature]
write_data_elements(children)
# As file has been written successfully, it can be closed.
@file.close
# Mark this write session as successful:
@write_success = true
end
end | ruby | def write_elements(options={})
# Check if we are able to create given file:
open_file(options[:file_name])
# Go ahead and write if the file was opened successfully:
if @file
# Initiate necessary variables:
@transfer_syntax = options[:syntax]
# Until a DICOM write has completed successfully the status is 'unsuccessful':
@write_success = false
# Default explicitness of start of DICOM file:
@explicit = true
# Default endianness of start of DICOM files (little endian):
@str_endian = false
# When the file switch from group 0002 to a later group we will update encoding values, and this switch will keep track of that:
@switched = false
# Items contained under the Pixel Data element needs some special attention to write correctly:
@enc_image = false
# Create a Stream instance to handle the encoding of content to a binary string:
@stream = Stream.new(nil, @str_endian)
# Tell the Stream instance which file to write to:
@stream.set_file(@file)
# Write the DICOM signature:
write_signature if options[:signature]
write_data_elements(children)
# As file has been written successfully, it can be closed.
@file.close
# Mark this write session as successful:
@write_success = true
end
end | [
"def",
"write_elements",
"(",
"options",
"=",
"{",
"}",
")",
"open_file",
"(",
"options",
"[",
":file_name",
"]",
")",
"if",
"@file",
"@transfer_syntax",
"=",
"options",
"[",
":syntax",
"]",
"@write_success",
"=",
"false",
"@explicit",
"=",
"true",
"@str_endian",
"=",
"false",
"@switched",
"=",
"false",
"@enc_image",
"=",
"false",
"@stream",
"=",
"Stream",
".",
"new",
"(",
"nil",
",",
"@str_endian",
")",
"@stream",
".",
"set_file",
"(",
"@file",
")",
"write_signature",
"if",
"options",
"[",
":signature",
"]",
"write_data_elements",
"(",
"children",
")",
"@file",
".",
"close",
"@write_success",
"=",
"true",
"end",
"end"
]
| Handles the encoding of DICOM information to string as well as writing it to file.
@param [Hash] options the options to use for encoding the DICOM string
@option options [String] :file_name the path & name of the DICOM file which is to be written to disk
@option options [Boolean] :signature if true, the 128 byte preamble and 'DICM' signature is prepended to the encoded string
@option options [String] :syntax the transfer syntax used for the encoding settings of the post-meta part of the DICOM string | [
"Handles",
"the",
"encoding",
"of",
"DICOM",
"information",
"to",
"string",
"as",
"well",
"as",
"writing",
"it",
"to",
"file",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/d_write.rb#L225-L254 | train |
dicom/ruby-dicom | lib/dicom/elemental.rb | DICOM.Elemental.stream | def stream
if top_parent.is_a?(DObject)
return top_parent.stream
else
return Stream.new(nil, file_endian=false)
end
end | ruby | def stream
if top_parent.is_a?(DObject)
return top_parent.stream
else
return Stream.new(nil, file_endian=false)
end
end | [
"def",
"stream",
"if",
"top_parent",
".",
"is_a?",
"(",
"DObject",
")",
"return",
"top_parent",
".",
"stream",
"else",
"return",
"Stream",
".",
"new",
"(",
"nil",
",",
"file_endian",
"=",
"false",
")",
"end",
"end"
]
| Returns a Stream instance which can be used for encoding a value to binary.
@note Retrieves the Stream instance of the top parent DObject instance.
If this fails, a new Stream instance is created (with little endian encoding assumed). | [
"Returns",
"a",
"Stream",
"instance",
"which",
"can",
"be",
"used",
"for",
"encoding",
"a",
"value",
"to",
"binary",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/elemental.rb#L93-L99 | train |
dicom/ruby-dicom | lib/dicom/d_library.rb | DICOM.DLibrary.add_element | def add_element(element)
raise ArgumentError, "Invalid argument 'element'. Expected DictionaryElement, got #{element.class}" unless element.is_a?(DictionaryElement)
# We store the elements in a hash with tag as key and the element instance as value:
@elements[element.tag] = element
# Populate the method conversion hashes with element data:
method = element.name.to_element_method
@methods_from_names[element.name] = method
@names_from_methods[method] = element.name
end | ruby | def add_element(element)
raise ArgumentError, "Invalid argument 'element'. Expected DictionaryElement, got #{element.class}" unless element.is_a?(DictionaryElement)
# We store the elements in a hash with tag as key and the element instance as value:
@elements[element.tag] = element
# Populate the method conversion hashes with element data:
method = element.name.to_element_method
@methods_from_names[element.name] = method
@names_from_methods[method] = element.name
end | [
"def",
"add_element",
"(",
"element",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'element'. Expected DictionaryElement, got #{element.class}\"",
"unless",
"element",
".",
"is_a?",
"(",
"DictionaryElement",
")",
"@elements",
"[",
"element",
".",
"tag",
"]",
"=",
"element",
"method",
"=",
"element",
".",
"name",
".",
"to_element_method",
"@methods_from_names",
"[",
"element",
".",
"name",
"]",
"=",
"method",
"@names_from_methods",
"[",
"method",
"]",
"=",
"element",
".",
"name",
"end"
]
| Creates a DLibrary instance.
Adds a custom DictionaryElement to the ruby-dicom element dictionary.
@param [DictionaryElement] element the custom dictionary element to be added | [
"Creates",
"a",
"DLibrary",
"instance",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/d_library.rb#L40-L48 | train |
dicom/ruby-dicom | lib/dicom/d_library.rb | DICOM.DLibrary.add_element_dictionary | def add_element_dictionary(file)
File.open(file, :encoding => 'utf-8').each do |record|
fields = record.split("\t")
add_element(DictionaryElement.new(fields[0], fields[1], fields[2].split(","), fields[3].rstrip, fields[4].rstrip))
end
end | ruby | def add_element_dictionary(file)
File.open(file, :encoding => 'utf-8').each do |record|
fields = record.split("\t")
add_element(DictionaryElement.new(fields[0], fields[1], fields[2].split(","), fields[3].rstrip, fields[4].rstrip))
end
end | [
"def",
"add_element_dictionary",
"(",
"file",
")",
"File",
".",
"open",
"(",
"file",
",",
":encoding",
"=>",
"'utf-8'",
")",
".",
"each",
"do",
"|",
"record",
"|",
"fields",
"=",
"record",
".",
"split",
"(",
"\"\\t\"",
")",
"add_element",
"(",
"DictionaryElement",
".",
"new",
"(",
"fields",
"[",
"0",
"]",
",",
"fields",
"[",
"1",
"]",
",",
"fields",
"[",
"2",
"]",
".",
"split",
"(",
"\",\"",
")",
",",
"fields",
"[",
"3",
"]",
".",
"rstrip",
",",
"fields",
"[",
"4",
"]",
".",
"rstrip",
")",
")",
"end",
"end"
]
| Adds a custom dictionary file to the ruby-dicom element dictionary.
@note The format of the dictionary is a tab-separated text file with 5 columns:
* Tag, Name, VR, VM & Retired status
* For samples check out ruby-dicom's element dictionaries in the git repository
@param [String] file the path to the dictionary file to be added | [
"Adds",
"a",
"custom",
"dictionary",
"file",
"to",
"the",
"ruby",
"-",
"dicom",
"element",
"dictionary",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/d_library.rb#L57-L62 | train |
dicom/ruby-dicom | lib/dicom/d_library.rb | DICOM.DLibrary.add_uid_dictionary | def add_uid_dictionary(file)
File.open(file, :encoding => 'utf-8').each do |record|
fields = record.split("\t")
add_uid(UID.new(fields[0], fields[1], fields[2].rstrip, fields[3].rstrip))
end
end | ruby | def add_uid_dictionary(file)
File.open(file, :encoding => 'utf-8').each do |record|
fields = record.split("\t")
add_uid(UID.new(fields[0], fields[1], fields[2].rstrip, fields[3].rstrip))
end
end | [
"def",
"add_uid_dictionary",
"(",
"file",
")",
"File",
".",
"open",
"(",
"file",
",",
":encoding",
"=>",
"'utf-8'",
")",
".",
"each",
"do",
"|",
"record",
"|",
"fields",
"=",
"record",
".",
"split",
"(",
"\"\\t\"",
")",
"add_uid",
"(",
"UID",
".",
"new",
"(",
"fields",
"[",
"0",
"]",
",",
"fields",
"[",
"1",
"]",
",",
"fields",
"[",
"2",
"]",
".",
"rstrip",
",",
"fields",
"[",
"3",
"]",
".",
"rstrip",
")",
")",
"end",
"end"
]
| Adds a custom dictionary file to the ruby-dicom uid dictionary.
@note The format of the dictionary is a tab-separated text file with 4 columns:
* Value, Name, Type & Retired status
* For samples check out ruby-dicom's uid dictionaries in the git repository
@param [String] file the path to the dictionary file to be added | [
"Adds",
"a",
"custom",
"dictionary",
"file",
"to",
"the",
"ruby",
"-",
"dicom",
"uid",
"dictionary",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/d_library.rb#L81-L86 | train |
dicom/ruby-dicom | lib/dicom/d_library.rb | DICOM.DLibrary.as_name | def as_name(value)
case true
when value.tag?
element(value).name
when value.dicom_name?
@methods_from_names.has_key?(value) ? value.to_s : nil
when value.dicom_method?
@names_from_methods[value.to_sym]
else
nil
end
end | ruby | def as_name(value)
case true
when value.tag?
element(value).name
when value.dicom_name?
@methods_from_names.has_key?(value) ? value.to_s : nil
when value.dicom_method?
@names_from_methods[value.to_sym]
else
nil
end
end | [
"def",
"as_name",
"(",
"value",
")",
"case",
"true",
"when",
"value",
".",
"tag?",
"element",
"(",
"value",
")",
".",
"name",
"when",
"value",
".",
"dicom_name?",
"@methods_from_names",
".",
"has_key?",
"(",
"value",
")",
"?",
"value",
".",
"to_s",
":",
"nil",
"when",
"value",
".",
"dicom_method?",
"@names_from_methods",
"[",
"value",
".",
"to_sym",
"]",
"else",
"nil",
"end",
"end"
]
| Gives the name corresponding to the specified element string value.
@param [String] value an element tag, element name or an element's method name
@return [String, NilClass] the matched element name, or nil if no match is made | [
"Gives",
"the",
"name",
"corresponding",
"to",
"the",
"specified",
"element",
"string",
"value",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/d_library.rb#L112-L123 | train |
dicom/ruby-dicom | lib/dicom/d_library.rb | DICOM.DLibrary.as_tag | def as_tag(value)
case true
when value.tag?
element(value) ? value : nil
when value.dicom_name?
get_tag(value)
when value.dicom_method?
get_tag(@names_from_methods[value.to_sym])
else
nil
end
end | ruby | def as_tag(value)
case true
when value.tag?
element(value) ? value : nil
when value.dicom_name?
get_tag(value)
when value.dicom_method?
get_tag(@names_from_methods[value.to_sym])
else
nil
end
end | [
"def",
"as_tag",
"(",
"value",
")",
"case",
"true",
"when",
"value",
".",
"tag?",
"element",
"(",
"value",
")",
"?",
"value",
":",
"nil",
"when",
"value",
".",
"dicom_name?",
"get_tag",
"(",
"value",
")",
"when",
"value",
".",
"dicom_method?",
"get_tag",
"(",
"@names_from_methods",
"[",
"value",
".",
"to_sym",
"]",
")",
"else",
"nil",
"end",
"end"
]
| Gives the tag corresponding to the specified element string value.
@param [String] value an element tag, element name or an element's method name
@return [String, NilClass] the matched element tag, or nil if no match is made | [
"Gives",
"the",
"tag",
"corresponding",
"to",
"the",
"specified",
"element",
"string",
"value",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/d_library.rb#L130-L141 | train |
dicom/ruby-dicom | lib/dicom/d_library.rb | DICOM.DLibrary.element | def element(tag)
element = @elements[tag]
unless element
if tag.group_length?
element = DictionaryElement.new(tag, 'Group Length', ['UL'], '1', '')
else
if tag.private?
element = DictionaryElement.new(tag, 'Private', ['UN'], '1', '')
else
element = unknown_or_range_element(tag)
end
end
end
element
end | ruby | def element(tag)
element = @elements[tag]
unless element
if tag.group_length?
element = DictionaryElement.new(tag, 'Group Length', ['UL'], '1', '')
else
if tag.private?
element = DictionaryElement.new(tag, 'Private', ['UN'], '1', '')
else
element = unknown_or_range_element(tag)
end
end
end
element
end | [
"def",
"element",
"(",
"tag",
")",
"element",
"=",
"@elements",
"[",
"tag",
"]",
"unless",
"element",
"if",
"tag",
".",
"group_length?",
"element",
"=",
"DictionaryElement",
".",
"new",
"(",
"tag",
",",
"'Group Length'",
",",
"[",
"'UL'",
"]",
",",
"'1'",
",",
"''",
")",
"else",
"if",
"tag",
".",
"private?",
"element",
"=",
"DictionaryElement",
".",
"new",
"(",
"tag",
",",
"'Private'",
",",
"[",
"'UN'",
"]",
",",
"'1'",
",",
"''",
")",
"else",
"element",
"=",
"unknown_or_range_element",
"(",
"tag",
")",
"end",
"end",
"end",
"element",
"end"
]
| Identifies the DictionaryElement that corresponds to the given tag.
@note If a given tag doesn't return a dictionary match, a new DictionaryElement is created.
* For private tags, a name 'Private' and VR 'UN' is assigned
* For unknown tags, a name 'Unknown' and VR 'UN' is assigned
@param [String] tag the tag of the element
@return [DictionaryElement] a corresponding DictionaryElement | [
"Identifies",
"the",
"DictionaryElement",
"that",
"corresponds",
"to",
"the",
"given",
"tag",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/d_library.rb#L151-L165 | train |
dicom/ruby-dicom | lib/dicom/d_library.rb | DICOM.DLibrary.extract_transfer_syntaxes_and_sop_classes | def extract_transfer_syntaxes_and_sop_classes
transfer_syntaxes = Hash.new
sop_classes = Hash.new
@uids.each_value do |uid|
if uid.transfer_syntax?
transfer_syntaxes[uid.value] = uid.name
elsif uid.sop_class?
sop_classes[uid.value] = uid.name
end
end
return transfer_syntaxes, sop_classes
end | ruby | def extract_transfer_syntaxes_and_sop_classes
transfer_syntaxes = Hash.new
sop_classes = Hash.new
@uids.each_value do |uid|
if uid.transfer_syntax?
transfer_syntaxes[uid.value] = uid.name
elsif uid.sop_class?
sop_classes[uid.value] = uid.name
end
end
return transfer_syntaxes, sop_classes
end | [
"def",
"extract_transfer_syntaxes_and_sop_classes",
"transfer_syntaxes",
"=",
"Hash",
".",
"new",
"sop_classes",
"=",
"Hash",
".",
"new",
"@uids",
".",
"each_value",
"do",
"|",
"uid",
"|",
"if",
"uid",
".",
"transfer_syntax?",
"transfer_syntaxes",
"[",
"uid",
".",
"value",
"]",
"=",
"uid",
".",
"name",
"elsif",
"uid",
".",
"sop_class?",
"sop_classes",
"[",
"uid",
".",
"value",
"]",
"=",
"uid",
".",
"name",
"end",
"end",
"return",
"transfer_syntaxes",
",",
"sop_classes",
"end"
]
| Extracts, and returns, all transfer syntaxes and SOP Classes from the dictionary.
@return [Array<Hash, Hash>] transfer syntax and sop class hashes, each with uid as key and name as value | [
"Extracts",
"and",
"returns",
"all",
"transfer",
"syntaxes",
"and",
"SOP",
"Classes",
"from",
"the",
"dictionary",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/d_library.rb#L171-L182 | train |
dicom/ruby-dicom | lib/dicom/d_library.rb | DICOM.DLibrary.get_tag | def get_tag(name)
tag = nil
name = name.to_s.downcase
@tag_name_pairs_cache ||= Hash.new
return @tag_name_pairs_cache[name] unless @tag_name_pairs_cache[name].nil?
@elements.each_value do |element|
next unless element.name.downcase == name
tag = element.tag
break
end
@tag_name_pairs_cache[name]=tag
return tag
end | ruby | def get_tag(name)
tag = nil
name = name.to_s.downcase
@tag_name_pairs_cache ||= Hash.new
return @tag_name_pairs_cache[name] unless @tag_name_pairs_cache[name].nil?
@elements.each_value do |element|
next unless element.name.downcase == name
tag = element.tag
break
end
@tag_name_pairs_cache[name]=tag
return tag
end | [
"def",
"get_tag",
"(",
"name",
")",
"tag",
"=",
"nil",
"name",
"=",
"name",
".",
"to_s",
".",
"downcase",
"@tag_name_pairs_cache",
"||=",
"Hash",
".",
"new",
"return",
"@tag_name_pairs_cache",
"[",
"name",
"]",
"unless",
"@tag_name_pairs_cache",
"[",
"name",
"]",
".",
"nil?",
"@elements",
".",
"each_value",
"do",
"|",
"element",
"|",
"next",
"unless",
"element",
".",
"name",
".",
"downcase",
"==",
"name",
"tag",
"=",
"element",
".",
"tag",
"break",
"end",
"@tag_name_pairs_cache",
"[",
"name",
"]",
"=",
"tag",
"return",
"tag",
"end"
]
| Gives the tag that matches the supplied data element name, by searching the element dictionary.
@param [String] name a data element name
@return [String, NilClass] the corresponding element tag, or nil if no match is made | [
"Gives",
"the",
"tag",
"that",
"matches",
"the",
"supplied",
"data",
"element",
"name",
"by",
"searching",
"the",
"element",
"dictionary",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/d_library.rb#L189-L201 | train |
dicom/ruby-dicom | lib/dicom/d_library.rb | DICOM.DLibrary.unknown_or_range_element | def unknown_or_range_element(tag)
element = nil
range_candidates(tag).each do |range_candidate_tag|
if de = @elements[range_candidate_tag]
element = DictionaryElement.new(tag, de.name, de.vrs, de.vm, de.retired)
break
end
end
# If nothing was matched, we are facing an unknown (but not private) tag:
element ||= DictionaryElement.new(tag, 'Unknown', ['UN'], '1', '')
end | ruby | def unknown_or_range_element(tag)
element = nil
range_candidates(tag).each do |range_candidate_tag|
if de = @elements[range_candidate_tag]
element = DictionaryElement.new(tag, de.name, de.vrs, de.vm, de.retired)
break
end
end
# If nothing was matched, we are facing an unknown (but not private) tag:
element ||= DictionaryElement.new(tag, 'Unknown', ['UN'], '1', '')
end | [
"def",
"unknown_or_range_element",
"(",
"tag",
")",
"element",
"=",
"nil",
"range_candidates",
"(",
"tag",
")",
".",
"each",
"do",
"|",
"range_candidate_tag",
"|",
"if",
"de",
"=",
"@elements",
"[",
"range_candidate_tag",
"]",
"element",
"=",
"DictionaryElement",
".",
"new",
"(",
"tag",
",",
"de",
".",
"name",
",",
"de",
".",
"vrs",
",",
"de",
".",
"vm",
",",
"de",
".",
"retired",
")",
"break",
"end",
"end",
"element",
"||=",
"DictionaryElement",
".",
"new",
"(",
"tag",
",",
"'Unknown'",
",",
"[",
"'UN'",
"]",
",",
"'1'",
",",
"''",
")",
"end"
]
| Matches a tag against the possible range tag candidates, and if no match
is found, returns a dictionary element representing an unknown tag.
@param [String] tag the element tag
@return [DictionaryElement] a matched range element or an unknown element | [
"Matches",
"a",
"tag",
"against",
"the",
"possible",
"range",
"tag",
"candidates",
"and",
"if",
"no",
"match",
"is",
"found",
"returns",
"a",
"dictionary",
"element",
"representing",
"an",
"unknown",
"tag",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/d_library.rb#L255-L265 | train |
oscar-stack/vagrant-auto_network | lib/auto_network/pool_manager.rb | AutoNetwork.PoolManager.with_pool_for | def with_pool_for(machine, read_only=false)
@pool_storage.transaction(read_only) do
pool = lookup_pool_for(machine)
pool ||= generate_pool_for(machine)
yield pool
end
end | ruby | def with_pool_for(machine, read_only=false)
@pool_storage.transaction(read_only) do
pool = lookup_pool_for(machine)
pool ||= generate_pool_for(machine)
yield pool
end
end | [
"def",
"with_pool_for",
"(",
"machine",
",",
"read_only",
"=",
"false",
")",
"@pool_storage",
".",
"transaction",
"(",
"read_only",
")",
"do",
"pool",
"=",
"lookup_pool_for",
"(",
"machine",
")",
"pool",
"||=",
"generate_pool_for",
"(",
"machine",
")",
"yield",
"pool",
"end",
"end"
]
| Create a new `PoolManager` instance with persistent storage.
@param path [String, Pathname] the location at which to persist the state
of `AutoNetwork` pools.
Looks up the pool associated with the provider for a given machine and
sets up a transaction where the state of the pool can be safely inspected
or modified. If a pool does not exist for the machine provider, one will
automatically be created.
@param machine [Vagrant::Machine]
@param read_only [Boolean] whether to create a read_only transaction.
@yieldparam pool [AutoNetwork::Pool] | [
"Create",
"a",
"new",
"PoolManager",
"instance",
"with",
"persistent",
"storage",
"."
]
| 5b4b4d5b5cb18dc1417e91650adb713b9f54ab01 | https://github.com/oscar-stack/vagrant-auto_network/blob/5b4b4d5b5cb18dc1417e91650adb713b9f54ab01/lib/auto_network/pool_manager.rb#L43-L50 | train |
oscar-stack/vagrant-auto_network | lib/auto_network/action/base.rb | AutoNetwork.Action::Base.machine_auto_networks | def machine_auto_networks(machine)
machine.config.vm.networks.select do |(net_type, options)|
net_type == :private_network and options[:auto_network]
end
end | ruby | def machine_auto_networks(machine)
machine.config.vm.networks.select do |(net_type, options)|
net_type == :private_network and options[:auto_network]
end
end | [
"def",
"machine_auto_networks",
"(",
"machine",
")",
"machine",
".",
"config",
".",
"vm",
".",
"networks",
".",
"select",
"do",
"|",
"(",
"net_type",
",",
"options",
")",
"|",
"net_type",
"==",
":private_network",
"and",
"options",
"[",
":auto_network",
"]",
"end",
"end"
]
| Fetch all private networks that are tagged for auto networking
@param machine [Vagrant::Machine]
@return [Array(Symbol, Hash)] All auto_networks | [
"Fetch",
"all",
"private",
"networks",
"that",
"are",
"tagged",
"for",
"auto",
"networking"
]
| 5b4b4d5b5cb18dc1417e91650adb713b9f54ab01 | https://github.com/oscar-stack/vagrant-auto_network/blob/5b4b4d5b5cb18dc1417e91650adb713b9f54ab01/lib/auto_network/action/base.rb#L45-L49 | train |
oscar-stack/vagrant-auto_network | lib/auto_network/pool.rb | AutoNetwork.Pool.request | def request(machine)
if (address = address_for(machine))
return address
elsif (address = next_available_lease)
@pool[address] = id_for(machine)
return address
else
raise PoolExhaustedError,
:name => machine.name,
:network => @network_range
end
end | ruby | def request(machine)
if (address = address_for(machine))
return address
elsif (address = next_available_lease)
@pool[address] = id_for(machine)
return address
else
raise PoolExhaustedError,
:name => machine.name,
:network => @network_range
end
end | [
"def",
"request",
"(",
"machine",
")",
"if",
"(",
"address",
"=",
"address_for",
"(",
"machine",
")",
")",
"return",
"address",
"elsif",
"(",
"address",
"=",
"next_available_lease",
")",
"@pool",
"[",
"address",
"]",
"=",
"id_for",
"(",
"machine",
")",
"return",
"address",
"else",
"raise",
"PoolExhaustedError",
",",
":name",
"=>",
"machine",
".",
"name",
",",
":network",
"=>",
"@network_range",
"end",
"end"
]
| Create a new Pool object that manages a range of IP addresses.
@param network_range [String] The network address range to use as the
address pool.
Allocate an IP address for the given machine. If a machine already has an
IP address allocated, then return that.
@param machine [Vagrant::Machine]
@return [IPAddr] the IP address assigned to the machine.
@raise [PoolExhaustedError] if no allocatable addresses remain in the
range managed by the pool. | [
"Create",
"a",
"new",
"Pool",
"object",
"that",
"manages",
"a",
"range",
"of",
"IP",
"addresses",
"."
]
| 5b4b4d5b5cb18dc1417e91650adb713b9f54ab01 | https://github.com/oscar-stack/vagrant-auto_network/blob/5b4b4d5b5cb18dc1417e91650adb713b9f54ab01/lib/auto_network/pool.rb#L35-L46 | train |
oscar-stack/vagrant-auto_network | lib/auto_network/pool.rb | AutoNetwork.Pool.address_for | def address_for(machine)
machine_id = id_for(machine)
addr, _ = @pool.find do |(addr, id)|
if id.is_a?(String)
# Check for old-style UUID values. These should eventually cycle out
# as machines are destroyed.
id == machine.id
else
id == machine_id
end
end
addr
end | ruby | def address_for(machine)
machine_id = id_for(machine)
addr, _ = @pool.find do |(addr, id)|
if id.is_a?(String)
# Check for old-style UUID values. These should eventually cycle out
# as machines are destroyed.
id == machine.id
else
id == machine_id
end
end
addr
end | [
"def",
"address_for",
"(",
"machine",
")",
"machine_id",
"=",
"id_for",
"(",
"machine",
")",
"addr",
",",
"_",
"=",
"@pool",
".",
"find",
"do",
"|",
"(",
"addr",
",",
"id",
")",
"|",
"if",
"id",
".",
"is_a?",
"(",
"String",
")",
"id",
"==",
"machine",
".",
"id",
"else",
"id",
"==",
"machine_id",
"end",
"end",
"addr",
"end"
]
| Look up the address assigned to a given machine.
@param machine [Vagrant::Machine]
@return [IPAddr] the IP address assigned to the machine.
@return [nil] if the machine has no address assigned. | [
"Look",
"up",
"the",
"address",
"assigned",
"to",
"a",
"given",
"machine",
"."
]
| 5b4b4d5b5cb18dc1417e91650adb713b9f54ab01 | https://github.com/oscar-stack/vagrant-auto_network/blob/5b4b4d5b5cb18dc1417e91650adb713b9f54ab01/lib/auto_network/pool.rb#L63-L76 | train |
oscar-stack/vagrant-auto_network | lib/auto_network/settings.rb | AutoNetwork.Settings.default_pool= | def default_pool=(pool)
# Ensure the pool is valid.
begin
IPAddr.new pool
rescue ArgumentError
raise InvalidSettingErrror,
:setting_name => 'default_pool',
:value => pool.inspect
end
@default_pool = pool
end | ruby | def default_pool=(pool)
# Ensure the pool is valid.
begin
IPAddr.new pool
rescue ArgumentError
raise InvalidSettingErrror,
:setting_name => 'default_pool',
:value => pool.inspect
end
@default_pool = pool
end | [
"def",
"default_pool",
"=",
"(",
"pool",
")",
"begin",
"IPAddr",
".",
"new",
"pool",
"rescue",
"ArgumentError",
"raise",
"InvalidSettingErrror",
",",
":setting_name",
"=>",
"'default_pool'",
",",
":value",
"=>",
"pool",
".",
"inspect",
"end",
"@default_pool",
"=",
"pool",
"end"
]
| Set the default pool to a new IP range.
@param pool [String]
@raise [InvalidSettingErrror] if an IPAddr object cannot be initialized
from the value of pool.
@return [void] | [
"Set",
"the",
"default",
"pool",
"to",
"a",
"new",
"IP",
"range",
"."
]
| 5b4b4d5b5cb18dc1417e91650adb713b9f54ab01 | https://github.com/oscar-stack/vagrant-auto_network/blob/5b4b4d5b5cb18dc1417e91650adb713b9f54ab01/lib/auto_network/settings.rb#L60-L71 | train |
jarmo/RAutomation | lib/rautomation/element_collections.rb | RAutomation.ElementCollections.has_many | def has_many(*elements)
elements.each do |element|
class_name_plural = element.to_s.split("_").map {|e| e.capitalize}.join
class_name = class_name_plural.chop
adapter_class = self.to_s.scan(/(.*)::/).flatten.first
clazz = RAutomation.constants.include?(class_name) ? RAutomation : class_eval(adapter_class)
clazz.class_eval %Q{
class #{class_name_plural}
include Enumerable
def initialize(window, locators)
if locators[:hwnd] || locators[:pid]
raise UnsupportedLocatorException,
":hwnd or :pid in " + locators.inspect + " are not supported for #{adapter_class}::#{class_name_plural}"
end
@window = window
@locators = locators
end
def each
i = -1
while true
args = [@window, @locators.merge(:index => i += 1)].compact
object = #{clazz}::#{class_name}.new(*args)
break unless object.exists?
yield object
end
end
def method_missing(name, *args)
ary = self.to_a
ary.respond_to?(name) ? ary.send(name, *args) : super
end
end
}
class_eval %Q{
def #{element}(locators = {})
#{adapter_class}::#{class_name_plural}.new(@window || self, locators)
end
}
end
end | ruby | def has_many(*elements)
elements.each do |element|
class_name_plural = element.to_s.split("_").map {|e| e.capitalize}.join
class_name = class_name_plural.chop
adapter_class = self.to_s.scan(/(.*)::/).flatten.first
clazz = RAutomation.constants.include?(class_name) ? RAutomation : class_eval(adapter_class)
clazz.class_eval %Q{
class #{class_name_plural}
include Enumerable
def initialize(window, locators)
if locators[:hwnd] || locators[:pid]
raise UnsupportedLocatorException,
":hwnd or :pid in " + locators.inspect + " are not supported for #{adapter_class}::#{class_name_plural}"
end
@window = window
@locators = locators
end
def each
i = -1
while true
args = [@window, @locators.merge(:index => i += 1)].compact
object = #{clazz}::#{class_name}.new(*args)
break unless object.exists?
yield object
end
end
def method_missing(name, *args)
ary = self.to_a
ary.respond_to?(name) ? ary.send(name, *args) : super
end
end
}
class_eval %Q{
def #{element}(locators = {})
#{adapter_class}::#{class_name_plural}.new(@window || self, locators)
end
}
end
end | [
"def",
"has_many",
"(",
"*",
"elements",
")",
"elements",
".",
"each",
"do",
"|",
"element",
"|",
"class_name_plural",
"=",
"element",
".",
"to_s",
".",
"split",
"(",
"\"_\"",
")",
".",
"map",
"{",
"|",
"e",
"|",
"e",
".",
"capitalize",
"}",
".",
"join",
"class_name",
"=",
"class_name_plural",
".",
"chop",
"adapter_class",
"=",
"self",
".",
"to_s",
".",
"scan",
"(",
"/",
"/",
")",
".",
"flatten",
".",
"first",
"clazz",
"=",
"RAutomation",
".",
"constants",
".",
"include?",
"(",
"class_name",
")",
"?",
"RAutomation",
":",
"class_eval",
"(",
"adapter_class",
")",
"clazz",
".",
"class_eval",
"%Q{ class #{class_name_plural} include Enumerable def initialize(window, locators) if locators[:hwnd] || locators[:pid] raise UnsupportedLocatorException, \":hwnd or :pid in \" + locators.inspect + \" are not supported for #{adapter_class}::#{class_name_plural}\" end @window = window @locators = locators end def each i = -1 while true args = [@window, @locators.merge(:index => i += 1)].compact object = #{clazz}::#{class_name}.new(*args) break unless object.exists? yield object end end def method_missing(name, *args) ary = self.to_a ary.respond_to?(name) ? ary.send(name, *args) : super end end }",
"class_eval",
"%Q{ def #{element}(locators = {}) #{adapter_class}::#{class_name_plural}.new(@window || self, locators) end }",
"end",
"end"
]
| Creates collection classes and methods for elements.
@param [Array<Symbol>] elements for which to create collection classes
and methods. | [
"Creates",
"collection",
"classes",
"and",
"methods",
"for",
"elements",
"."
]
| 7314a7e6f8bbba797d276ca1950abde0cba6897a | https://github.com/jarmo/RAutomation/blob/7314a7e6f8bbba797d276ca1950abde0cba6897a/lib/rautomation/element_collections.rb#L10-L53 | train |
hicknhack-software/rails-disco | active_event/lib/active_event/event_source_server.rb | ActiveEvent.EventSourceServer.process_projection | def process_projection(data)
mutex.synchronize do
projection_status = status[data[:projection]]
projection_status.set_error data[:error], data[:backtrace]
projection_status.event = data[:event]
end
end | ruby | def process_projection(data)
mutex.synchronize do
projection_status = status[data[:projection]]
projection_status.set_error data[:error], data[:backtrace]
projection_status.event = data[:event]
end
end | [
"def",
"process_projection",
"(",
"data",
")",
"mutex",
".",
"synchronize",
"do",
"projection_status",
"=",
"status",
"[",
"data",
"[",
":projection",
"]",
"]",
"projection_status",
".",
"set_error",
"data",
"[",
":error",
"]",
",",
"data",
"[",
":backtrace",
"]",
"projection_status",
".",
"event",
"=",
"data",
"[",
":event",
"]",
"end",
"end"
]
| status of all projections received so far | [
"status",
"of",
"all",
"projections",
"received",
"so",
"far"
]
| 5d1f2801a41dc2a1c9f745499bd32c8f634dcc43 | https://github.com/hicknhack-software/rails-disco/blob/5d1f2801a41dc2a1c9f745499bd32c8f634dcc43/active_event/lib/active_event/event_source_server.rb#L94-L100 | train |
RallyTools/RallyRestToolkitForRuby | lib/rally_api/rally_rest_json.rb | RallyAPI.RallyRestJson.allowed_values | def allowed_values(type, field, workspace = nil)
rally_workspace_object(workspace)
type_def = get_typedef_for(type, workspace)
allowed_vals = {}
type_def["Attributes"].each do |attr|
next if attr["ElementName"] != field
attr["AllowedValues"].each do |val_ref|
val = val_ref["StringValue"]
val = "Null" if val.nil? || val.empty?
allowed_vals[val] = true
end
end
allowed_vals
end | ruby | def allowed_values(type, field, workspace = nil)
rally_workspace_object(workspace)
type_def = get_typedef_for(type, workspace)
allowed_vals = {}
type_def["Attributes"].each do |attr|
next if attr["ElementName"] != field
attr["AllowedValues"].each do |val_ref|
val = val_ref["StringValue"]
val = "Null" if val.nil? || val.empty?
allowed_vals[val] = true
end
end
allowed_vals
end | [
"def",
"allowed_values",
"(",
"type",
",",
"field",
",",
"workspace",
"=",
"nil",
")",
"rally_workspace_object",
"(",
"workspace",
")",
"type_def",
"=",
"get_typedef_for",
"(",
"type",
",",
"workspace",
")",
"allowed_vals",
"=",
"{",
"}",
"type_def",
"[",
"\"Attributes\"",
"]",
".",
"each",
"do",
"|",
"attr",
"|",
"next",
"if",
"attr",
"[",
"\"ElementName\"",
"]",
"!=",
"field",
"attr",
"[",
"\"AllowedValues\"",
"]",
".",
"each",
"do",
"|",
"val_ref",
"|",
"val",
"=",
"val_ref",
"[",
"\"StringValue\"",
"]",
"val",
"=",
"\"Null\"",
"if",
"val",
".",
"nil?",
"||",
"val",
".",
"empty?",
"allowed_vals",
"[",
"val",
"]",
"=",
"true",
"end",
"end",
"allowed_vals",
"end"
]
| todo - check support for portfolio item fields | [
"todo",
"-",
"check",
"support",
"for",
"portfolio",
"item",
"fields"
]
| a091616254c7a72e9a6f04f757026e5968312777 | https://github.com/RallyTools/RallyRestToolkitForRuby/blob/a091616254c7a72e9a6f04f757026e5968312777/lib/rally_api/rally_rest_json.rb#L357-L371 | train |
RallyTools/RallyRestToolkitForRuby | lib/rally_api/rally_rest_json.rb | RallyAPI.RallyRestJson.check_type | def check_type(type_name)
alias_name = @rally_alias_types[type_name.downcase.to_s]
return alias_name unless alias_name.nil?
return type_name
end | ruby | def check_type(type_name)
alias_name = @rally_alias_types[type_name.downcase.to_s]
return alias_name unless alias_name.nil?
return type_name
end | [
"def",
"check_type",
"(",
"type_name",
")",
"alias_name",
"=",
"@rally_alias_types",
"[",
"type_name",
".",
"downcase",
".",
"to_s",
"]",
"return",
"alias_name",
"unless",
"alias_name",
".",
"nil?",
"return",
"type_name",
"end"
]
| check for an alias of a type - eg userstory => hierarchicalrequirement
you can add to @rally_alias_types as desired | [
"check",
"for",
"an",
"alias",
"of",
"a",
"type",
"-",
"eg",
"userstory",
"=",
">",
"hierarchicalrequirement",
"you",
"can",
"add",
"to"
]
| a091616254c7a72e9a6f04f757026e5968312777 | https://github.com/RallyTools/RallyRestToolkitForRuby/blob/a091616254c7a72e9a6f04f757026e5968312777/lib/rally_api/rally_rest_json.rb#L431-L435 | train |
RallyTools/RallyRestToolkitForRuby | lib/rally_api/rally_rest_json.rb | RallyAPI.RallyRestJson.check_id | def check_id(type, idstring)
if idstring.class == Fixnum
return make_read_url(type, idstring)
end
if (idstring.class == String)
return idstring if idstring.index("http") == 0
return ref_by_formatted_id(type, idstring.split("|")[1]) if idstring.index("FormattedID") == 0
end
make_read_url(type, idstring)
end | ruby | def check_id(type, idstring)
if idstring.class == Fixnum
return make_read_url(type, idstring)
end
if (idstring.class == String)
return idstring if idstring.index("http") == 0
return ref_by_formatted_id(type, idstring.split("|")[1]) if idstring.index("FormattedID") == 0
end
make_read_url(type, idstring)
end | [
"def",
"check_id",
"(",
"type",
",",
"idstring",
")",
"if",
"idstring",
".",
"class",
"==",
"Fixnum",
"return",
"make_read_url",
"(",
"type",
",",
"idstring",
")",
"end",
"if",
"(",
"idstring",
".",
"class",
"==",
"String",
")",
"return",
"idstring",
"if",
"idstring",
".",
"index",
"(",
"\"http\"",
")",
"==",
"0",
"return",
"ref_by_formatted_id",
"(",
"type",
",",
"idstring",
".",
"split",
"(",
"\"|\"",
")",
"[",
"1",
"]",
")",
"if",
"idstring",
".",
"index",
"(",
"\"FormattedID\"",
")",
"==",
"0",
"end",
"make_read_url",
"(",
"type",
",",
"idstring",
")",
"end"
]
| expecting idstring to have "FormattedID|DE45" or the objectID or a ref itself | [
"expecting",
"idstring",
"to",
"have",
"FormattedID|DE45",
"or",
"the",
"objectID",
"or",
"a",
"ref",
"itself"
]
| a091616254c7a72e9a6f04f757026e5968312777 | https://github.com/RallyTools/RallyRestToolkitForRuby/blob/a091616254c7a72e9a6f04f757026e5968312777/lib/rally_api/rally_rest_json.rb#L451-L461 | train |
RallyTools/RallyRestToolkitForRuby | lib/rally_api/rally_object.rb | RallyAPI.RallyObject.method_missing | def method_missing(sym, *args)
ret_val = get_val(sym.to_s)
if ret_val.nil? && @rally_rest.rally_rest_api_compat
ret_val = get_val(camel_case_word(sym))
end
ret_val
end | ruby | def method_missing(sym, *args)
ret_val = get_val(sym.to_s)
if ret_val.nil? && @rally_rest.rally_rest_api_compat
ret_val = get_val(camel_case_word(sym))
end
ret_val
end | [
"def",
"method_missing",
"(",
"sym",
",",
"*",
"args",
")",
"ret_val",
"=",
"get_val",
"(",
"sym",
".",
"to_s",
")",
"if",
"ret_val",
".",
"nil?",
"&&",
"@rally_rest",
".",
"rally_rest_api_compat",
"ret_val",
"=",
"get_val",
"(",
"camel_case_word",
"(",
"sym",
")",
")",
"end",
"ret_val",
"end"
]
| An attempt to be rally_rest_api user friendly -
you can get a field the old way with an underscored field name or the upcase name | [
"An",
"attempt",
"to",
"be",
"rally_rest_api",
"user",
"friendly",
"-",
"you",
"can",
"get",
"a",
"field",
"the",
"old",
"way",
"with",
"an",
"underscored",
"field",
"name",
"or",
"the",
"upcase",
"name"
]
| a091616254c7a72e9a6f04f757026e5968312777 | https://github.com/RallyTools/RallyRestToolkitForRuby/blob/a091616254c7a72e9a6f04f757026e5968312777/lib/rally_api/rally_object.rb#L146-L152 | train |
arempe93/bunny-mock | lib/bunny_mock/channel.rb | BunnyMock.Channel.ack | def ack(delivery_tag, multiple = false)
if multiple
@acknowledged_state[:pending].keys.each do |key|
ack(key, false) if key <= delivery_tag
end
elsif @acknowledged_state[:pending].key?(delivery_tag)
update_acknowledgement_state(delivery_tag, :acked)
end
nil
end | ruby | def ack(delivery_tag, multiple = false)
if multiple
@acknowledged_state[:pending].keys.each do |key|
ack(key, false) if key <= delivery_tag
end
elsif @acknowledged_state[:pending].key?(delivery_tag)
update_acknowledgement_state(delivery_tag, :acked)
end
nil
end | [
"def",
"ack",
"(",
"delivery_tag",
",",
"multiple",
"=",
"false",
")",
"if",
"multiple",
"@acknowledged_state",
"[",
":pending",
"]",
".",
"keys",
".",
"each",
"do",
"|",
"key",
"|",
"ack",
"(",
"key",
",",
"false",
")",
"if",
"key",
"<=",
"delivery_tag",
"end",
"elsif",
"@acknowledged_state",
"[",
":pending",
"]",
".",
"key?",
"(",
"delivery_tag",
")",
"update_acknowledgement_state",
"(",
"delivery_tag",
",",
":acked",
")",
"end",
"nil",
"end"
]
| Acknowledge message.
@param [Integer] delivery_tag Delivery tag to acknowledge
@param [Boolean] multiple (false) Should all unacknowledged messages up to this be acknowleded as well?
@return nil
@api public | [
"Acknowledge",
"message",
"."
]
| 468fe867815bd86fde9797379964b7336d5bcfec | https://github.com/arempe93/bunny-mock/blob/468fe867815bd86fde9797379964b7336d5bcfec/lib/bunny_mock/channel.rb#L279-L288 | train |
arempe93/bunny-mock | lib/bunny_mock/channel.rb | BunnyMock.Channel.nack | def nack(delivery_tag, multiple = false, requeue = false)
if multiple
@acknowledged_state[:pending].keys.each do |key|
nack(key, false, requeue) if key <= delivery_tag
end
elsif @acknowledged_state[:pending].key?(delivery_tag)
delivery, header, body = update_acknowledgement_state(delivery_tag, :nacked)
delivery.queue.publish(body, header.to_hash) if requeue
end
nil
end | ruby | def nack(delivery_tag, multiple = false, requeue = false)
if multiple
@acknowledged_state[:pending].keys.each do |key|
nack(key, false, requeue) if key <= delivery_tag
end
elsif @acknowledged_state[:pending].key?(delivery_tag)
delivery, header, body = update_acknowledgement_state(delivery_tag, :nacked)
delivery.queue.publish(body, header.to_hash) if requeue
end
nil
end | [
"def",
"nack",
"(",
"delivery_tag",
",",
"multiple",
"=",
"false",
",",
"requeue",
"=",
"false",
")",
"if",
"multiple",
"@acknowledged_state",
"[",
":pending",
"]",
".",
"keys",
".",
"each",
"do",
"|",
"key",
"|",
"nack",
"(",
"key",
",",
"false",
",",
"requeue",
")",
"if",
"key",
"<=",
"delivery_tag",
"end",
"elsif",
"@acknowledged_state",
"[",
":pending",
"]",
".",
"key?",
"(",
"delivery_tag",
")",
"delivery",
",",
"header",
",",
"body",
"=",
"update_acknowledgement_state",
"(",
"delivery_tag",
",",
":nacked",
")",
"delivery",
".",
"queue",
".",
"publish",
"(",
"body",
",",
"header",
".",
"to_hash",
")",
"if",
"requeue",
"end",
"nil",
"end"
]
| Unacknowledge message.
@param [Integer] delivery_tag Delivery tag to acknowledge
@param [Boolean] multiple (false) Should all unacknowledged messages up to this be rejected as well?
@param [Boolean] requeue (false) Should this message be requeued instead of dropping it?
@return nil
@api public | [
"Unacknowledge",
"message",
"."
]
| 468fe867815bd86fde9797379964b7336d5bcfec | https://github.com/arempe93/bunny-mock/blob/468fe867815bd86fde9797379964b7336d5bcfec/lib/bunny_mock/channel.rb#L301-L311 | train |
arempe93/bunny-mock | lib/bunny_mock/channel.rb | BunnyMock.Channel.reject | def reject(delivery_tag, requeue = false)
if @acknowledged_state[:pending].key?(delivery_tag)
delivery, header, body = update_acknowledgement_state(delivery_tag, :rejected)
delivery.queue.publish(body, header.to_hash) if requeue
end
nil
end | ruby | def reject(delivery_tag, requeue = false)
if @acknowledged_state[:pending].key?(delivery_tag)
delivery, header, body = update_acknowledgement_state(delivery_tag, :rejected)
delivery.queue.publish(body, header.to_hash) if requeue
end
nil
end | [
"def",
"reject",
"(",
"delivery_tag",
",",
"requeue",
"=",
"false",
")",
"if",
"@acknowledged_state",
"[",
":pending",
"]",
".",
"key?",
"(",
"delivery_tag",
")",
"delivery",
",",
"header",
",",
"body",
"=",
"update_acknowledgement_state",
"(",
"delivery_tag",
",",
":rejected",
")",
"delivery",
".",
"queue",
".",
"publish",
"(",
"body",
",",
"header",
".",
"to_hash",
")",
"if",
"requeue",
"end",
"nil",
"end"
]
| Rejects a message. A rejected message can be requeued or
dropped by RabbitMQ.
@param [Integer] delivery_tag Delivery tag to reject
@param [Boolean] requeue Should this message be requeued instead of dropping it?
@return nil
@api public | [
"Rejects",
"a",
"message",
".",
"A",
"rejected",
"message",
"can",
"be",
"requeued",
"or",
"dropped",
"by",
"RabbitMQ",
"."
]
| 468fe867815bd86fde9797379964b7336d5bcfec | https://github.com/arempe93/bunny-mock/blob/468fe867815bd86fde9797379964b7336d5bcfec/lib/bunny_mock/channel.rb#L323-L329 | train |
arempe93/bunny-mock | lib/bunny_mock/queue.rb | BunnyMock.Queue.bind | def bind(exchange, opts = {})
check_queue_deleted!
if exchange.respond_to?(:add_route)
# we can do the binding ourselves
exchange.add_route opts.fetch(:routing_key, @name), self
else
# we need the channel to lookup the exchange
@channel.queue_bind self, opts.fetch(:routing_key, @name), exchange
end
self
end | ruby | def bind(exchange, opts = {})
check_queue_deleted!
if exchange.respond_to?(:add_route)
# we can do the binding ourselves
exchange.add_route opts.fetch(:routing_key, @name), self
else
# we need the channel to lookup the exchange
@channel.queue_bind self, opts.fetch(:routing_key, @name), exchange
end
self
end | [
"def",
"bind",
"(",
"exchange",
",",
"opts",
"=",
"{",
"}",
")",
"check_queue_deleted!",
"if",
"exchange",
".",
"respond_to?",
"(",
":add_route",
")",
"exchange",
".",
"add_route",
"opts",
".",
"fetch",
"(",
":routing_key",
",",
"@name",
")",
",",
"self",
"else",
"@channel",
".",
"queue_bind",
"self",
",",
"opts",
".",
"fetch",
"(",
":routing_key",
",",
"@name",
")",
",",
"exchange",
"end",
"self",
"end"
]
| Bind this queue to an exchange
@param [BunnyMock::Exchange,String] exchange Exchange to bind to
@param [Hash] opts Binding properties
@option opts [String] :routing_key Custom routing key
@api public | [
"Bind",
"this",
"queue",
"to",
"an",
"exchange"
]
| 468fe867815bd86fde9797379964b7336d5bcfec | https://github.com/arempe93/bunny-mock/blob/468fe867815bd86fde9797379964b7336d5bcfec/lib/bunny_mock/queue.rb#L118-L131 | train |
arempe93/bunny-mock | lib/bunny_mock/queue.rb | BunnyMock.Queue.unbind | def unbind(exchange, opts = {})
check_queue_deleted!
if exchange.respond_to?(:remove_route)
# we can do the unbinding ourselves
exchange.remove_route opts.fetch(:routing_key, @name), self
else
# we need the channel to lookup the exchange
@channel.queue_unbind self, opts.fetch(:routing_key, @name), exchange
end
end | ruby | def unbind(exchange, opts = {})
check_queue_deleted!
if exchange.respond_to?(:remove_route)
# we can do the unbinding ourselves
exchange.remove_route opts.fetch(:routing_key, @name), self
else
# we need the channel to lookup the exchange
@channel.queue_unbind self, opts.fetch(:routing_key, @name), exchange
end
end | [
"def",
"unbind",
"(",
"exchange",
",",
"opts",
"=",
"{",
"}",
")",
"check_queue_deleted!",
"if",
"exchange",
".",
"respond_to?",
"(",
":remove_route",
")",
"exchange",
".",
"remove_route",
"opts",
".",
"fetch",
"(",
":routing_key",
",",
"@name",
")",
",",
"self",
"else",
"@channel",
".",
"queue_unbind",
"self",
",",
"opts",
".",
"fetch",
"(",
":routing_key",
",",
"@name",
")",
",",
"exchange",
"end",
"end"
]
| Unbind this queue from an exchange
@param [BunnyMock::Exchange,String] exchange Exchange to unbind from
@param [Hash] opts Binding properties
@option opts [String] :routing_key Custom routing key
@api public | [
"Unbind",
"this",
"queue",
"from",
"an",
"exchange"
]
| 468fe867815bd86fde9797379964b7336d5bcfec | https://github.com/arempe93/bunny-mock/blob/468fe867815bd86fde9797379964b7336d5bcfec/lib/bunny_mock/queue.rb#L143-L155 | train |
arempe93/bunny-mock | lib/bunny_mock/queue.rb | BunnyMock.Queue.pop | def pop(opts = { manual_ack: false }, &block)
if BunnyMock.use_bunny_queue_pop_api
bunny_pop(opts, &block)
else
warn '[DEPRECATED] This behavior is deprecated - please set `BunnyMock::use_bunny_queue_pop_api` to true to use Bunny Queue#pop behavior'
@messages.shift
end
end | ruby | def pop(opts = { manual_ack: false }, &block)
if BunnyMock.use_bunny_queue_pop_api
bunny_pop(opts, &block)
else
warn '[DEPRECATED] This behavior is deprecated - please set `BunnyMock::use_bunny_queue_pop_api` to true to use Bunny Queue#pop behavior'
@messages.shift
end
end | [
"def",
"pop",
"(",
"opts",
"=",
"{",
"manual_ack",
":",
"false",
"}",
",",
"&",
"block",
")",
"if",
"BunnyMock",
".",
"use_bunny_queue_pop_api",
"bunny_pop",
"(",
"opts",
",",
"&",
"block",
")",
"else",
"warn",
"'[DEPRECATED] This behavior is deprecated - please set `BunnyMock::use_bunny_queue_pop_api` to true to use Bunny Queue#pop behavior'",
"@messages",
".",
"shift",
"end",
"end"
]
| Get oldest message in queue
@return [Hash] Message data
@api public | [
"Get",
"oldest",
"message",
"in",
"queue"
]
| 468fe867815bd86fde9797379964b7336d5bcfec | https://github.com/arempe93/bunny-mock/blob/468fe867815bd86fde9797379964b7336d5bcfec/lib/bunny_mock/queue.rb#L198-L205 | train |
arempe93/bunny-mock | lib/bunny_mock/exchange.rb | BunnyMock.Exchange.bind | def bind(exchange, opts = {})
if exchange.respond_to?(:add_route)
# we can do the binding ourselves
exchange.add_route opts.fetch(:routing_key, @name), self
else
# we need the channel to look up the exchange
@channel.xchg_bind self, opts.fetch(:routing_key, @name), exchange
end
self
end | ruby | def bind(exchange, opts = {})
if exchange.respond_to?(:add_route)
# we can do the binding ourselves
exchange.add_route opts.fetch(:routing_key, @name), self
else
# we need the channel to look up the exchange
@channel.xchg_bind self, opts.fetch(:routing_key, @name), exchange
end
self
end | [
"def",
"bind",
"(",
"exchange",
",",
"opts",
"=",
"{",
"}",
")",
"if",
"exchange",
".",
"respond_to?",
"(",
":add_route",
")",
"exchange",
".",
"add_route",
"opts",
".",
"fetch",
"(",
":routing_key",
",",
"@name",
")",
",",
"self",
"else",
"@channel",
".",
"xchg_bind",
"self",
",",
"opts",
".",
"fetch",
"(",
":routing_key",
",",
"@name",
")",
",",
"exchange",
"end",
"self",
"end"
]
| Bind this exchange to another exchange
@param [BunnyMock::Exchange,String] exchange Exchange to bind to
@param [Hash] opts Binding properties
@option opts [String] :routing_key Custom routing key
@return [BunnyMock::Exchange] self
@api public | [
"Bind",
"this",
"exchange",
"to",
"another",
"exchange"
]
| 468fe867815bd86fde9797379964b7336d5bcfec | https://github.com/arempe93/bunny-mock/blob/468fe867815bd86fde9797379964b7336d5bcfec/lib/bunny_mock/exchange.rb#L144-L156 | train |
arempe93/bunny-mock | lib/bunny_mock/exchange.rb | BunnyMock.Exchange.unbind | def unbind(exchange, opts = {})
if exchange.respond_to?(:remove_route)
# we can do the unbinding ourselves
exchange.remove_route opts.fetch(:routing_key, @name), self
else
# we need the channel to look up the exchange
@channel.xchg_unbind opts.fetch(:routing_key, @name), exchange, self
end
self
end | ruby | def unbind(exchange, opts = {})
if exchange.respond_to?(:remove_route)
# we can do the unbinding ourselves
exchange.remove_route opts.fetch(:routing_key, @name), self
else
# we need the channel to look up the exchange
@channel.xchg_unbind opts.fetch(:routing_key, @name), exchange, self
end
self
end | [
"def",
"unbind",
"(",
"exchange",
",",
"opts",
"=",
"{",
"}",
")",
"if",
"exchange",
".",
"respond_to?",
"(",
":remove_route",
")",
"exchange",
".",
"remove_route",
"opts",
".",
"fetch",
"(",
":routing_key",
",",
"@name",
")",
",",
"self",
"else",
"@channel",
".",
"xchg_unbind",
"opts",
".",
"fetch",
"(",
":routing_key",
",",
"@name",
")",
",",
"exchange",
",",
"self",
"end",
"self",
"end"
]
| Unbind this exchange from another exchange
@param [BunnyMock::Exchange,String] exchange Exchange to unbind from
@param [Hash] opts Binding properties
@option opts [String] :routing_key Custom routing key
@return [BunnyMock::Exchange] self
@api public | [
"Unbind",
"this",
"exchange",
"from",
"another",
"exchange"
]
| 468fe867815bd86fde9797379964b7336d5bcfec | https://github.com/arempe93/bunny-mock/blob/468fe867815bd86fde9797379964b7336d5bcfec/lib/bunny_mock/exchange.rb#L169-L179 | train |
arempe93/bunny-mock | lib/bunny_mock/exchange.rb | BunnyMock.Exchange.routes_to? | def routes_to?(exchange_or_queue, opts = {})
route = exchange_or_queue.respond_to?(:name) ? exchange_or_queue.name : exchange_or_queue
rk = opts.fetch(:routing_key, route)
@routes.key?(rk) && @routes[rk].any? { |r| r == exchange_or_queue }
end | ruby | def routes_to?(exchange_or_queue, opts = {})
route = exchange_or_queue.respond_to?(:name) ? exchange_or_queue.name : exchange_or_queue
rk = opts.fetch(:routing_key, route)
@routes.key?(rk) && @routes[rk].any? { |r| r == exchange_or_queue }
end | [
"def",
"routes_to?",
"(",
"exchange_or_queue",
",",
"opts",
"=",
"{",
"}",
")",
"route",
"=",
"exchange_or_queue",
".",
"respond_to?",
"(",
":name",
")",
"?",
"exchange_or_queue",
".",
"name",
":",
"exchange_or_queue",
"rk",
"=",
"opts",
".",
"fetch",
"(",
":routing_key",
",",
"route",
")",
"@routes",
".",
"key?",
"(",
"rk",
")",
"&&",
"@routes",
"[",
"rk",
"]",
".",
"any?",
"{",
"|",
"r",
"|",
"r",
"==",
"exchange_or_queue",
"}",
"end"
]
| Check if a queue is bound to this exchange
@param [BunnyMock::Queue,String] exchange_or_queue Exchange or queue to check
@param [Hash] opts Binding properties
@option opts [String] :routing_key Custom routing key
@return [Boolean] true if the given queue or exchange matching options is bound to this exchange, false otherwise
@api public | [
"Check",
"if",
"a",
"queue",
"is",
"bound",
"to",
"this",
"exchange"
]
| 468fe867815bd86fde9797379964b7336d5bcfec | https://github.com/arempe93/bunny-mock/blob/468fe867815bd86fde9797379964b7336d5bcfec/lib/bunny_mock/exchange.rb#L216-L220 | train |
piotrmurach/tty-cursor | lib/tty/cursor.rb | TTY.Cursor.move | def move(x, y)
(x < 0 ? backward(-x) : (x > 0 ? forward(x) : '')) +
(y < 0 ? down(-y) : (y > 0 ? up(y) : ''))
end | ruby | def move(x, y)
(x < 0 ? backward(-x) : (x > 0 ? forward(x) : '')) +
(y < 0 ? down(-y) : (y > 0 ? up(y) : ''))
end | [
"def",
"move",
"(",
"x",
",",
"y",
")",
"(",
"x",
"<",
"0",
"?",
"backward",
"(",
"-",
"x",
")",
":",
"(",
"x",
">",
"0",
"?",
"forward",
"(",
"x",
")",
":",
"''",
")",
")",
"+",
"(",
"y",
"<",
"0",
"?",
"down",
"(",
"-",
"y",
")",
":",
"(",
"y",
">",
"0",
"?",
"up",
"(",
"y",
")",
":",
"''",
")",
")",
"end"
]
| Move cursor relative to its current position
@param [Integer] x
@param [Integer] y
@api public | [
"Move",
"cursor",
"relative",
"to",
"its",
"current",
"position"
]
| eed06fea403ed6d7400ea048435e463cfa538aed | https://github.com/piotrmurach/tty-cursor/blob/eed06fea403ed6d7400ea048435e463cfa538aed/lib/tty/cursor.rb#L70-L73 | train |
piotrmurach/tty-cursor | lib/tty/cursor.rb | TTY.Cursor.clear_lines | def clear_lines(n, direction = :up)
n.times.reduce([]) do |acc, i|
dir = direction == :up ? up : down
acc << clear_line + ((i == n - 1) ? '' : dir)
end.join
end | ruby | def clear_lines(n, direction = :up)
n.times.reduce([]) do |acc, i|
dir = direction == :up ? up : down
acc << clear_line + ((i == n - 1) ? '' : dir)
end.join
end | [
"def",
"clear_lines",
"(",
"n",
",",
"direction",
"=",
":up",
")",
"n",
".",
"times",
".",
"reduce",
"(",
"[",
"]",
")",
"do",
"|",
"acc",
",",
"i",
"|",
"dir",
"=",
"direction",
"==",
":up",
"?",
"up",
":",
"down",
"acc",
"<<",
"clear_line",
"+",
"(",
"(",
"i",
"==",
"n",
"-",
"1",
")",
"?",
"''",
":",
"dir",
")",
"end",
".",
"join",
"end"
]
| Clear a number of lines
@param [Integer] n
the number of lines to clear
@param [Symbol] :direction
the direction to clear, default :up
@api public | [
"Clear",
"a",
"number",
"of",
"lines"
]
| eed06fea403ed6d7400ea048435e463cfa538aed | https://github.com/piotrmurach/tty-cursor/blob/eed06fea403ed6d7400ea048435e463cfa538aed/lib/tty/cursor.rb#L169-L174 | train |
iyuuya/jkf | lib/jkf/parser/kif.rb | Jkf::Parser.Kif.transform_move | def transform_move(line, c)
ret = {}
ret["comments"] = c if !c.empty?
if line["move"].is_a? Hash
ret["move"] = line["move"]
else
ret["special"] = special2csa(line["move"])
end
ret["time"] = line["time"] if line["time"]
ret
end | ruby | def transform_move(line, c)
ret = {}
ret["comments"] = c if !c.empty?
if line["move"].is_a? Hash
ret["move"] = line["move"]
else
ret["special"] = special2csa(line["move"])
end
ret["time"] = line["time"] if line["time"]
ret
end | [
"def",
"transform_move",
"(",
"line",
",",
"c",
")",
"ret",
"=",
"{",
"}",
"ret",
"[",
"\"comments\"",
"]",
"=",
"c",
"if",
"!",
"c",
".",
"empty?",
"if",
"line",
"[",
"\"move\"",
"]",
".",
"is_a?",
"Hash",
"ret",
"[",
"\"move\"",
"]",
"=",
"line",
"[",
"\"move\"",
"]",
"else",
"ret",
"[",
"\"special\"",
"]",
"=",
"special2csa",
"(",
"line",
"[",
"\"move\"",
"]",
")",
"end",
"ret",
"[",
"\"time\"",
"]",
"=",
"line",
"[",
"\"time\"",
"]",
"if",
"line",
"[",
"\"time\"",
"]",
"ret",
"end"
]
| transform move to jkf | [
"transform",
"move",
"to",
"jkf"
]
| 4fd229c50737cab7b41281238880f1414e55e061 | https://github.com/iyuuya/jkf/blob/4fd229c50737cab7b41281238880f1414e55e061/lib/jkf/parser/kif.rb#L567-L577 | train |
iyuuya/jkf | lib/jkf/parser/kif.rb | Jkf::Parser.Kif.transform_teban_fugou_from | def transform_teban_fugou_from(teban, fugou, from)
ret = { "color" => teban2color(teban.join), "piece" => fugou["piece"] }
if fugou["to"]
ret["to"] = fugou["to"]
else
ret["same"] = true
end
ret["promote"] = true if fugou["promote"]
ret["from"] = from if from
ret
end | ruby | def transform_teban_fugou_from(teban, fugou, from)
ret = { "color" => teban2color(teban.join), "piece" => fugou["piece"] }
if fugou["to"]
ret["to"] = fugou["to"]
else
ret["same"] = true
end
ret["promote"] = true if fugou["promote"]
ret["from"] = from if from
ret
end | [
"def",
"transform_teban_fugou_from",
"(",
"teban",
",",
"fugou",
",",
"from",
")",
"ret",
"=",
"{",
"\"color\"",
"=>",
"teban2color",
"(",
"teban",
".",
"join",
")",
",",
"\"piece\"",
"=>",
"fugou",
"[",
"\"piece\"",
"]",
"}",
"if",
"fugou",
"[",
"\"to\"",
"]",
"ret",
"[",
"\"to\"",
"]",
"=",
"fugou",
"[",
"\"to\"",
"]",
"else",
"ret",
"[",
"\"same\"",
"]",
"=",
"true",
"end",
"ret",
"[",
"\"promote\"",
"]",
"=",
"true",
"if",
"fugou",
"[",
"\"promote\"",
"]",
"ret",
"[",
"\"from\"",
"]",
"=",
"from",
"if",
"from",
"ret",
"end"
]
| transform teban-fugou-from to jkf | [
"transform",
"teban",
"-",
"fugou",
"-",
"from",
"to",
"jkf"
]
| 4fd229c50737cab7b41281238880f1414e55e061 | https://github.com/iyuuya/jkf/blob/4fd229c50737cab7b41281238880f1414e55e061/lib/jkf/parser/kif.rb#L580-L590 | train |
iyuuya/jkf | lib/jkf/parser/kif.rb | Jkf::Parser.Kif.reverse_color | def reverse_color(moves)
moves.each do |move|
if move["move"] && move["move"]["color"]
move["move"]["color"] = (move["move"]["color"] + 1) % 2
end
move["forks"].each { |_fork| reverse_color(_fork) } if move["forks"]
end
end | ruby | def reverse_color(moves)
moves.each do |move|
if move["move"] && move["move"]["color"]
move["move"]["color"] = (move["move"]["color"] + 1) % 2
end
move["forks"].each { |_fork| reverse_color(_fork) } if move["forks"]
end
end | [
"def",
"reverse_color",
"(",
"moves",
")",
"moves",
".",
"each",
"do",
"|",
"move",
"|",
"if",
"move",
"[",
"\"move\"",
"]",
"&&",
"move",
"[",
"\"move\"",
"]",
"[",
"\"color\"",
"]",
"move",
"[",
"\"move\"",
"]",
"[",
"\"color\"",
"]",
"=",
"(",
"move",
"[",
"\"move\"",
"]",
"[",
"\"color\"",
"]",
"+",
"1",
")",
"%",
"2",
"end",
"move",
"[",
"\"forks\"",
"]",
".",
"each",
"{",
"|",
"_fork",
"|",
"reverse_color",
"(",
"_fork",
")",
"}",
"if",
"move",
"[",
"\"forks\"",
"]",
"end",
"end"
]
| exchange sente gote | [
"exchange",
"sente",
"gote"
]
| 4fd229c50737cab7b41281238880f1414e55e061 | https://github.com/iyuuya/jkf/blob/4fd229c50737cab7b41281238880f1414e55e061/lib/jkf/parser/kif.rb#L628-L635 | train |
iyuuya/jkf | lib/jkf/parser/ki2.rb | Jkf::Parser.Ki2.transform_fugou | def transform_fugou(pl, pi, sou, dou, pro, da)
ret = { "piece" => pi }
if pl["same"]
ret["same"] = true
else
ret["to"] = pl
end
ret["promote"] = (pro == "成") if pro
if da
ret["relative"] = "H"
else
rel = soutai2relative(sou) + dousa2relative(dou)
ret["relative"] = rel unless rel.empty?
end
ret
end | ruby | def transform_fugou(pl, pi, sou, dou, pro, da)
ret = { "piece" => pi }
if pl["same"]
ret["same"] = true
else
ret["to"] = pl
end
ret["promote"] = (pro == "成") if pro
if da
ret["relative"] = "H"
else
rel = soutai2relative(sou) + dousa2relative(dou)
ret["relative"] = rel unless rel.empty?
end
ret
end | [
"def",
"transform_fugou",
"(",
"pl",
",",
"pi",
",",
"sou",
",",
"dou",
",",
"pro",
",",
"da",
")",
"ret",
"=",
"{",
"\"piece\"",
"=>",
"pi",
"}",
"if",
"pl",
"[",
"\"same\"",
"]",
"ret",
"[",
"\"same\"",
"]",
"=",
"true",
"else",
"ret",
"[",
"\"to\"",
"]",
"=",
"pl",
"end",
"ret",
"[",
"\"promote\"",
"]",
"=",
"(",
"pro",
"==",
"\"成\") ",
"i",
" p",
"o",
"if",
"da",
"ret",
"[",
"\"relative\"",
"]",
"=",
"\"H\"",
"else",
"rel",
"=",
"soutai2relative",
"(",
"sou",
")",
"+",
"dousa2relative",
"(",
"dou",
")",
"ret",
"[",
"\"relative\"",
"]",
"=",
"rel",
"unless",
"rel",
".",
"empty?",
"end",
"ret",
"end"
]
| transfrom fugou to jkf | [
"transfrom",
"fugou",
"to",
"jkf"
]
| 4fd229c50737cab7b41281238880f1414e55e061 | https://github.com/iyuuya/jkf/blob/4fd229c50737cab7b41281238880f1414e55e061/lib/jkf/parser/ki2.rb#L373-L388 | train |
iyuuya/jkf | lib/jkf/parser/base.rb | Jkf::Parser.Base.match_spaces | def match_spaces
stack = []
matched = match_space
while matched != :failed
stack << matched
matched = match_space
end
stack
end | ruby | def match_spaces
stack = []
matched = match_space
while matched != :failed
stack << matched
matched = match_space
end
stack
end | [
"def",
"match_spaces",
"stack",
"=",
"[",
"]",
"matched",
"=",
"match_space",
"while",
"matched",
"!=",
":failed",
"stack",
"<<",
"matched",
"matched",
"=",
"match_space",
"end",
"stack",
"end"
]
| match space one or more | [
"match",
"space",
"one",
"or",
"more"
]
| 4fd229c50737cab7b41281238880f1414e55e061 | https://github.com/iyuuya/jkf/blob/4fd229c50737cab7b41281238880f1414e55e061/lib/jkf/parser/base.rb#L70-L78 | train |
iyuuya/jkf | lib/jkf/parser/kifuable.rb | Jkf::Parser.Kifuable.transform_root_forks | def transform_root_forks(forks, moves)
fork_stack = [{ "te" => 0, "moves" => moves }]
forks.each do |f|
now_fork = f
_fork = fork_stack.pop
_fork = fork_stack.pop while _fork["te"] > now_fork["te"]
move = _fork["moves"][now_fork["te"] - _fork["te"]]
move["forks"] ||= []
move["forks"] << now_fork["moves"]
fork_stack << _fork
fork_stack << now_fork
end
end | ruby | def transform_root_forks(forks, moves)
fork_stack = [{ "te" => 0, "moves" => moves }]
forks.each do |f|
now_fork = f
_fork = fork_stack.pop
_fork = fork_stack.pop while _fork["te"] > now_fork["te"]
move = _fork["moves"][now_fork["te"] - _fork["te"]]
move["forks"] ||= []
move["forks"] << now_fork["moves"]
fork_stack << _fork
fork_stack << now_fork
end
end | [
"def",
"transform_root_forks",
"(",
"forks",
",",
"moves",
")",
"fork_stack",
"=",
"[",
"{",
"\"te\"",
"=>",
"0",
",",
"\"moves\"",
"=>",
"moves",
"}",
"]",
"forks",
".",
"each",
"do",
"|",
"f",
"|",
"now_fork",
"=",
"f",
"_fork",
"=",
"fork_stack",
".",
"pop",
"_fork",
"=",
"fork_stack",
".",
"pop",
"while",
"_fork",
"[",
"\"te\"",
"]",
">",
"now_fork",
"[",
"\"te\"",
"]",
"move",
"=",
"_fork",
"[",
"\"moves\"",
"]",
"[",
"now_fork",
"[",
"\"te\"",
"]",
"-",
"_fork",
"[",
"\"te\"",
"]",
"]",
"move",
"[",
"\"forks\"",
"]",
"||=",
"[",
"]",
"move",
"[",
"\"forks\"",
"]",
"<<",
"now_fork",
"[",
"\"moves\"",
"]",
"fork_stack",
"<<",
"_fork",
"fork_stack",
"<<",
"now_fork",
"end",
"end"
]
| transfrom forks to jkf | [
"transfrom",
"forks",
"to",
"jkf"
]
| 4fd229c50737cab7b41281238880f1414e55e061 | https://github.com/iyuuya/jkf/blob/4fd229c50737cab7b41281238880f1414e55e061/lib/jkf/parser/kifuable.rb#L545-L557 | train |
iyuuya/jkf | lib/jkf/parser/kifuable.rb | Jkf::Parser.Kifuable.transform_initialboard | def transform_initialboard(lines)
board = []
9.times do |i|
line = []
9.times do |j|
line << lines[j][8 - i]
end
board << line
end
{ "preset" => "OTHER", "data" => { "board" => board } }
end | ruby | def transform_initialboard(lines)
board = []
9.times do |i|
line = []
9.times do |j|
line << lines[j][8 - i]
end
board << line
end
{ "preset" => "OTHER", "data" => { "board" => board } }
end | [
"def",
"transform_initialboard",
"(",
"lines",
")",
"board",
"=",
"[",
"]",
"9",
".",
"times",
"do",
"|",
"i",
"|",
"line",
"=",
"[",
"]",
"9",
".",
"times",
"do",
"|",
"j",
"|",
"line",
"<<",
"lines",
"[",
"j",
"]",
"[",
"8",
"-",
"i",
"]",
"end",
"board",
"<<",
"line",
"end",
"{",
"\"preset\"",
"=>",
"\"OTHER\"",
",",
"\"data\"",
"=>",
"{",
"\"board\"",
"=>",
"board",
"}",
"}",
"end"
]
| transform initialboard to jkf | [
"transform",
"initialboard",
"to",
"jkf"
]
| 4fd229c50737cab7b41281238880f1414e55e061 | https://github.com/iyuuya/jkf/blob/4fd229c50737cab7b41281238880f1414e55e061/lib/jkf/parser/kifuable.rb#L560-L570 | train |
iyuuya/jkf | lib/jkf/parser/csa.rb | Jkf::Parser.Csa.transform_komabetsu_lines | def transform_komabetsu_lines(lines)
board = generate_empty_board
hands = [
{ "FU" => 0, "KY" => 0, "KE" => 0, "GI" => 0, "KI" => 0, "KA" => 0, "HI" => 0 },
{ "FU" => 0, "KY" => 0, "KE" => 0, "GI" => 0, "KI" => 0, "KA" => 0, "HI" => 0 }
]
all = { "FU" => 18, "KY" => 4, "KE" => 4, "GI" => 4, "KI" => 4, "KA" => 2, "HI" => 2 }
lines.each do |line|
line["pieces"].each do |piece|
xy = piece["xy"]
if xy["x"] == 0
if piece["piece"] == "AL"
hands[line["teban"]] = all
return { "preset" => "OTHER", "data" => { "board" => board, "hands" => hands } }
end
obj = hands[line["teban"]]
obj[piece["piece"]] += 1
else
board[xy["x"] - 1][xy["y"] - 1] = { "color" => line["teban"],
"kind" => piece["piece"] }
end
all[piece["piece"]] -= 1 if piece["piece"] != "OU"
end
end
{ "preset" => "OTHER", "data" => { "board" => board, "hands" => hands } }
end | ruby | def transform_komabetsu_lines(lines)
board = generate_empty_board
hands = [
{ "FU" => 0, "KY" => 0, "KE" => 0, "GI" => 0, "KI" => 0, "KA" => 0, "HI" => 0 },
{ "FU" => 0, "KY" => 0, "KE" => 0, "GI" => 0, "KI" => 0, "KA" => 0, "HI" => 0 }
]
all = { "FU" => 18, "KY" => 4, "KE" => 4, "GI" => 4, "KI" => 4, "KA" => 2, "HI" => 2 }
lines.each do |line|
line["pieces"].each do |piece|
xy = piece["xy"]
if xy["x"] == 0
if piece["piece"] == "AL"
hands[line["teban"]] = all
return { "preset" => "OTHER", "data" => { "board" => board, "hands" => hands } }
end
obj = hands[line["teban"]]
obj[piece["piece"]] += 1
else
board[xy["x"] - 1][xy["y"] - 1] = { "color" => line["teban"],
"kind" => piece["piece"] }
end
all[piece["piece"]] -= 1 if piece["piece"] != "OU"
end
end
{ "preset" => "OTHER", "data" => { "board" => board, "hands" => hands } }
end | [
"def",
"transform_komabetsu_lines",
"(",
"lines",
")",
"board",
"=",
"generate_empty_board",
"hands",
"=",
"[",
"{",
"\"FU\"",
"=>",
"0",
",",
"\"KY\"",
"=>",
"0",
",",
"\"KE\"",
"=>",
"0",
",",
"\"GI\"",
"=>",
"0",
",",
"\"KI\"",
"=>",
"0",
",",
"\"KA\"",
"=>",
"0",
",",
"\"HI\"",
"=>",
"0",
"}",
",",
"{",
"\"FU\"",
"=>",
"0",
",",
"\"KY\"",
"=>",
"0",
",",
"\"KE\"",
"=>",
"0",
",",
"\"GI\"",
"=>",
"0",
",",
"\"KI\"",
"=>",
"0",
",",
"\"KA\"",
"=>",
"0",
",",
"\"HI\"",
"=>",
"0",
"}",
"]",
"all",
"=",
"{",
"\"FU\"",
"=>",
"18",
",",
"\"KY\"",
"=>",
"4",
",",
"\"KE\"",
"=>",
"4",
",",
"\"GI\"",
"=>",
"4",
",",
"\"KI\"",
"=>",
"4",
",",
"\"KA\"",
"=>",
"2",
",",
"\"HI\"",
"=>",
"2",
"}",
"lines",
".",
"each",
"do",
"|",
"line",
"|",
"line",
"[",
"\"pieces\"",
"]",
".",
"each",
"do",
"|",
"piece",
"|",
"xy",
"=",
"piece",
"[",
"\"xy\"",
"]",
"if",
"xy",
"[",
"\"x\"",
"]",
"==",
"0",
"if",
"piece",
"[",
"\"piece\"",
"]",
"==",
"\"AL\"",
"hands",
"[",
"line",
"[",
"\"teban\"",
"]",
"]",
"=",
"all",
"return",
"{",
"\"preset\"",
"=>",
"\"OTHER\"",
",",
"\"data\"",
"=>",
"{",
"\"board\"",
"=>",
"board",
",",
"\"hands\"",
"=>",
"hands",
"}",
"}",
"end",
"obj",
"=",
"hands",
"[",
"line",
"[",
"\"teban\"",
"]",
"]",
"obj",
"[",
"piece",
"[",
"\"piece\"",
"]",
"]",
"+=",
"1",
"else",
"board",
"[",
"xy",
"[",
"\"x\"",
"]",
"-",
"1",
"]",
"[",
"xy",
"[",
"\"y\"",
"]",
"-",
"1",
"]",
"=",
"{",
"\"color\"",
"=>",
"line",
"[",
"\"teban\"",
"]",
",",
"\"kind\"",
"=>",
"piece",
"[",
"\"piece\"",
"]",
"}",
"end",
"all",
"[",
"piece",
"[",
"\"piece\"",
"]",
"]",
"-=",
"1",
"if",
"piece",
"[",
"\"piece\"",
"]",
"!=",
"\"OU\"",
"end",
"end",
"{",
"\"preset\"",
"=>",
"\"OTHER\"",
",",
"\"data\"",
"=>",
"{",
"\"board\"",
"=>",
"board",
",",
"\"hands\"",
"=>",
"hands",
"}",
"}",
"end"
]
| lines to jkf | [
"lines",
"to",
"jkf"
]
| 4fd229c50737cab7b41281238880f1414e55e061 | https://github.com/iyuuya/jkf/blob/4fd229c50737cab7b41281238880f1414e55e061/lib/jkf/parser/csa.rb#L743-L770 | train |
iyuuya/jkf | lib/jkf/parser/csa.rb | Jkf::Parser.Csa.generate_empty_board | def generate_empty_board
board = []
9.times do |_i|
line = []
9.times do |_j|
line << {}
end
board << line
end
board
end | ruby | def generate_empty_board
board = []
9.times do |_i|
line = []
9.times do |_j|
line << {}
end
board << line
end
board
end | [
"def",
"generate_empty_board",
"board",
"=",
"[",
"]",
"9",
".",
"times",
"do",
"|",
"_i",
"|",
"line",
"=",
"[",
"]",
"9",
".",
"times",
"do",
"|",
"_j",
"|",
"line",
"<<",
"{",
"}",
"end",
"board",
"<<",
"line",
"end",
"board",
"end"
]
| return empty board jkf | [
"return",
"empty",
"board",
"jkf"
]
| 4fd229c50737cab7b41281238880f1414e55e061 | https://github.com/iyuuya/jkf/blob/4fd229c50737cab7b41281238880f1414e55e061/lib/jkf/parser/csa.rb#L773-L783 | train |
stellar/ruby-stellar-base | lib/stellar/transaction.rb | Stellar.Transaction.to_operations | def to_operations
cloned = Marshal.load Marshal.dump(operations)
operations.each do |op|
op.source_account ||= self.source_account
end
end | ruby | def to_operations
cloned = Marshal.load Marshal.dump(operations)
operations.each do |op|
op.source_account ||= self.source_account
end
end | [
"def",
"to_operations",
"cloned",
"=",
"Marshal",
".",
"load",
"Marshal",
".",
"dump",
"(",
"operations",
")",
"operations",
".",
"each",
"do",
"|",
"op",
"|",
"op",
".",
"source_account",
"||=",
"self",
".",
"source_account",
"end",
"end"
]
| Extracts the operations from this single transaction,
setting the source account on the extracted operations.
Useful for merging transactions.
@return [Array<Operation>] the operations | [
"Extracts",
"the",
"operations",
"from",
"this",
"single",
"transaction",
"setting",
"the",
"source",
"account",
"on",
"the",
"extracted",
"operations",
"."
]
| 59ce19d1a71b5a02b67bc18c53b838f3fed6c5d1 | https://github.com/stellar/ruby-stellar-base/blob/59ce19d1a71b5a02b67bc18c53b838f3fed6c5d1/lib/stellar/transaction.rb#L169-L174 | train |
stellar/ruby-stellar-base | lib/stellar/path_payment_result.rb | Stellar.PathPaymentResult.send_amount | def send_amount
s = success!
return s.last.amount if s.offers.blank?
source_asset = s.offers.first.asset_bought
source_offers = s.offers.take_while{|o| o.asset_bought == source_asset}
source_offers.map(&:amount_bought).sum
end | ruby | def send_amount
s = success!
return s.last.amount if s.offers.blank?
source_asset = s.offers.first.asset_bought
source_offers = s.offers.take_while{|o| o.asset_bought == source_asset}
source_offers.map(&:amount_bought).sum
end | [
"def",
"send_amount",
"s",
"=",
"success!",
"return",
"s",
".",
"last",
".",
"amount",
"if",
"s",
".",
"offers",
".",
"blank?",
"source_asset",
"=",
"s",
".",
"offers",
".",
"first",
".",
"asset_bought",
"source_offers",
"=",
"s",
".",
"offers",
".",
"take_while",
"{",
"|",
"o",
"|",
"o",
".",
"asset_bought",
"==",
"source_asset",
"}",
"source_offers",
".",
"map",
"(",
"&",
":amount_bought",
")",
".",
"sum",
"end"
]
| send_amount returns the actual amount paid for the corresponding
PathPaymentOp to this result. | [
"send_amount",
"returns",
"the",
"actual",
"amount",
"paid",
"for",
"the",
"corresponding",
"PathPaymentOp",
"to",
"this",
"result",
"."
]
| 59ce19d1a71b5a02b67bc18c53b838f3fed6c5d1 | https://github.com/stellar/ruby-stellar-base/blob/59ce19d1a71b5a02b67bc18c53b838f3fed6c5d1/lib/stellar/path_payment_result.rb#L6-L14 | train |
stellar/ruby-stellar-base | lib/stellar/transaction_envelope.rb | Stellar.TransactionEnvelope.signed_correctly? | def signed_correctly?(*key_pairs)
hash = tx.hash
return false if signatures.empty?
key_index = key_pairs.index_by(&:signature_hint)
signatures.all? do |sig|
key_pair = key_index[sig.hint]
break false if key_pair.nil?
key_pair.verify(sig.signature, hash)
end
end | ruby | def signed_correctly?(*key_pairs)
hash = tx.hash
return false if signatures.empty?
key_index = key_pairs.index_by(&:signature_hint)
signatures.all? do |sig|
key_pair = key_index[sig.hint]
break false if key_pair.nil?
key_pair.verify(sig.signature, hash)
end
end | [
"def",
"signed_correctly?",
"(",
"*",
"key_pairs",
")",
"hash",
"=",
"tx",
".",
"hash",
"return",
"false",
"if",
"signatures",
".",
"empty?",
"key_index",
"=",
"key_pairs",
".",
"index_by",
"(",
"&",
":signature_hint",
")",
"signatures",
".",
"all?",
"do",
"|",
"sig",
"|",
"key_pair",
"=",
"key_index",
"[",
"sig",
".",
"hint",
"]",
"break",
"false",
"if",
"key_pair",
".",
"nil?",
"key_pair",
".",
"verify",
"(",
"sig",
".",
"signature",
",",
"hash",
")",
"end",
"end"
]
| Checks to ensure that every signature for the envelope is
a valid signature of one of the provided `key_pairs`
NOTE: this does not do any authorization checks, which requires access to
the current ledger state.
@param *key_pairs [Array<Stellar::KeyPair>] The key pairs to check the envelopes signatures against
@return [Boolean] true if all signatures are from the provided key_pairs and validly sign the tx's hash | [
"Checks",
"to",
"ensure",
"that",
"every",
"signature",
"for",
"the",
"envelope",
"is",
"a",
"valid",
"signature",
"of",
"one",
"of",
"the",
"provided",
"key_pairs"
]
| 59ce19d1a71b5a02b67bc18c53b838f3fed6c5d1 | https://github.com/stellar/ruby-stellar-base/blob/59ce19d1a71b5a02b67bc18c53b838f3fed6c5d1/lib/stellar/transaction_envelope.rb#L14-L26 | train |
xing/beetle | lib/beetle/client.rb | Beetle.Client.configure | def configure(options={}, &block)
configurator = Configurator.new(self, options)
if block.arity == 1
yield configurator
else
configurator.instance_eval(&block)
end
self
end | ruby | def configure(options={}, &block)
configurator = Configurator.new(self, options)
if block.arity == 1
yield configurator
else
configurator.instance_eval(&block)
end
self
end | [
"def",
"configure",
"(",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"configurator",
"=",
"Configurator",
".",
"new",
"(",
"self",
",",
"options",
")",
"if",
"block",
".",
"arity",
"==",
"1",
"yield",
"configurator",
"else",
"configurator",
".",
"instance_eval",
"(",
"&",
"block",
")",
"end",
"self",
"end"
]
| this is a convenience method to configure exchanges, queues, messages and handlers
with a common set of options. allows one to call all register methods without the
register_ prefix. returns self. if the passed in block has no parameters, the block
will be evaluated in the context of the client configurator.
Example: (block with config argument)
client = Beetle.client.new.configure :exchange => :foobar do |config|
config.queue :q1, :key => "foo"
config.queue :q2, :key => "bar"
config.message :foo
config.message :bar
config.handler :q1 { puts "got foo"}
config.handler :q2 { puts "got bar"}
end
Example: (block without config argument)
client = Beetle.client.new.configure :exchange => :foobar do
queue :q1, :key => "foo"
queue :q2, :key => "bar"
message :foo
message :bar
handler :q1 { puts "got foo"}
handler :q2 { puts "got bar"}
end | [
"this",
"is",
"a",
"convenience",
"method",
"to",
"configure",
"exchanges",
"queues",
"messages",
"and",
"handlers",
"with",
"a",
"common",
"set",
"of",
"options",
".",
"allows",
"one",
"to",
"call",
"all",
"register",
"methods",
"without",
"the",
"register_",
"prefix",
".",
"returns",
"self",
".",
"if",
"the",
"passed",
"in",
"block",
"has",
"no",
"parameters",
"the",
"block",
"will",
"be",
"evaluated",
"in",
"the",
"context",
"of",
"the",
"client",
"configurator",
"."
]
| 42322edc78e6e181b3b9ee284c3b00bddfc89108 | https://github.com/xing/beetle/blob/42322edc78e6e181b3b9ee284c3b00bddfc89108/lib/beetle/client.rb#L181-L189 | train |
xing/beetle | lib/beetle/client.rb | Beetle.Client.rpc | def rpc(message_name, data=nil, opts={})
message_name = validated_message_name(message_name)
publisher.rpc(message_name, data, opts)
end | ruby | def rpc(message_name, data=nil, opts={})
message_name = validated_message_name(message_name)
publisher.rpc(message_name, data, opts)
end | [
"def",
"rpc",
"(",
"message_name",
",",
"data",
"=",
"nil",
",",
"opts",
"=",
"{",
"}",
")",
"message_name",
"=",
"validated_message_name",
"(",
"message_name",
")",
"publisher",
".",
"rpc",
"(",
"message_name",
",",
"data",
",",
"opts",
")",
"end"
]
| sends the given message to one of the configured servers and returns the result of running the associated handler.
unexpected behavior can ensue if the message gets routed to more than one recipient, so be careful. | [
"sends",
"the",
"given",
"message",
"to",
"one",
"of",
"the",
"configured",
"servers",
"and",
"returns",
"the",
"result",
"of",
"running",
"the",
"associated",
"handler",
"."
]
| 42322edc78e6e181b3b9ee284c3b00bddfc89108 | https://github.com/xing/beetle/blob/42322edc78e6e181b3b9ee284c3b00bddfc89108/lib/beetle/client.rb#L201-L204 | train |
xing/beetle | lib/beetle/client.rb | Beetle.Client.trace | def trace(queue_names=self.queues.keys, tracer=nil, &block)
queues_to_trace = self.queues.slice(*queue_names)
queues_to_trace.each do |name, opts|
opts.merge! :durable => false, :auto_delete => true, :amqp_name => queue_name_for_tracing(opts[:amqp_name])
end
tracer ||=
lambda do |msg|
puts "-----===== new message =====-----"
puts "SERVER: #{msg.server}"
puts "HEADER: #{msg.header.attributes[:headers].inspect}"
puts "EXCHANGE: #{msg.header.method.exchange}"
puts "KEY: #{msg.header.method.routing_key}"
puts "MSGID: #{msg.msg_id}"
puts "DATA: #{msg.data}"
end
register_handler(queue_names){|msg| tracer.call msg }
listen_queues(queue_names, &block)
end | ruby | def trace(queue_names=self.queues.keys, tracer=nil, &block)
queues_to_trace = self.queues.slice(*queue_names)
queues_to_trace.each do |name, opts|
opts.merge! :durable => false, :auto_delete => true, :amqp_name => queue_name_for_tracing(opts[:amqp_name])
end
tracer ||=
lambda do |msg|
puts "-----===== new message =====-----"
puts "SERVER: #{msg.server}"
puts "HEADER: #{msg.header.attributes[:headers].inspect}"
puts "EXCHANGE: #{msg.header.method.exchange}"
puts "KEY: #{msg.header.method.routing_key}"
puts "MSGID: #{msg.msg_id}"
puts "DATA: #{msg.data}"
end
register_handler(queue_names){|msg| tracer.call msg }
listen_queues(queue_names, &block)
end | [
"def",
"trace",
"(",
"queue_names",
"=",
"self",
".",
"queues",
".",
"keys",
",",
"tracer",
"=",
"nil",
",",
"&",
"block",
")",
"queues_to_trace",
"=",
"self",
".",
"queues",
".",
"slice",
"(",
"*",
"queue_names",
")",
"queues_to_trace",
".",
"each",
"do",
"|",
"name",
",",
"opts",
"|",
"opts",
".",
"merge!",
":durable",
"=>",
"false",
",",
":auto_delete",
"=>",
"true",
",",
":amqp_name",
"=>",
"queue_name_for_tracing",
"(",
"opts",
"[",
":amqp_name",
"]",
")",
"end",
"tracer",
"||=",
"lambda",
"do",
"|",
"msg",
"|",
"puts",
"\"-----===== new message =====-----\"",
"puts",
"\"SERVER: #{msg.server}\"",
"puts",
"\"HEADER: #{msg.header.attributes[:headers].inspect}\"",
"puts",
"\"EXCHANGE: #{msg.header.method.exchange}\"",
"puts",
"\"KEY: #{msg.header.method.routing_key}\"",
"puts",
"\"MSGID: #{msg.msg_id}\"",
"puts",
"\"DATA: #{msg.data}\"",
"end",
"register_handler",
"(",
"queue_names",
")",
"{",
"|",
"msg",
"|",
"tracer",
".",
"call",
"msg",
"}",
"listen_queues",
"(",
"queue_names",
",",
"&",
"block",
")",
"end"
]
| traces queues without consuming them. useful for debugging message flow. | [
"traces",
"queues",
"without",
"consuming",
"them",
".",
"useful",
"for",
"debugging",
"message",
"flow",
"."
]
| 42322edc78e6e181b3b9ee284c3b00bddfc89108 | https://github.com/xing/beetle/blob/42322edc78e6e181b3b9ee284c3b00bddfc89108/lib/beetle/client.rb#L255-L272 | train |
xing/beetle | lib/beetle/client.rb | Beetle.Client.load | def load(glob)
b = binding
Dir[glob].each do |f|
eval(File.read(f), b, f)
end
end | ruby | def load(glob)
b = binding
Dir[glob].each do |f|
eval(File.read(f), b, f)
end
end | [
"def",
"load",
"(",
"glob",
")",
"b",
"=",
"binding",
"Dir",
"[",
"glob",
"]",
".",
"each",
"do",
"|",
"f",
"|",
"eval",
"(",
"File",
".",
"read",
"(",
"f",
")",
",",
"b",
",",
"f",
")",
"end",
"end"
]
| evaluate the ruby files matching the given +glob+ pattern in the context of the client instance. | [
"evaluate",
"the",
"ruby",
"files",
"matching",
"the",
"given",
"+",
"glob",
"+",
"pattern",
"in",
"the",
"context",
"of",
"the",
"client",
"instance",
"."
]
| 42322edc78e6e181b3b9ee284c3b00bddfc89108 | https://github.com/xing/beetle/blob/42322edc78e6e181b3b9ee284c3b00bddfc89108/lib/beetle/client.rb#L275-L280 | train |
xing/beetle | lib/beetle/message.rb | Beetle.Message.decode | def decode #:nodoc:
amqp_headers = header.attributes
@uuid = amqp_headers[:message_id]
@timestamp = amqp_headers[:timestamp]
headers = amqp_headers[:headers].symbolize_keys
@format_version = headers[:format_version].to_i
@flags = headers[:flags].to_i
@expires_at = headers[:expires_at].to_i
rescue Exception => @exception
Beetle::reraise_expectation_errors!
logger.error "Could not decode message. #{self.inspect}"
end | ruby | def decode #:nodoc:
amqp_headers = header.attributes
@uuid = amqp_headers[:message_id]
@timestamp = amqp_headers[:timestamp]
headers = amqp_headers[:headers].symbolize_keys
@format_version = headers[:format_version].to_i
@flags = headers[:flags].to_i
@expires_at = headers[:expires_at].to_i
rescue Exception => @exception
Beetle::reraise_expectation_errors!
logger.error "Could not decode message. #{self.inspect}"
end | [
"def",
"decode",
"amqp_headers",
"=",
"header",
".",
"attributes",
"@uuid",
"=",
"amqp_headers",
"[",
":message_id",
"]",
"@timestamp",
"=",
"amqp_headers",
"[",
":timestamp",
"]",
"headers",
"=",
"amqp_headers",
"[",
":headers",
"]",
".",
"symbolize_keys",
"@format_version",
"=",
"headers",
"[",
":format_version",
"]",
".",
"to_i",
"@flags",
"=",
"headers",
"[",
":flags",
"]",
".",
"to_i",
"@expires_at",
"=",
"headers",
"[",
":expires_at",
"]",
".",
"to_i",
"rescue",
"Exception",
"=>",
"@exception",
"Beetle",
"::",
"reraise_expectation_errors!",
"logger",
".",
"error",
"\"Could not decode message. #{self.inspect}\"",
"end"
]
| extracts various values from the AMQP header properties | [
"extracts",
"various",
"values",
"from",
"the",
"AMQP",
"header",
"properties"
]
| 42322edc78e6e181b3b9ee284c3b00bddfc89108 | https://github.com/xing/beetle/blob/42322edc78e6e181b3b9ee284c3b00bddfc89108/lib/beetle/message.rb#L84-L95 | train |
xing/beetle | lib/beetle/message.rb | Beetle.Message.key_exists? | def key_exists?
old_message = [email protected](msg_id, :status =>"incomplete", :expires => @expires_at, :timeout => now + timeout)
if old_message
logger.debug "Beetle: received duplicate message: #{msg_id} on queue: #{@queue}"
end
old_message
end | ruby | def key_exists?
old_message = [email protected](msg_id, :status =>"incomplete", :expires => @expires_at, :timeout => now + timeout)
if old_message
logger.debug "Beetle: received duplicate message: #{msg_id} on queue: #{@queue}"
end
old_message
end | [
"def",
"key_exists?",
"old_message",
"=",
"!",
"@store",
".",
"msetnx",
"(",
"msg_id",
",",
":status",
"=>",
"\"incomplete\"",
",",
":expires",
"=>",
"@expires_at",
",",
":timeout",
"=>",
"now",
"+",
"timeout",
")",
"if",
"old_message",
"logger",
".",
"debug",
"\"Beetle: received duplicate message: #{msg_id} on queue: #{@queue}\"",
"end",
"old_message",
"end"
]
| have we already seen this message? if not, set the status to "incomplete" and store
the message exipration timestamp in the deduplication store. | [
"have",
"we",
"already",
"seen",
"this",
"message?",
"if",
"not",
"set",
"the",
"status",
"to",
"incomplete",
"and",
"store",
"the",
"message",
"exipration",
"timestamp",
"in",
"the",
"deduplication",
"store",
"."
]
| 42322edc78e6e181b3b9ee284c3b00bddfc89108 | https://github.com/xing/beetle/blob/42322edc78e6e181b3b9ee284c3b00bddfc89108/lib/beetle/message.rb#L237-L243 | train |
xing/beetle | lib/beetle/message.rb | Beetle.Message.process | def process(handler)
logger.debug "Beetle: processing message #{msg_id}"
result = nil
begin
result = process_internal(handler)
handler.process_exception(@exception) if @exception
handler.process_failure(result) if result.failure?
rescue Exception => e
Beetle::reraise_expectation_errors!
logger.warn "Beetle: exception '#{e}' during processing of message #{msg_id}"
logger.warn "Beetle: backtrace: #{e.backtrace.join("\n")}"
result = RC::InternalError
end
result
end | ruby | def process(handler)
logger.debug "Beetle: processing message #{msg_id}"
result = nil
begin
result = process_internal(handler)
handler.process_exception(@exception) if @exception
handler.process_failure(result) if result.failure?
rescue Exception => e
Beetle::reraise_expectation_errors!
logger.warn "Beetle: exception '#{e}' during processing of message #{msg_id}"
logger.warn "Beetle: backtrace: #{e.backtrace.join("\n")}"
result = RC::InternalError
end
result
end | [
"def",
"process",
"(",
"handler",
")",
"logger",
".",
"debug",
"\"Beetle: processing message #{msg_id}\"",
"result",
"=",
"nil",
"begin",
"result",
"=",
"process_internal",
"(",
"handler",
")",
"handler",
".",
"process_exception",
"(",
"@exception",
")",
"if",
"@exception",
"handler",
".",
"process_failure",
"(",
"result",
")",
"if",
"result",
".",
"failure?",
"rescue",
"Exception",
"=>",
"e",
"Beetle",
"::",
"reraise_expectation_errors!",
"logger",
".",
"warn",
"\"Beetle: exception '#{e}' during processing of message #{msg_id}\"",
"logger",
".",
"warn",
"\"Beetle: backtrace: #{e.backtrace.join(\"\\n\")}\"",
"result",
"=",
"RC",
"::",
"InternalError",
"end",
"result",
"end"
]
| process this message and do not allow any exception to escape to the caller | [
"process",
"this",
"message",
"and",
"do",
"not",
"allow",
"any",
"exception",
"to",
"escape",
"to",
"the",
"caller"
]
| 42322edc78e6e181b3b9ee284c3b00bddfc89108 | https://github.com/xing/beetle/blob/42322edc78e6e181b3b9ee284c3b00bddfc89108/lib/beetle/message.rb#L266-L280 | train |
xing/beetle | lib/beetle/message.rb | Beetle.Message.ack! | def ack!
#:doc:
logger.debug "Beetle: ack! for message #{msg_id}"
header.ack
return if simple? # simple messages don't use the deduplication store
if !redundant? || @store.incr(msg_id, :ack_count) == 2
@store.del_keys(msg_id)
end
end | ruby | def ack!
#:doc:
logger.debug "Beetle: ack! for message #{msg_id}"
header.ack
return if simple? # simple messages don't use the deduplication store
if !redundant? || @store.incr(msg_id, :ack_count) == 2
@store.del_keys(msg_id)
end
end | [
"def",
"ack!",
"logger",
".",
"debug",
"\"Beetle: ack! for message #{msg_id}\"",
"header",
".",
"ack",
"return",
"if",
"simple?",
"if",
"!",
"redundant?",
"||",
"@store",
".",
"incr",
"(",
"msg_id",
",",
":ack_count",
")",
"==",
"2",
"@store",
".",
"del_keys",
"(",
"msg_id",
")",
"end",
"end"
]
| ack the message for rabbit. deletes all keys associated with this message in the
deduplication store if we are sure this is the last message with the given msg_id. | [
"ack",
"the",
"message",
"for",
"rabbit",
".",
"deletes",
"all",
"keys",
"associated",
"with",
"this",
"message",
"in",
"the",
"deduplication",
"store",
"if",
"we",
"are",
"sure",
"this",
"is",
"the",
"last",
"message",
"with",
"the",
"given",
"msg_id",
"."
]
| 42322edc78e6e181b3b9ee284c3b00bddfc89108 | https://github.com/xing/beetle/blob/42322edc78e6e181b3b9ee284c3b00bddfc89108/lib/beetle/message.rb#L379-L387 | train |
xing/beetle | lib/beetle/publisher.rb | Beetle.Publisher.bunny_exceptions | def bunny_exceptions
[
Bunny::ConnectionError, Bunny::ForcedChannelCloseError, Bunny::ForcedConnectionCloseError,
Bunny::MessageError, Bunny::ProtocolError, Bunny::ServerDownError, Bunny::UnsubscribeError,
Bunny::AcknowledgementError, Qrack::BufferOverflowError, Qrack::InvalidTypeError,
Errno::EHOSTUNREACH, Errno::ECONNRESET, Timeout::Error
]
end | ruby | def bunny_exceptions
[
Bunny::ConnectionError, Bunny::ForcedChannelCloseError, Bunny::ForcedConnectionCloseError,
Bunny::MessageError, Bunny::ProtocolError, Bunny::ServerDownError, Bunny::UnsubscribeError,
Bunny::AcknowledgementError, Qrack::BufferOverflowError, Qrack::InvalidTypeError,
Errno::EHOSTUNREACH, Errno::ECONNRESET, Timeout::Error
]
end | [
"def",
"bunny_exceptions",
"[",
"Bunny",
"::",
"ConnectionError",
",",
"Bunny",
"::",
"ForcedChannelCloseError",
",",
"Bunny",
"::",
"ForcedConnectionCloseError",
",",
"Bunny",
"::",
"MessageError",
",",
"Bunny",
"::",
"ProtocolError",
",",
"Bunny",
"::",
"ServerDownError",
",",
"Bunny",
"::",
"UnsubscribeError",
",",
"Bunny",
"::",
"AcknowledgementError",
",",
"Qrack",
"::",
"BufferOverflowError",
",",
"Qrack",
"::",
"InvalidTypeError",
",",
"Errno",
"::",
"EHOSTUNREACH",
",",
"Errno",
"::",
"ECONNRESET",
",",
"Timeout",
"::",
"Error",
"]",
"end"
]
| list of exceptions potentially raised by bunny
these need to be lazy, because qrack exceptions are only defined after a connection has been established | [
"list",
"of",
"exceptions",
"potentially",
"raised",
"by",
"bunny",
"these",
"need",
"to",
"be",
"lazy",
"because",
"qrack",
"exceptions",
"are",
"only",
"defined",
"after",
"a",
"connection",
"has",
"been",
"established"
]
| 42322edc78e6e181b3b9ee284c3b00bddfc89108 | https://github.com/xing/beetle/blob/42322edc78e6e181b3b9ee284c3b00bddfc89108/lib/beetle/publisher.rb#L17-L24 | train |
xing/beetle | lib/beetle/publisher.rb | Beetle.Publisher.recycle_dead_servers | def recycle_dead_servers
recycle = []
@dead_servers.each do |s, dead_since|
recycle << s if dead_since < 10.seconds.ago
end
if recycle.empty? && @servers.empty?
recycle << @dead_servers.keys.sort_by{|k| @dead_servers[k]}.first
end
@servers.concat recycle
recycle.each {|s| @dead_servers.delete(s)}
end | ruby | def recycle_dead_servers
recycle = []
@dead_servers.each do |s, dead_since|
recycle << s if dead_since < 10.seconds.ago
end
if recycle.empty? && @servers.empty?
recycle << @dead_servers.keys.sort_by{|k| @dead_servers[k]}.first
end
@servers.concat recycle
recycle.each {|s| @dead_servers.delete(s)}
end | [
"def",
"recycle_dead_servers",
"recycle",
"=",
"[",
"]",
"@dead_servers",
".",
"each",
"do",
"|",
"s",
",",
"dead_since",
"|",
"recycle",
"<<",
"s",
"if",
"dead_since",
"<",
"10",
".",
"seconds",
".",
"ago",
"end",
"if",
"recycle",
".",
"empty?",
"&&",
"@servers",
".",
"empty?",
"recycle",
"<<",
"@dead_servers",
".",
"keys",
".",
"sort_by",
"{",
"|",
"k",
"|",
"@dead_servers",
"[",
"k",
"]",
"}",
".",
"first",
"end",
"@servers",
".",
"concat",
"recycle",
"recycle",
".",
"each",
"{",
"|",
"s",
"|",
"@dead_servers",
".",
"delete",
"(",
"s",
")",
"}",
"end"
]
| retry dead servers after ignoring them for 10.seconds
if all servers are dead, retry the one which has been dead for the longest time | [
"retry",
"dead",
"servers",
"after",
"ignoring",
"them",
"for",
"10",
".",
"seconds",
"if",
"all",
"servers",
"are",
"dead",
"retry",
"the",
"one",
"which",
"has",
"been",
"dead",
"for",
"the",
"longest",
"time"
]
| 42322edc78e6e181b3b9ee284c3b00bddfc89108 | https://github.com/xing/beetle/blob/42322edc78e6e181b3b9ee284c3b00bddfc89108/lib/beetle/publisher.rb#L187-L197 | train |
xing/beetle | lib/beetle/deduplication_store.rb | Beetle.DeduplicationStore.with_failover | def with_failover #:nodoc:
end_time = Time.now.to_i + @config.redis_failover_timeout.to_i
begin
yield
rescue Exception => e
Beetle::reraise_expectation_errors!
logger.error "Beetle: redis connection error #{e} #{@config.redis_server} (#{e.backtrace[0]})"
if Time.now.to_i < end_time
sleep 1
logger.info "Beetle: retrying redis operation"
retry
else
raise NoRedisMaster.new(e.to_s)
end
end
end | ruby | def with_failover #:nodoc:
end_time = Time.now.to_i + @config.redis_failover_timeout.to_i
begin
yield
rescue Exception => e
Beetle::reraise_expectation_errors!
logger.error "Beetle: redis connection error #{e} #{@config.redis_server} (#{e.backtrace[0]})"
if Time.now.to_i < end_time
sleep 1
logger.info "Beetle: retrying redis operation"
retry
else
raise NoRedisMaster.new(e.to_s)
end
end
end | [
"def",
"with_failover",
"end_time",
"=",
"Time",
".",
"now",
".",
"to_i",
"+",
"@config",
".",
"redis_failover_timeout",
".",
"to_i",
"begin",
"yield",
"rescue",
"Exception",
"=>",
"e",
"Beetle",
"::",
"reraise_expectation_errors!",
"logger",
".",
"error",
"\"Beetle: redis connection error #{e} #{@config.redis_server} (#{e.backtrace[0]})\"",
"if",
"Time",
".",
"now",
".",
"to_i",
"<",
"end_time",
"sleep",
"1",
"logger",
".",
"info",
"\"Beetle: retrying redis operation\"",
"retry",
"else",
"raise",
"NoRedisMaster",
".",
"new",
"(",
"e",
".",
"to_s",
")",
"end",
"end",
"end"
]
| performs redis operations by yielding a passed in block, waiting for a new master to
show up on the network if the operation throws an exception. if a new master doesn't
appear after the configured timeout interval, we raise an exception. | [
"performs",
"redis",
"operations",
"by",
"yielding",
"a",
"passed",
"in",
"block",
"waiting",
"for",
"a",
"new",
"master",
"to",
"show",
"up",
"on",
"the",
"network",
"if",
"the",
"operation",
"throws",
"an",
"exception",
".",
"if",
"a",
"new",
"master",
"doesn",
"t",
"appear",
"after",
"the",
"configured",
"timeout",
"interval",
"we",
"raise",
"an",
"exception",
"."
]
| 42322edc78e6e181b3b9ee284c3b00bddfc89108 | https://github.com/xing/beetle/blob/42322edc78e6e181b3b9ee284c3b00bddfc89108/lib/beetle/deduplication_store.rb#L112-L127 | train |
xing/beetle | lib/beetle/deduplication_store.rb | Beetle.DeduplicationStore.extract_redis_master | def extract_redis_master(text)
system_name = @config.system_name
redis_master = ""
text.each_line do |line|
parts = line.split('/', 2)
case parts.size
when 1
redis_master = parts[0]
when 2
name, master = parts
redis_master = master if name == system_name
end
end
redis_master
end | ruby | def extract_redis_master(text)
system_name = @config.system_name
redis_master = ""
text.each_line do |line|
parts = line.split('/', 2)
case parts.size
when 1
redis_master = parts[0]
when 2
name, master = parts
redis_master = master if name == system_name
end
end
redis_master
end | [
"def",
"extract_redis_master",
"(",
"text",
")",
"system_name",
"=",
"@config",
".",
"system_name",
"redis_master",
"=",
"\"\"",
"text",
".",
"each_line",
"do",
"|",
"line",
"|",
"parts",
"=",
"line",
".",
"split",
"(",
"'/'",
",",
"2",
")",
"case",
"parts",
".",
"size",
"when",
"1",
"redis_master",
"=",
"parts",
"[",
"0",
"]",
"when",
"2",
"name",
",",
"master",
"=",
"parts",
"redis_master",
"=",
"master",
"if",
"name",
"==",
"system_name",
"end",
"end",
"redis_master",
"end"
]
| extract redis master from file content and return the server for our system | [
"extract",
"redis",
"master",
"from",
"file",
"content",
"and",
"return",
"the",
"server",
"for",
"our",
"system"
]
| 42322edc78e6e181b3b9ee284c3b00bddfc89108 | https://github.com/xing/beetle/blob/42322edc78e6e181b3b9ee284c3b00bddfc89108/lib/beetle/deduplication_store.rb#L153-L167 | train |
xing/beetle | lib/beetle/subscriber.rb | Beetle.Subscriber.close_all_connections | def close_all_connections
if @connections.empty?
EM.stop_event_loop
else
server, connection = @connections.shift
logger.debug "Beetle: closing connection to #{server}"
connection.close { close_all_connections }
end
end | ruby | def close_all_connections
if @connections.empty?
EM.stop_event_loop
else
server, connection = @connections.shift
logger.debug "Beetle: closing connection to #{server}"
connection.close { close_all_connections }
end
end | [
"def",
"close_all_connections",
"if",
"@connections",
".",
"empty?",
"EM",
".",
"stop_event_loop",
"else",
"server",
",",
"connection",
"=",
"@connections",
".",
"shift",
"logger",
".",
"debug",
"\"Beetle: closing connection to #{server}\"",
"connection",
".",
"close",
"{",
"close_all_connections",
"}",
"end",
"end"
]
| close all connections. this assumes the reactor is running | [
"close",
"all",
"connections",
".",
"this",
"assumes",
"the",
"reactor",
"is",
"running"
]
| 42322edc78e6e181b3b9ee284c3b00bddfc89108 | https://github.com/xing/beetle/blob/42322edc78e6e181b3b9ee284c3b00bddfc89108/lib/beetle/subscriber.rb#L84-L92 | train |
theforeman/foreman-digitalocean | app/models/foreman_digitalocean/digitalocean.rb | ForemanDigitalocean.Digitalocean.setup_key_pair | def setup_key_pair
public_key, private_key = generate_key
key_name = "foreman-#{id}#{Foreman.uuid}"
client.create_ssh_key key_name, public_key
KeyPair.create! :name => key_name, :compute_resource_id => id, :secret => private_key
rescue StandardError => e
logger.warn 'failed to generate key pair'
logger.error e.message
logger.error e.backtrace.join("\n")
destroy_key_pair
raise
end | ruby | def setup_key_pair
public_key, private_key = generate_key
key_name = "foreman-#{id}#{Foreman.uuid}"
client.create_ssh_key key_name, public_key
KeyPair.create! :name => key_name, :compute_resource_id => id, :secret => private_key
rescue StandardError => e
logger.warn 'failed to generate key pair'
logger.error e.message
logger.error e.backtrace.join("\n")
destroy_key_pair
raise
end | [
"def",
"setup_key_pair",
"public_key",
",",
"private_key",
"=",
"generate_key",
"key_name",
"=",
"\"foreman-#{id}#{Foreman.uuid}\"",
"client",
".",
"create_ssh_key",
"key_name",
",",
"public_key",
"KeyPair",
".",
"create!",
":name",
"=>",
"key_name",
",",
":compute_resource_id",
"=>",
"id",
",",
":secret",
"=>",
"private_key",
"rescue",
"StandardError",
"=>",
"e",
"logger",
".",
"warn",
"'failed to generate key pair'",
"logger",
".",
"error",
"e",
".",
"message",
"logger",
".",
"error",
"e",
".",
"backtrace",
".",
"join",
"(",
"\"\\n\"",
")",
"destroy_key_pair",
"raise",
"end"
]
| Creates a new key pair for each new DigitalOcean compute resource
After creating the key, it uploads it to DigitalOcean | [
"Creates",
"a",
"new",
"key",
"pair",
"for",
"each",
"new",
"DigitalOcean",
"compute",
"resource",
"After",
"creating",
"the",
"key",
"it",
"uploads",
"it",
"to",
"DigitalOcean"
]
| 81a20226af7052a61edb14f1289271ab7b6a2ff7 | https://github.com/theforeman/foreman-digitalocean/blob/81a20226af7052a61edb14f1289271ab7b6a2ff7/app/models/foreman_digitalocean/digitalocean.rb#L119-L130 | train |
keenlabs/keen-gem | lib/keen/saved_queries.rb | Keen.SavedQueries.clear_nil_attributes | def clear_nil_attributes(hash)
hash.reject! do |key, value|
if value.nil?
return true
elsif value.is_a? Hash
value.reject! { |inner_key, inner_value| inner_value.nil? }
end
false
end
hash
end | ruby | def clear_nil_attributes(hash)
hash.reject! do |key, value|
if value.nil?
return true
elsif value.is_a? Hash
value.reject! { |inner_key, inner_value| inner_value.nil? }
end
false
end
hash
end | [
"def",
"clear_nil_attributes",
"(",
"hash",
")",
"hash",
".",
"reject!",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"value",
".",
"nil?",
"return",
"true",
"elsif",
"value",
".",
"is_a?",
"Hash",
"value",
".",
"reject!",
"{",
"|",
"inner_key",
",",
"inner_value",
"|",
"inner_value",
".",
"nil?",
"}",
"end",
"false",
"end",
"hash",
"end"
]
| Remove any attributes with nil values in a saved query hash. The API will
already assume missing attributes are nil | [
"Remove",
"any",
"attributes",
"with",
"nil",
"values",
"in",
"a",
"saved",
"query",
"hash",
".",
"The",
"API",
"will",
"already",
"assume",
"missing",
"attributes",
"are",
"nil"
]
| 5309fc62e1211685bf70fb676bce24350fbe7668 | https://github.com/keenlabs/keen-gem/blob/5309fc62e1211685bf70fb676bce24350fbe7668/lib/keen/saved_queries.rb#L101-L113 | train |
chicks/sugarcrm | lib/sugarcrm/connection_pool.rb | SugarCRM.ConnectionPool.with_connection | def with_connection
connection_id = current_connection_id
fresh_connection = true unless @reserved_connections[connection_id]
yield connection
ensure
release_connection(connection_id) if fresh_connection
end | ruby | def with_connection
connection_id = current_connection_id
fresh_connection = true unless @reserved_connections[connection_id]
yield connection
ensure
release_connection(connection_id) if fresh_connection
end | [
"def",
"with_connection",
"connection_id",
"=",
"current_connection_id",
"fresh_connection",
"=",
"true",
"unless",
"@reserved_connections",
"[",
"connection_id",
"]",
"yield",
"connection",
"ensure",
"release_connection",
"(",
"connection_id",
")",
"if",
"fresh_connection",
"end"
]
| If a connection already exists yield it to the block. If no connection
exists checkout a connection, yield it to the block, and checkin the
connection when finished. | [
"If",
"a",
"connection",
"already",
"exists",
"yield",
"it",
"to",
"the",
"block",
".",
"If",
"no",
"connection",
"exists",
"checkout",
"a",
"connection",
"yield",
"it",
"to",
"the",
"block",
"and",
"checkin",
"the",
"connection",
"when",
"finished",
"."
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/connection_pool.rb#L27-L33 | train |
chicks/sugarcrm | lib/sugarcrm/connection_pool.rb | SugarCRM.ConnectionPool.clear_stale_cached_connections! | def clear_stale_cached_connections!
keys = @reserved_connections.keys - Thread.list.find_all { |t|
t.alive?
}.map { |thread| thread.object_id }
keys.each do |key|
checkin @reserved_connections[key]
@reserved_connections.delete(key)
end
end | ruby | def clear_stale_cached_connections!
keys = @reserved_connections.keys - Thread.list.find_all { |t|
t.alive?
}.map { |thread| thread.object_id }
keys.each do |key|
checkin @reserved_connections[key]
@reserved_connections.delete(key)
end
end | [
"def",
"clear_stale_cached_connections!",
"keys",
"=",
"@reserved_connections",
".",
"keys",
"-",
"Thread",
".",
"list",
".",
"find_all",
"{",
"|",
"t",
"|",
"t",
".",
"alive?",
"}",
".",
"map",
"{",
"|",
"thread",
"|",
"thread",
".",
"object_id",
"}",
"keys",
".",
"each",
"do",
"|",
"key",
"|",
"checkin",
"@reserved_connections",
"[",
"key",
"]",
"@reserved_connections",
".",
"delete",
"(",
"key",
")",
"end",
"end"
]
| Return any checked-out connections back to the pool by threads that
are no longer alive. | [
"Return",
"any",
"checked",
"-",
"out",
"connections",
"back",
"to",
"the",
"pool",
"by",
"threads",
"that",
"are",
"no",
"longer",
"alive",
"."
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/connection_pool.rb#L103-L111 | train |
chicks/sugarcrm | lib/sugarcrm/attributes/attribute_methods.rb | SugarCRM.AttributeMethods.merge_attributes | def merge_attributes(attrs={})
# copy attributes from the parent module fields array
@attributes = self.class.attributes_from_module
# populate the attributes with values from the attrs provided to init.
@attributes.keys.each do |name|
write_attribute name, attrs[name] if attrs[name]
end
# If this is an existing record, blank out the modified_attributes hash
@modified_attributes = {} unless new?
end | ruby | def merge_attributes(attrs={})
# copy attributes from the parent module fields array
@attributes = self.class.attributes_from_module
# populate the attributes with values from the attrs provided to init.
@attributes.keys.each do |name|
write_attribute name, attrs[name] if attrs[name]
end
# If this is an existing record, blank out the modified_attributes hash
@modified_attributes = {} unless new?
end | [
"def",
"merge_attributes",
"(",
"attrs",
"=",
"{",
"}",
")",
"@attributes",
"=",
"self",
".",
"class",
".",
"attributes_from_module",
"@attributes",
".",
"keys",
".",
"each",
"do",
"|",
"name",
"|",
"write_attribute",
"name",
",",
"attrs",
"[",
"name",
"]",
"if",
"attrs",
"[",
"name",
"]",
"end",
"@modified_attributes",
"=",
"{",
"}",
"unless",
"new?",
"end"
]
| Merges attributes provided as an argument to initialize
with attributes from the module.fields array. Skips any
fields that aren't in the module.fields array
BUG: SugarCRM likes to return fields you don't ask for and
aren't fields on a module (i.e. modified_user_name). This
royally screws up our typecasting code, so we handle it here. | [
"Merges",
"attributes",
"provided",
"as",
"an",
"argument",
"to",
"initialize",
"with",
"attributes",
"from",
"the",
"module",
".",
"fields",
"array",
".",
"Skips",
"any",
"fields",
"that",
"aren",
"t",
"in",
"the",
"module",
".",
"fields",
"array"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/attributes/attribute_methods.rb#L100-L109 | train |
chicks/sugarcrm | lib/sugarcrm/attributes/attribute_methods.rb | SugarCRM.AttributeMethods.save_modified_attributes! | def save_modified_attributes!(opts={})
options = { :validate => true }.merge(opts)
if options[:validate]
# Complain if we aren't valid
raise InvalidRecord, @errors.full_messages.join(", ") unless valid?
end
# Send the save request
response = self.class.session.connection.set_entry(self.class._module.name, serialize_modified_attributes)
# Complain if we don't get a parseable response back
raise RecordsaveFailed, "Failed to save record: #{self}. Response was not a Hash" unless response.is_a? Hash
# Complain if we don't get a valid id back
raise RecordSaveFailed, "Failed to save record: #{self}. Response did not contain a valid 'id'." if response["id"].nil?
# Save the id to the record, if it's a new record
@attributes[:id] = response["id"] if new?
raise InvalidRecord, "Failed to update id for: #{self}." if id.nil?
# Clear the modified attributes Hash
@modified_attributes = {}
true
end | ruby | def save_modified_attributes!(opts={})
options = { :validate => true }.merge(opts)
if options[:validate]
# Complain if we aren't valid
raise InvalidRecord, @errors.full_messages.join(", ") unless valid?
end
# Send the save request
response = self.class.session.connection.set_entry(self.class._module.name, serialize_modified_attributes)
# Complain if we don't get a parseable response back
raise RecordsaveFailed, "Failed to save record: #{self}. Response was not a Hash" unless response.is_a? Hash
# Complain if we don't get a valid id back
raise RecordSaveFailed, "Failed to save record: #{self}. Response did not contain a valid 'id'." if response["id"].nil?
# Save the id to the record, if it's a new record
@attributes[:id] = response["id"] if new?
raise InvalidRecord, "Failed to update id for: #{self}." if id.nil?
# Clear the modified attributes Hash
@modified_attributes = {}
true
end | [
"def",
"save_modified_attributes!",
"(",
"opts",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":validate",
"=>",
"true",
"}",
".",
"merge",
"(",
"opts",
")",
"if",
"options",
"[",
":validate",
"]",
"raise",
"InvalidRecord",
",",
"@errors",
".",
"full_messages",
".",
"join",
"(",
"\", \"",
")",
"unless",
"valid?",
"end",
"response",
"=",
"self",
".",
"class",
".",
"session",
".",
"connection",
".",
"set_entry",
"(",
"self",
".",
"class",
".",
"_module",
".",
"name",
",",
"serialize_modified_attributes",
")",
"raise",
"RecordsaveFailed",
",",
"\"Failed to save record: #{self}. Response was not a Hash\"",
"unless",
"response",
".",
"is_a?",
"Hash",
"raise",
"RecordSaveFailed",
",",
"\"Failed to save record: #{self}. Response did not contain a valid 'id'.\"",
"if",
"response",
"[",
"\"id\"",
"]",
".",
"nil?",
"@attributes",
"[",
":id",
"]",
"=",
"response",
"[",
"\"id\"",
"]",
"if",
"new?",
"raise",
"InvalidRecord",
",",
"\"Failed to update id for: #{self}.\"",
"if",
"id",
".",
"nil?",
"@modified_attributes",
"=",
"{",
"}",
"true",
"end"
]
| Wrapper for invoking save on modified_attributes
sets the id if it's a new record | [
"Wrapper",
"for",
"invoking",
"save",
"on",
"modified_attributes",
"sets",
"the",
"id",
"if",
"it",
"s",
"a",
"new",
"record"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/attributes/attribute_methods.rb#L169-L187 | train |
chicks/sugarcrm | lib/sugarcrm/associations/associations.rb | SugarCRM.Associations.find! | def find!(target)
@associations.each do |a|
return a if a.include? target
end
raise InvalidAssociation, "Could not lookup association for: #{target}"
end | ruby | def find!(target)
@associations.each do |a|
return a if a.include? target
end
raise InvalidAssociation, "Could not lookup association for: #{target}"
end | [
"def",
"find!",
"(",
"target",
")",
"@associations",
".",
"each",
"do",
"|",
"a",
"|",
"return",
"a",
"if",
"a",
".",
"include?",
"target",
"end",
"raise",
"InvalidAssociation",
",",
"\"Could not lookup association for: #{target}\"",
"end"
]
| Looks up an association by object, link_field, or method.
Raises an exception if not found | [
"Looks",
"up",
"an",
"association",
"by",
"object",
"link_field",
"or",
"method",
".",
"Raises",
"an",
"exception",
"if",
"not",
"found"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/associations/associations.rb#L31-L36 | train |
chicks/sugarcrm | lib/sugarcrm/associations/association_methods.rb | SugarCRM.AssociationMethods.query_association | def query_association(assoc, reload=false)
association = assoc.to_sym
return @association_cache[association] if association_cached?(association) && !reload
# TODO: Some relationships aren't fetchable via get_relationship (i.e users.contacts)
# even though get_module_fields lists them on the related_fields array. This is most
# commonly seen with one-to-many relationships without a join table. We need to cook
# up some elegant way to handle this.
collection = AssociationCollection.new(self,association,true)
# add it to the cache
@association_cache[association] = collection
collection
end | ruby | def query_association(assoc, reload=false)
association = assoc.to_sym
return @association_cache[association] if association_cached?(association) && !reload
# TODO: Some relationships aren't fetchable via get_relationship (i.e users.contacts)
# even though get_module_fields lists them on the related_fields array. This is most
# commonly seen with one-to-many relationships without a join table. We need to cook
# up some elegant way to handle this.
collection = AssociationCollection.new(self,association,true)
# add it to the cache
@association_cache[association] = collection
collection
end | [
"def",
"query_association",
"(",
"assoc",
",",
"reload",
"=",
"false",
")",
"association",
"=",
"assoc",
".",
"to_sym",
"return",
"@association_cache",
"[",
"association",
"]",
"if",
"association_cached?",
"(",
"association",
")",
"&&",
"!",
"reload",
"collection",
"=",
"AssociationCollection",
".",
"new",
"(",
"self",
",",
"association",
",",
"true",
")",
"@association_cache",
"[",
"association",
"]",
"=",
"collection",
"collection",
"end"
]
| Returns the records from the associated module or returns the cached copy if we've already
loaded it. Force a reload of the records with reload=true
{"email_addresses"=>
{"name"=>"email_addresses",
"module"=>"EmailAddress",
"bean_name"=>"EmailAddress",
"relationship"=>"users_email_addresses",
"type"=>"link"}, | [
"Returns",
"the",
"records",
"from",
"the",
"associated",
"module",
"or",
"returns",
"the",
"cached",
"copy",
"if",
"we",
"ve",
"already",
"loaded",
"it",
".",
"Force",
"a",
"reload",
"of",
"the",
"records",
"with",
"reload",
"=",
"true"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/associations/association_methods.rb#L78-L89 | train |
chicks/sugarcrm | lib/sugarcrm/associations/association_cache.rb | SugarCRM.AssociationCache.update_association_cache_for | def update_association_cache_for(association, target, action=:add)
return unless association_cached? association
case action
when :add
return if @association_cache[association].collection.include? target
@association_cache[association].push(target) # don't use `<<` because overriden method in AssociationCollection gets called instead
when :delete
@association_cache[association].delete target
end
end | ruby | def update_association_cache_for(association, target, action=:add)
return unless association_cached? association
case action
when :add
return if @association_cache[association].collection.include? target
@association_cache[association].push(target) # don't use `<<` because overriden method in AssociationCollection gets called instead
when :delete
@association_cache[association].delete target
end
end | [
"def",
"update_association_cache_for",
"(",
"association",
",",
"target",
",",
"action",
"=",
":add",
")",
"return",
"unless",
"association_cached?",
"association",
"case",
"action",
"when",
":add",
"return",
"if",
"@association_cache",
"[",
"association",
"]",
".",
"collection",
".",
"include?",
"target",
"@association_cache",
"[",
"association",
"]",
".",
"push",
"(",
"target",
")",
"when",
":delete",
"@association_cache",
"[",
"association",
"]",
".",
"delete",
"target",
"end",
"end"
]
| Updates an association cache entry if it's been initialized | [
"Updates",
"an",
"association",
"cache",
"entry",
"if",
"it",
"s",
"been",
"initialized"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/associations/association_cache.rb#L11-L20 | train |
chicks/sugarcrm | lib/sugarcrm/associations/association_collection.rb | SugarCRM.AssociationCollection.changed? | def changed?
return false unless loaded?
return true if added.length > 0
return true if removed.length > 0
false
end | ruby | def changed?
return false unless loaded?
return true if added.length > 0
return true if removed.length > 0
false
end | [
"def",
"changed?",
"return",
"false",
"unless",
"loaded?",
"return",
"true",
"if",
"added",
".",
"length",
">",
"0",
"return",
"true",
"if",
"removed",
".",
"length",
">",
"0",
"false",
"end"
]
| creates a new instance of an AssociationCollection
Owner is the parent object, and association is the target | [
"creates",
"a",
"new",
"instance",
"of",
"an",
"AssociationCollection",
"Owner",
"is",
"the",
"parent",
"object",
"and",
"association",
"is",
"the",
"target"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/associations/association_collection.rb#L18-L23 | train |
chicks/sugarcrm | lib/sugarcrm/associations/association_collection.rb | SugarCRM.AssociationCollection.delete | def delete(record)
load
raise InvalidRecord, "#{record.class} does not have a valid :id!" if record.id.empty?
@collection.delete record
end | ruby | def delete(record)
load
raise InvalidRecord, "#{record.class} does not have a valid :id!" if record.id.empty?
@collection.delete record
end | [
"def",
"delete",
"(",
"record",
")",
"load",
"raise",
"InvalidRecord",
",",
"\"#{record.class} does not have a valid :id!\"",
"if",
"record",
".",
"id",
".",
"empty?",
"@collection",
".",
"delete",
"record",
"end"
]
| Removes a record from the collection, uses the id of the record as a test for inclusion. | [
"Removes",
"a",
"record",
"from",
"the",
"collection",
"uses",
"the",
"id",
"of",
"the",
"record",
"as",
"a",
"test",
"for",
"inclusion",
"."
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/associations/association_collection.rb#L50-L54 | train |
chicks/sugarcrm | lib/sugarcrm/associations/association_collection.rb | SugarCRM.AssociationCollection.<< | def <<(record)
load
record.save! if record.new?
result = true
result = false if include?(record)
@owner.update_association_cache_for(@association, record, :add)
record.update_association_cache_for(record.associations.find!(@owner).link_field, @owner, :add)
result && self
end | ruby | def <<(record)
load
record.save! if record.new?
result = true
result = false if include?(record)
@owner.update_association_cache_for(@association, record, :add)
record.update_association_cache_for(record.associations.find!(@owner).link_field, @owner, :add)
result && self
end | [
"def",
"<<",
"(",
"record",
")",
"load",
"record",
".",
"save!",
"if",
"record",
".",
"new?",
"result",
"=",
"true",
"result",
"=",
"false",
"if",
"include?",
"(",
"record",
")",
"@owner",
".",
"update_association_cache_for",
"(",
"@association",
",",
"record",
",",
":add",
")",
"record",
".",
"update_association_cache_for",
"(",
"record",
".",
"associations",
".",
"find!",
"(",
"@owner",
")",
".",
"link_field",
",",
"@owner",
",",
":add",
")",
"result",
"&&",
"self",
"end"
]
| Add +records+ to this association, saving any unsaved records before adding them.
Returns +self+ so method calls may be chained.
Be sure to call save on the association to commit any association changes | [
"Add",
"+",
"records",
"+",
"to",
"this",
"association",
"saving",
"any",
"unsaved",
"records",
"before",
"adding",
"them",
".",
"Returns",
"+",
"self",
"+",
"so",
"method",
"calls",
"may",
"be",
"chained",
".",
"Be",
"sure",
"to",
"call",
"save",
"on",
"the",
"association",
"to",
"commit",
"any",
"association",
"changes"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/associations/association_collection.rb#L66-L74 | train |
chicks/sugarcrm | lib/sugarcrm/associations/association_collection.rb | SugarCRM.AssociationCollection.method_missing | def method_missing(method_name, *args, &block)
load
@collection.send(method_name.to_sym, *args, &block)
end | ruby | def method_missing(method_name, *args, &block)
load
@collection.send(method_name.to_sym, *args, &block)
end | [
"def",
"method_missing",
"(",
"method_name",
",",
"*",
"args",
",",
"&",
"block",
")",
"load",
"@collection",
".",
"send",
"(",
"method_name",
".",
"to_sym",
",",
"*",
"args",
",",
"&",
"block",
")",
"end"
]
| delegate undefined methods to the @collection array
E.g. contact.cases should behave like an array and allow `length`, `size`, `each`, etc. | [
"delegate",
"undefined",
"methods",
"to",
"the"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/associations/association_collection.rb#L79-L82 | train |
chicks/sugarcrm | lib/sugarcrm/associations/association_collection.rb | SugarCRM.AssociationCollection.save! | def save!
load
added.each do |record|
associate!(record)
end
removed.each do |record|
disassociate!(record)
end
reload
true
end | ruby | def save!
load
added.each do |record|
associate!(record)
end
removed.each do |record|
disassociate!(record)
end
reload
true
end | [
"def",
"save!",
"load",
"added",
".",
"each",
"do",
"|",
"record",
"|",
"associate!",
"(",
"record",
")",
"end",
"removed",
".",
"each",
"do",
"|",
"record",
"|",
"disassociate!",
"(",
"record",
")",
"end",
"reload",
"true",
"end"
]
| Pushes collection changes to SugarCRM, and updates the state of the collection | [
"Pushes",
"collection",
"changes",
"to",
"SugarCRM",
"and",
"updates",
"the",
"state",
"of",
"the",
"collection"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/associations/association_collection.rb#L100-L110 | train |
chicks/sugarcrm | lib/sugarcrm/associations/association_collection.rb | SugarCRM.AssociationCollection.load_associated_records | def load_associated_records
array = @owner.class.session.connection.get_relationships(@owner.class._module.name, @owner.id, @association.to_s)
@loaded = true
# we use original to track the state of the collection at start
@collection = Array.wrap(array).dup
@original = Array.wrap(array).freeze
end | ruby | def load_associated_records
array = @owner.class.session.connection.get_relationships(@owner.class._module.name, @owner.id, @association.to_s)
@loaded = true
# we use original to track the state of the collection at start
@collection = Array.wrap(array).dup
@original = Array.wrap(array).freeze
end | [
"def",
"load_associated_records",
"array",
"=",
"@owner",
".",
"class",
".",
"session",
".",
"connection",
".",
"get_relationships",
"(",
"@owner",
".",
"class",
".",
"_module",
".",
"name",
",",
"@owner",
".",
"id",
",",
"@association",
".",
"to_s",
")",
"@loaded",
"=",
"true",
"@collection",
"=",
"Array",
".",
"wrap",
"(",
"array",
")",
".",
"dup",
"@original",
"=",
"Array",
".",
"wrap",
"(",
"array",
")",
".",
"freeze",
"end"
]
| Loads related records for the given association | [
"Loads",
"related",
"records",
"for",
"the",
"given",
"association"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/associations/association_collection.rb#L115-L121 | train |
chicks/sugarcrm | lib/sugarcrm/connection/helper.rb | SugarCRM.Connection.class_for | def class_for(module_name)
begin
class_const = @session.namespace_const.const_get(module_name.classify)
klass = class_const.new
rescue NameError
raise InvalidModule, "Module: #{module_name} is not registered"
end
end | ruby | def class_for(module_name)
begin
class_const = @session.namespace_const.const_get(module_name.classify)
klass = class_const.new
rescue NameError
raise InvalidModule, "Module: #{module_name} is not registered"
end
end | [
"def",
"class_for",
"(",
"module_name",
")",
"begin",
"class_const",
"=",
"@session",
".",
"namespace_const",
".",
"const_get",
"(",
"module_name",
".",
"classify",
")",
"klass",
"=",
"class_const",
".",
"new",
"rescue",
"NameError",
"raise",
"InvalidModule",
",",
"\"Module: #{module_name} is not registered\"",
"end",
"end"
]
| Returns an instance of class for the provided module name | [
"Returns",
"an",
"instance",
"of",
"class",
"for",
"the",
"provided",
"module",
"name"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/connection/helper.rb#L32-L39 | train |
chicks/sugarcrm | lib/sugarcrm/connection/connection.rb | SugarCRM.Connection.send! | def send!(method, json, max_retry=3)
if max_retry == 0
raise SugarCRM::RetryLimitExceeded, "SugarCRM::Connection Errors: \n#{@errors.reverse.join "\n\s\s"}"
end
@request = SugarCRM::Request.new(@url, method, json, @options[:debug])
# Send Ze Request
begin
if @request.length > 3900
@response = @connection.post(@url.path, @request)
else
@response = @connection.get(@url.path.dup + "?" + @request.to_s)
end
return handle_response
# Timeouts are usually a server side issue
rescue Timeout::Error => error
@errors << error
send!(method, json, max_retry.pred)
# Lower level errors requiring a reconnect
rescue Errno::ECONNRESET, Errno::ECONNABORTED, Errno::EPIPE, EOFError => error
@errors << error
reconnect!
send!(method, json, max_retry.pred)
# Handle invalid sessions
rescue SugarCRM::InvalidSession => error
@errors << error
old_session = @sugar_session_id.dup
login!
# Update the session id in the request that we want to retry.
json.gsub!(old_session, @sugar_session_id)
send!(method, json, max_retry.pred)
end
end | ruby | def send!(method, json, max_retry=3)
if max_retry == 0
raise SugarCRM::RetryLimitExceeded, "SugarCRM::Connection Errors: \n#{@errors.reverse.join "\n\s\s"}"
end
@request = SugarCRM::Request.new(@url, method, json, @options[:debug])
# Send Ze Request
begin
if @request.length > 3900
@response = @connection.post(@url.path, @request)
else
@response = @connection.get(@url.path.dup + "?" + @request.to_s)
end
return handle_response
# Timeouts are usually a server side issue
rescue Timeout::Error => error
@errors << error
send!(method, json, max_retry.pred)
# Lower level errors requiring a reconnect
rescue Errno::ECONNRESET, Errno::ECONNABORTED, Errno::EPIPE, EOFError => error
@errors << error
reconnect!
send!(method, json, max_retry.pred)
# Handle invalid sessions
rescue SugarCRM::InvalidSession => error
@errors << error
old_session = @sugar_session_id.dup
login!
# Update the session id in the request that we want to retry.
json.gsub!(old_session, @sugar_session_id)
send!(method, json, max_retry.pred)
end
end | [
"def",
"send!",
"(",
"method",
",",
"json",
",",
"max_retry",
"=",
"3",
")",
"if",
"max_retry",
"==",
"0",
"raise",
"SugarCRM",
"::",
"RetryLimitExceeded",
",",
"\"SugarCRM::Connection Errors: \\n#{@errors.reverse.join \"\\n\\s\\s\"}\"",
"end",
"@request",
"=",
"SugarCRM",
"::",
"Request",
".",
"new",
"(",
"@url",
",",
"method",
",",
"json",
",",
"@options",
"[",
":debug",
"]",
")",
"begin",
"if",
"@request",
".",
"length",
">",
"3900",
"@response",
"=",
"@connection",
".",
"post",
"(",
"@url",
".",
"path",
",",
"@request",
")",
"else",
"@response",
"=",
"@connection",
".",
"get",
"(",
"@url",
".",
"path",
".",
"dup",
"+",
"\"?\"",
"+",
"@request",
".",
"to_s",
")",
"end",
"return",
"handle_response",
"rescue",
"Timeout",
"::",
"Error",
"=>",
"error",
"@errors",
"<<",
"error",
"send!",
"(",
"method",
",",
"json",
",",
"max_retry",
".",
"pred",
")",
"rescue",
"Errno",
"::",
"ECONNRESET",
",",
"Errno",
"::",
"ECONNABORTED",
",",
"Errno",
"::",
"EPIPE",
",",
"EOFError",
"=>",
"error",
"@errors",
"<<",
"error",
"reconnect!",
"send!",
"(",
"method",
",",
"json",
",",
"max_retry",
".",
"pred",
")",
"rescue",
"SugarCRM",
"::",
"InvalidSession",
"=>",
"error",
"@errors",
"<<",
"error",
"old_session",
"=",
"@sugar_session_id",
".",
"dup",
"login!",
"json",
".",
"gsub!",
"(",
"old_session",
",",
"@sugar_session_id",
")",
"send!",
"(",
"method",
",",
"json",
",",
"max_retry",
".",
"pred",
")",
"end",
"end"
]
| Send a request to the Sugar Instance | [
"Send",
"a",
"request",
"to",
"the",
"Sugar",
"Instance"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/connection/connection.rb#L76-L107 | train |
chicks/sugarcrm | lib/sugarcrm/session.rb | SugarCRM.Session.reconnect | def reconnect(url=nil, user=nil, pass=nil, opts={})
@connection_pool.disconnect!
connect(url, user, pass, opts)
end | ruby | def reconnect(url=nil, user=nil, pass=nil, opts={})
@connection_pool.disconnect!
connect(url, user, pass, opts)
end | [
"def",
"reconnect",
"(",
"url",
"=",
"nil",
",",
"user",
"=",
"nil",
",",
"pass",
"=",
"nil",
",",
"opts",
"=",
"{",
"}",
")",
"@connection_pool",
".",
"disconnect!",
"connect",
"(",
"url",
",",
"user",
",",
"pass",
",",
"opts",
")",
"end"
]
| Re-uses this session and namespace if the user wants to connect with different credentials | [
"Re",
"-",
"uses",
"this",
"session",
"and",
"namespace",
"if",
"the",
"user",
"wants",
"to",
"connect",
"with",
"different",
"credentials"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/session.rb#L76-L79 | train |
chicks/sugarcrm | lib/sugarcrm/session.rb | SugarCRM.Session.load_extensions | def load_extensions
self.class.validate_path @extensions_path
Dir[File.join(@extensions_path, '**', '*.rb').to_s].each { |f| load(f) }
end | ruby | def load_extensions
self.class.validate_path @extensions_path
Dir[File.join(@extensions_path, '**', '*.rb').to_s].each { |f| load(f) }
end | [
"def",
"load_extensions",
"self",
".",
"class",
".",
"validate_path",
"@extensions_path",
"Dir",
"[",
"File",
".",
"join",
"(",
"@extensions_path",
",",
"'**'",
",",
"'*.rb'",
")",
".",
"to_s",
"]",
".",
"each",
"{",
"|",
"f",
"|",
"load",
"(",
"f",
")",
"}",
"end"
]
| load all the monkey patch extension files in the provided folder | [
"load",
"all",
"the",
"monkey",
"patch",
"extension",
"files",
"in",
"the",
"provided",
"folder"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/session.rb#L204-L207 | train |
chicks/sugarcrm | lib/sugarcrm/associations/association.rb | SugarCRM.Association.include? | def include?(attribute)
return true if attribute.class == @target
return true if attribute == link_field
return true if methods.include? attribute
false
end | ruby | def include?(attribute)
return true if attribute.class == @target
return true if attribute == link_field
return true if methods.include? attribute
false
end | [
"def",
"include?",
"(",
"attribute",
")",
"return",
"true",
"if",
"attribute",
".",
"class",
"==",
"@target",
"return",
"true",
"if",
"attribute",
"==",
"link_field",
"return",
"true",
"if",
"methods",
".",
"include?",
"attribute",
"false",
"end"
]
| Creates a new instance of an Association
Returns true if the association includes an attribute that matches
the provided string | [
"Creates",
"a",
"new",
"instance",
"of",
"an",
"Association",
"Returns",
"true",
"if",
"the",
"association",
"includes",
"an",
"attribute",
"that",
"matches",
"the",
"provided",
"string"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/associations/association.rb#L27-L32 | train |
chicks/sugarcrm | lib/sugarcrm/associations/association.rb | SugarCRM.Association.resolve_target | def resolve_target
# Use the link_field name first
klass = @link_field.singularize.camelize
namespace = @owner.class.session.namespace_const
return namespace.const_get(klass) if namespace.const_defined? klass
# Use the link_field attribute "module"
if @attributes["module"].length > 0
module_name = SugarCRM::Module.find(@attributes["module"], @owner.class.session)
return namespace.const_get(module_name.klass) if module_name && namespace.const_defined?(module_name.klass)
end
# Use the "relationship" target
if @attributes["relationship"].length > 0
klass = @relationship[:target][:name].singularize.camelize
return namespace.const_get(klass) if namespace.const_defined? klass
end
false
end | ruby | def resolve_target
# Use the link_field name first
klass = @link_field.singularize.camelize
namespace = @owner.class.session.namespace_const
return namespace.const_get(klass) if namespace.const_defined? klass
# Use the link_field attribute "module"
if @attributes["module"].length > 0
module_name = SugarCRM::Module.find(@attributes["module"], @owner.class.session)
return namespace.const_get(module_name.klass) if module_name && namespace.const_defined?(module_name.klass)
end
# Use the "relationship" target
if @attributes["relationship"].length > 0
klass = @relationship[:target][:name].singularize.camelize
return namespace.const_get(klass) if namespace.const_defined? klass
end
false
end | [
"def",
"resolve_target",
"klass",
"=",
"@link_field",
".",
"singularize",
".",
"camelize",
"namespace",
"=",
"@owner",
".",
"class",
".",
"session",
".",
"namespace_const",
"return",
"namespace",
".",
"const_get",
"(",
"klass",
")",
"if",
"namespace",
".",
"const_defined?",
"klass",
"if",
"@attributes",
"[",
"\"module\"",
"]",
".",
"length",
">",
"0",
"module_name",
"=",
"SugarCRM",
"::",
"Module",
".",
"find",
"(",
"@attributes",
"[",
"\"module\"",
"]",
",",
"@owner",
".",
"class",
".",
"session",
")",
"return",
"namespace",
".",
"const_get",
"(",
"module_name",
".",
"klass",
")",
"if",
"module_name",
"&&",
"namespace",
".",
"const_defined?",
"(",
"module_name",
".",
"klass",
")",
"end",
"if",
"@attributes",
"[",
"\"relationship\"",
"]",
".",
"length",
">",
"0",
"klass",
"=",
"@relationship",
"[",
":target",
"]",
"[",
":name",
"]",
".",
"singularize",
".",
"camelize",
"return",
"namespace",
".",
"const_get",
"(",
"klass",
")",
"if",
"namespace",
".",
"const_defined?",
"klass",
"end",
"false",
"end"
]
| Attempts to determine the class of the target in the association | [
"Attempts",
"to",
"determine",
"the",
"class",
"of",
"the",
"target",
"in",
"the",
"association"
]
| 360060139b13788a7ec462c6ecd08d3dbda9849a | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/associations/association.rb#L67-L83 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.