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 |
---|---|---|---|---|---|---|---|---|---|---|---|
visoft/ruby_odata | lib/ruby_odata/service.rb | OData.Service.link_child_to_parent | def link_child_to_parent(operation)
child_collection = operation.klass.send("#{operation.klass_name}") || []
child_collection << operation.child_klass
operation.klass.send("#{operation.klass_name}=", child_collection)
# Attach the parent to the child
parent_meta = @class_metadata[operation.klass.class.to_s][operation.klass_name]
child_meta = @class_metadata[operation.child_klass.class.to_s]
# Find the matching relationship on the child object
child_properties = Helpers.normalize_to_hash(
child_meta.select { |k, prop|
prop.nav_prop &&
prop.association.relationship == parent_meta.association.relationship })
child_property_to_set = child_properties.keys.first # There should be only one match
# TODO: Handle many to many scenarios where the child property is an enumerable
operation.child_klass.send("#{child_property_to_set}=", operation.klass)
end | ruby | def link_child_to_parent(operation)
child_collection = operation.klass.send("#{operation.klass_name}") || []
child_collection << operation.child_klass
operation.klass.send("#{operation.klass_name}=", child_collection)
# Attach the parent to the child
parent_meta = @class_metadata[operation.klass.class.to_s][operation.klass_name]
child_meta = @class_metadata[operation.child_klass.class.to_s]
# Find the matching relationship on the child object
child_properties = Helpers.normalize_to_hash(
child_meta.select { |k, prop|
prop.nav_prop &&
prop.association.relationship == parent_meta.association.relationship })
child_property_to_set = child_properties.keys.first # There should be only one match
# TODO: Handle many to many scenarios where the child property is an enumerable
operation.child_klass.send("#{child_property_to_set}=", operation.klass)
end | [
"def",
"link_child_to_parent",
"(",
"operation",
")",
"child_collection",
"=",
"operation",
".",
"klass",
".",
"send",
"(",
"\"#{operation.klass_name}\"",
")",
"||",
"[",
"]",
"child_collection",
"<<",
"operation",
".",
"child_klass",
"operation",
".",
"klass",
".",
"send",
"(",
"\"#{operation.klass_name}=\"",
",",
"child_collection",
")",
"parent_meta",
"=",
"@class_metadata",
"[",
"operation",
".",
"klass",
".",
"class",
".",
"to_s",
"]",
"[",
"operation",
".",
"klass_name",
"]",
"child_meta",
"=",
"@class_metadata",
"[",
"operation",
".",
"child_klass",
".",
"class",
".",
"to_s",
"]",
"child_properties",
"=",
"Helpers",
".",
"normalize_to_hash",
"(",
"child_meta",
".",
"select",
"{",
"|",
"k",
",",
"prop",
"|",
"prop",
".",
"nav_prop",
"&&",
"prop",
".",
"association",
".",
"relationship",
"==",
"parent_meta",
".",
"association",
".",
"relationship",
"}",
")",
"child_property_to_set",
"=",
"child_properties",
".",
"keys",
".",
"first",
"operation",
".",
"child_klass",
".",
"send",
"(",
"\"#{child_property_to_set}=\"",
",",
"operation",
".",
"klass",
")",
"end"
]
| Used to link a child object to its parent and vice-versa after a add_link operation | [
"Used",
"to",
"link",
"a",
"child",
"object",
"to",
"its",
"parent",
"and",
"vice",
"-",
"versa",
"after",
"a",
"add_link",
"operation"
]
| ca3d441494aa2f745c7f7fb2cd90173956f73663 | https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L580-L597 | train |
visoft/ruby_odata | lib/ruby_odata/service.rb | OData.Service.fill_complex_type_properties | def fill_complex_type_properties(complex_type_xml, klass)
properties = complex_type_xml.xpath(".//*")
properties.each do |prop|
klass.send "#{prop.name}=", parse_value_xml(prop)
end
end | ruby | def fill_complex_type_properties(complex_type_xml, klass)
properties = complex_type_xml.xpath(".//*")
properties.each do |prop|
klass.send "#{prop.name}=", parse_value_xml(prop)
end
end | [
"def",
"fill_complex_type_properties",
"(",
"complex_type_xml",
",",
"klass",
")",
"properties",
"=",
"complex_type_xml",
".",
"xpath",
"(",
"\".//*\"",
")",
"properties",
".",
"each",
"do",
"|",
"prop",
"|",
"klass",
".",
"send",
"\"#{prop.name}=\"",
",",
"parse_value_xml",
"(",
"prop",
")",
"end",
"end"
]
| Helper method for complex_type_to_class | [
"Helper",
"method",
"for",
"complex_type_to_class"
]
| ca3d441494aa2f745c7f7fb2cd90173956f73663 | https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L736-L741 | train |
visoft/ruby_odata | lib/ruby_odata/service.rb | OData.Service.parse_date | def parse_date(sdate)
# Assume this is UTC if no timezone is specified
sdate = sdate + "Z" unless sdate.match(/Z|([+|-]\d{2}:\d{2})$/)
# This is to handle older versions of Ruby (e.g. ruby 1.8.7 (2010-12-23 patchlevel 330) [i386-mingw32])
# See http://makandra.com/notes/1017-maximum-representable-value-for-a-ruby-time-object
# In recent versions of Ruby, Time has a much larger range
begin
result = Time.parse(sdate)
rescue ArgumentError
result = DateTime.parse(sdate)
end
return result
end | ruby | def parse_date(sdate)
# Assume this is UTC if no timezone is specified
sdate = sdate + "Z" unless sdate.match(/Z|([+|-]\d{2}:\d{2})$/)
# This is to handle older versions of Ruby (e.g. ruby 1.8.7 (2010-12-23 patchlevel 330) [i386-mingw32])
# See http://makandra.com/notes/1017-maximum-representable-value-for-a-ruby-time-object
# In recent versions of Ruby, Time has a much larger range
begin
result = Time.parse(sdate)
rescue ArgumentError
result = DateTime.parse(sdate)
end
return result
end | [
"def",
"parse_date",
"(",
"sdate",
")",
"sdate",
"=",
"sdate",
"+",
"\"Z\"",
"unless",
"sdate",
".",
"match",
"(",
"/",
"\\d",
"\\d",
"/",
")",
"begin",
"result",
"=",
"Time",
".",
"parse",
"(",
"sdate",
")",
"rescue",
"ArgumentError",
"result",
"=",
"DateTime",
".",
"parse",
"(",
"sdate",
")",
"end",
"return",
"result",
"end"
]
| Field Converters
Handles parsing datetimes from a string | [
"Field",
"Converters",
"Handles",
"parsing",
"datetimes",
"from",
"a",
"string"
]
| ca3d441494aa2f745c7f7fb2cd90173956f73663 | https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L746-L760 | train |
visoft/ruby_odata | lib/ruby_odata/service.rb | OData.Service.parse_value_xml | def parse_value_xml(property_xml)
property_type = Helpers.get_namespaced_attribute(property_xml, 'type', 'm')
property_null = Helpers.get_namespaced_attribute(property_xml, 'null', 'm')
if property_type.nil? || (property_type && property_type.match(/^Edm/))
return parse_value(property_xml.content, property_type, property_null)
end
complex_type_to_class(property_xml)
end | ruby | def parse_value_xml(property_xml)
property_type = Helpers.get_namespaced_attribute(property_xml, 'type', 'm')
property_null = Helpers.get_namespaced_attribute(property_xml, 'null', 'm')
if property_type.nil? || (property_type && property_type.match(/^Edm/))
return parse_value(property_xml.content, property_type, property_null)
end
complex_type_to_class(property_xml)
end | [
"def",
"parse_value_xml",
"(",
"property_xml",
")",
"property_type",
"=",
"Helpers",
".",
"get_namespaced_attribute",
"(",
"property_xml",
",",
"'type'",
",",
"'m'",
")",
"property_null",
"=",
"Helpers",
".",
"get_namespaced_attribute",
"(",
"property_xml",
",",
"'null'",
",",
"'m'",
")",
"if",
"property_type",
".",
"nil?",
"||",
"(",
"property_type",
"&&",
"property_type",
".",
"match",
"(",
"/",
"/",
")",
")",
"return",
"parse_value",
"(",
"property_xml",
".",
"content",
",",
"property_type",
",",
"property_null",
")",
"end",
"complex_type_to_class",
"(",
"property_xml",
")",
"end"
]
| Parses a value into the proper type based on an xml property element | [
"Parses",
"a",
"value",
"into",
"the",
"proper",
"type",
"based",
"on",
"an",
"xml",
"property",
"element"
]
| ca3d441494aa2f745c7f7fb2cd90173956f73663 | https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L763-L772 | train |
visoft/ruby_odata | lib/ruby_odata/service.rb | OData.Service.parse_primative_type | def parse_primative_type(value, return_type)
return value.to_i if return_type == Fixnum
return value.to_d if return_type == Float
return parse_date(value.to_s) if return_type == Time
return value.to_s
end | ruby | def parse_primative_type(value, return_type)
return value.to_i if return_type == Fixnum
return value.to_d if return_type == Float
return parse_date(value.to_s) if return_type == Time
return value.to_s
end | [
"def",
"parse_primative_type",
"(",
"value",
",",
"return_type",
")",
"return",
"value",
".",
"to_i",
"if",
"return_type",
"==",
"Fixnum",
"return",
"value",
".",
"to_d",
"if",
"return_type",
"==",
"Float",
"return",
"parse_date",
"(",
"value",
".",
"to_s",
")",
"if",
"return_type",
"==",
"Time",
"return",
"value",
".",
"to_s",
"end"
]
| Parses a value into the proper type based on a specified return type | [
"Parses",
"a",
"value",
"into",
"the",
"proper",
"type",
"based",
"on",
"a",
"specified",
"return",
"type"
]
| ca3d441494aa2f745c7f7fb2cd90173956f73663 | https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L796-L801 | train |
visoft/ruby_odata | lib/ruby_odata/service.rb | OData.Service.execute_import_function | def execute_import_function(name, *args)
func = @function_imports[name]
# Check the args making sure that more weren't passed in than the function needs
param_count = func[:parameters].nil? ? 0 : func[:parameters].count
arg_count = args.nil? ? 0 : args[0].count
if arg_count > param_count
raise ArgumentError, "wrong number of arguments (#{arg_count} for #{param_count})"
end
# Convert the parameters to a hash
params = {}
func[:parameters].keys.each_with_index { |key, i| params[key] = args[0][i] } unless func[:parameters].nil?
function_uri = build_function_import_uri(name, params)
result = OData::Resource.new(function_uri, @rest_options).send(func[:http_method].downcase, {})
# Is this a 204 (No content) result?
return true if result.status == 204
# No? Then we need to parse the results. There are 4 kinds...
if func[:return_type] == Array
# a collection of entites
return build_classes_from_result(result.body) if @classes.include?(func[:inner_return_type].to_s)
# a collection of native types
elements = Nokogiri::XML(result.body).xpath("//ds:element", @ds_namespaces)
results = []
elements.each do |e|
results << parse_primative_type(e.content, func[:inner_return_type])
end
return results
end
# a single entity
if @classes.include?(func[:return_type].to_s)
entry = Nokogiri::XML(result.body).xpath("atom:entry[not(ancestor::atom:entry)]", @ds_namespaces)
return entry_to_class(entry)
end
# or a single native type
unless func[:return_type].nil?
e = Nokogiri::XML(result.body).xpath("/*").first
return parse_primative_type(e.content, func[:return_type])
end
# Nothing could be parsed, so just return if we got a 200 or not
return (result.status == 200)
end | ruby | def execute_import_function(name, *args)
func = @function_imports[name]
# Check the args making sure that more weren't passed in than the function needs
param_count = func[:parameters].nil? ? 0 : func[:parameters].count
arg_count = args.nil? ? 0 : args[0].count
if arg_count > param_count
raise ArgumentError, "wrong number of arguments (#{arg_count} for #{param_count})"
end
# Convert the parameters to a hash
params = {}
func[:parameters].keys.each_with_index { |key, i| params[key] = args[0][i] } unless func[:parameters].nil?
function_uri = build_function_import_uri(name, params)
result = OData::Resource.new(function_uri, @rest_options).send(func[:http_method].downcase, {})
# Is this a 204 (No content) result?
return true if result.status == 204
# No? Then we need to parse the results. There are 4 kinds...
if func[:return_type] == Array
# a collection of entites
return build_classes_from_result(result.body) if @classes.include?(func[:inner_return_type].to_s)
# a collection of native types
elements = Nokogiri::XML(result.body).xpath("//ds:element", @ds_namespaces)
results = []
elements.each do |e|
results << parse_primative_type(e.content, func[:inner_return_type])
end
return results
end
# a single entity
if @classes.include?(func[:return_type].to_s)
entry = Nokogiri::XML(result.body).xpath("atom:entry[not(ancestor::atom:entry)]", @ds_namespaces)
return entry_to_class(entry)
end
# or a single native type
unless func[:return_type].nil?
e = Nokogiri::XML(result.body).xpath("/*").first
return parse_primative_type(e.content, func[:return_type])
end
# Nothing could be parsed, so just return if we got a 200 or not
return (result.status == 200)
end | [
"def",
"execute_import_function",
"(",
"name",
",",
"*",
"args",
")",
"func",
"=",
"@function_imports",
"[",
"name",
"]",
"param_count",
"=",
"func",
"[",
":parameters",
"]",
".",
"nil?",
"?",
"0",
":",
"func",
"[",
":parameters",
"]",
".",
"count",
"arg_count",
"=",
"args",
".",
"nil?",
"?",
"0",
":",
"args",
"[",
"0",
"]",
".",
"count",
"if",
"arg_count",
">",
"param_count",
"raise",
"ArgumentError",
",",
"\"wrong number of arguments (#{arg_count} for #{param_count})\"",
"end",
"params",
"=",
"{",
"}",
"func",
"[",
":parameters",
"]",
".",
"keys",
".",
"each_with_index",
"{",
"|",
"key",
",",
"i",
"|",
"params",
"[",
"key",
"]",
"=",
"args",
"[",
"0",
"]",
"[",
"i",
"]",
"}",
"unless",
"func",
"[",
":parameters",
"]",
".",
"nil?",
"function_uri",
"=",
"build_function_import_uri",
"(",
"name",
",",
"params",
")",
"result",
"=",
"OData",
"::",
"Resource",
".",
"new",
"(",
"function_uri",
",",
"@rest_options",
")",
".",
"send",
"(",
"func",
"[",
":http_method",
"]",
".",
"downcase",
",",
"{",
"}",
")",
"return",
"true",
"if",
"result",
".",
"status",
"==",
"204",
"if",
"func",
"[",
":return_type",
"]",
"==",
"Array",
"return",
"build_classes_from_result",
"(",
"result",
".",
"body",
")",
"if",
"@classes",
".",
"include?",
"(",
"func",
"[",
":inner_return_type",
"]",
".",
"to_s",
")",
"elements",
"=",
"Nokogiri",
"::",
"XML",
"(",
"result",
".",
"body",
")",
".",
"xpath",
"(",
"\"//ds:element\"",
",",
"@ds_namespaces",
")",
"results",
"=",
"[",
"]",
"elements",
".",
"each",
"do",
"|",
"e",
"|",
"results",
"<<",
"parse_primative_type",
"(",
"e",
".",
"content",
",",
"func",
"[",
":inner_return_type",
"]",
")",
"end",
"return",
"results",
"end",
"if",
"@classes",
".",
"include?",
"(",
"func",
"[",
":return_type",
"]",
".",
"to_s",
")",
"entry",
"=",
"Nokogiri",
"::",
"XML",
"(",
"result",
".",
"body",
")",
".",
"xpath",
"(",
"\"atom:entry[not(ancestor::atom:entry)]\"",
",",
"@ds_namespaces",
")",
"return",
"entry_to_class",
"(",
"entry",
")",
"end",
"unless",
"func",
"[",
":return_type",
"]",
".",
"nil?",
"e",
"=",
"Nokogiri",
"::",
"XML",
"(",
"result",
".",
"body",
")",
".",
"xpath",
"(",
"\"/*\"",
")",
".",
"first",
"return",
"parse_primative_type",
"(",
"e",
".",
"content",
",",
"func",
"[",
":return_type",
"]",
")",
"end",
"return",
"(",
"result",
".",
"status",
"==",
"200",
")",
"end"
]
| Method Missing Handlers
Executes an import function | [
"Method",
"Missing",
"Handlers",
"Executes",
"an",
"import",
"function"
]
| ca3d441494aa2f745c7f7fb2cd90173956f73663 | https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L815-L862 | train |
visoft/ruby_odata | features/support/pickle.rb | Pickle.Session.model_with_associations | def model_with_associations(name)
model = created_model(name)
return nil unless model
OData::PickleAdapter.get_model(model.class, model.id, true)
end | ruby | def model_with_associations(name)
model = created_model(name)
return nil unless model
OData::PickleAdapter.get_model(model.class, model.id, true)
end | [
"def",
"model_with_associations",
"(",
"name",
")",
"model",
"=",
"created_model",
"(",
"name",
")",
"return",
"nil",
"unless",
"model",
"OData",
"::",
"PickleAdapter",
".",
"get_model",
"(",
"model",
".",
"class",
",",
"model",
".",
"id",
",",
"true",
")",
"end"
]
| return a newly selected model with the navigation properties expanded | [
"return",
"a",
"newly",
"selected",
"model",
"with",
"the",
"navigation",
"properties",
"expanded"
]
| ca3d441494aa2f745c7f7fb2cd90173956f73663 | https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/features/support/pickle.rb#L87-L91 | train |
visoft/ruby_odata | lib/ruby_odata/class_builder.rb | OData.ClassBuilder.build | def build
# return if already built
return @klass unless @klass.nil?
# need the class name to build class
return nil if @klass_name.nil?
# return if we can find constant corresponding to class name
already_defined = eval("defined?(#{@klass_name}) == 'constant' and #{@klass_name}.class == Class")
if already_defined
@klass = @klass_name.constantize
return @klass
end
if @namespace
namespaces = @namespace.split(/\.|::/)
namespaces.each_with_index do |ns, index|
if index == 0
next if Object.const_defined? ns
Object.const_set(ns, Module.new)
else
current_ns = namespaces[0..index-1].join '::'
next if eval "#{current_ns}.const_defined? '#{ns}'"
eval "#{current_ns}.const_set('#{ns}', Module.new)"
end
end
klass_constant = @klass_name.split('::').last
eval "#{namespaces.join '::'}.const_set('#{klass_constant}', Class.new.extend(ActiveSupport::JSON))"
else
Object.const_set(@klass_name, Class.new.extend(ActiveSupport::JSON))
end
@klass = @klass_name.constantize
@klass.class_eval do
include OData
end
add_initializer(@klass)
add_methods(@klass)
add_nav_props(@klass)
add_class_methods(@klass)
return @klass
end | ruby | def build
# return if already built
return @klass unless @klass.nil?
# need the class name to build class
return nil if @klass_name.nil?
# return if we can find constant corresponding to class name
already_defined = eval("defined?(#{@klass_name}) == 'constant' and #{@klass_name}.class == Class")
if already_defined
@klass = @klass_name.constantize
return @klass
end
if @namespace
namespaces = @namespace.split(/\.|::/)
namespaces.each_with_index do |ns, index|
if index == 0
next if Object.const_defined? ns
Object.const_set(ns, Module.new)
else
current_ns = namespaces[0..index-1].join '::'
next if eval "#{current_ns}.const_defined? '#{ns}'"
eval "#{current_ns}.const_set('#{ns}', Module.new)"
end
end
klass_constant = @klass_name.split('::').last
eval "#{namespaces.join '::'}.const_set('#{klass_constant}', Class.new.extend(ActiveSupport::JSON))"
else
Object.const_set(@klass_name, Class.new.extend(ActiveSupport::JSON))
end
@klass = @klass_name.constantize
@klass.class_eval do
include OData
end
add_initializer(@klass)
add_methods(@klass)
add_nav_props(@klass)
add_class_methods(@klass)
return @klass
end | [
"def",
"build",
"return",
"@klass",
"unless",
"@klass",
".",
"nil?",
"return",
"nil",
"if",
"@klass_name",
".",
"nil?",
"already_defined",
"=",
"eval",
"(",
"\"defined?(#{@klass_name}) == 'constant' and #{@klass_name}.class == Class\"",
")",
"if",
"already_defined",
"@klass",
"=",
"@klass_name",
".",
"constantize",
"return",
"@klass",
"end",
"if",
"@namespace",
"namespaces",
"=",
"@namespace",
".",
"split",
"(",
"/",
"\\.",
"/",
")",
"namespaces",
".",
"each_with_index",
"do",
"|",
"ns",
",",
"index",
"|",
"if",
"index",
"==",
"0",
"next",
"if",
"Object",
".",
"const_defined?",
"ns",
"Object",
".",
"const_set",
"(",
"ns",
",",
"Module",
".",
"new",
")",
"else",
"current_ns",
"=",
"namespaces",
"[",
"0",
"..",
"index",
"-",
"1",
"]",
".",
"join",
"'::'",
"next",
"if",
"eval",
"\"#{current_ns}.const_defined? '#{ns}'\"",
"eval",
"\"#{current_ns}.const_set('#{ns}', Module.new)\"",
"end",
"end",
"klass_constant",
"=",
"@klass_name",
".",
"split",
"(",
"'::'",
")",
".",
"last",
"eval",
"\"#{namespaces.join '::'}.const_set('#{klass_constant}', Class.new.extend(ActiveSupport::JSON))\"",
"else",
"Object",
".",
"const_set",
"(",
"@klass_name",
",",
"Class",
".",
"new",
".",
"extend",
"(",
"ActiveSupport",
"::",
"JSON",
")",
")",
"end",
"@klass",
"=",
"@klass_name",
".",
"constantize",
"@klass",
".",
"class_eval",
"do",
"include",
"OData",
"end",
"add_initializer",
"(",
"@klass",
")",
"add_methods",
"(",
"@klass",
")",
"add_nav_props",
"(",
"@klass",
")",
"add_class_methods",
"(",
"@klass",
")",
"return",
"@klass",
"end"
]
| Creates a new instance of the ClassBuilder class
@param [String] klass_name the name/type of the class to create
@param [Array] methods the accessor methods to add to the class
@param [Array] nav_props the accessor methods to add for navigation properties
@param [Service] context the service context that this entity belongs to
@param [String, nil] namespace optional namespace to create the classes in
Returns a dynamically generated class definition based on the constructor parameters | [
"Creates",
"a",
"new",
"instance",
"of",
"the",
"ClassBuilder",
"class"
]
| ca3d441494aa2f745c7f7fb2cd90173956f73663 | https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/class_builder.rb#L20-L65 | train |
visoft/ruby_odata | lib/ruby_odata/query_builder.rb | OData.QueryBuilder.links | def links(navigation_property)
raise OData::NotSupportedError.new("You cannot call both the `links` method and the `count` method in the same query.") if @count
raise OData::NotSupportedError.new("You cannot call both the `links` method and the `select` method in the same query.") unless @select.empty?
@links_navigation_property = navigation_property
self
end | ruby | def links(navigation_property)
raise OData::NotSupportedError.new("You cannot call both the `links` method and the `count` method in the same query.") if @count
raise OData::NotSupportedError.new("You cannot call both the `links` method and the `select` method in the same query.") unless @select.empty?
@links_navigation_property = navigation_property
self
end | [
"def",
"links",
"(",
"navigation_property",
")",
"raise",
"OData",
"::",
"NotSupportedError",
".",
"new",
"(",
"\"You cannot call both the `links` method and the `count` method in the same query.\"",
")",
"if",
"@count",
"raise",
"OData",
"::",
"NotSupportedError",
".",
"new",
"(",
"\"You cannot call both the `links` method and the `select` method in the same query.\"",
")",
"unless",
"@select",
".",
"empty?",
"@links_navigation_property",
"=",
"navigation_property",
"self",
"end"
]
| Used to return links instead of actual objects
@param [String] navigation_property the NavigationProperty name to retrieve the links for
@raise [NotSupportedError] if count has already been called on the query
@example
svc.Categories(1).links("Products")
product_links = svc.execute # => returns URIs for the products under the Category with an ID of 1 | [
"Used",
"to",
"return",
"links",
"instead",
"of",
"actual",
"objects"
]
| ca3d441494aa2f745c7f7fb2cd90173956f73663 | https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/query_builder.rb#L104-L109 | train |
visoft/ruby_odata | lib/ruby_odata/query_builder.rb | OData.QueryBuilder.count | def count
raise OData::NotSupportedError.new("You cannot call both the `links` method and the `count` method in the same query.") if @links_navigation_property
raise OData::NotSupportedError.new("You cannot call both the `select` method and the `count` method in the same query.") unless @select.empty?
@count = true
self
end | ruby | def count
raise OData::NotSupportedError.new("You cannot call both the `links` method and the `count` method in the same query.") if @links_navigation_property
raise OData::NotSupportedError.new("You cannot call both the `select` method and the `count` method in the same query.") unless @select.empty?
@count = true
self
end | [
"def",
"count",
"raise",
"OData",
"::",
"NotSupportedError",
".",
"new",
"(",
"\"You cannot call both the `links` method and the `count` method in the same query.\"",
")",
"if",
"@links_navigation_property",
"raise",
"OData",
"::",
"NotSupportedError",
".",
"new",
"(",
"\"You cannot call both the `select` method and the `count` method in the same query.\"",
")",
"unless",
"@select",
".",
"empty?",
"@count",
"=",
"true",
"self",
"end"
]
| Used to return a count of objects instead of the objects themselves
@raise [NotSupportedError] if links has already been called on the query
@example
svc.Products
svc.count
product_count = svc.execute | [
"Used",
"to",
"return",
"a",
"count",
"of",
"objects",
"instead",
"of",
"the",
"objects",
"themselves"
]
| ca3d441494aa2f745c7f7fb2cd90173956f73663 | https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/query_builder.rb#L119-L125 | train |
visoft/ruby_odata | lib/ruby_odata/query_builder.rb | OData.QueryBuilder.select | def select(*fields)
raise OData::NotSupportedError.new("You cannot call both the `links` method and the `select` method in the same query.") if @links_navigation_property
raise OData::NotSupportedError.new("You cannot call both the `count` method and the `select` method in the same query.") if @count
@select |= fields
expands = fields.find_all { |f| /\// =~ f }
expands.each do |e|
parts = e.split '/'
@expands |= [parts[0...-1].join('/')]
end
self
end | ruby | def select(*fields)
raise OData::NotSupportedError.new("You cannot call both the `links` method and the `select` method in the same query.") if @links_navigation_property
raise OData::NotSupportedError.new("You cannot call both the `count` method and the `select` method in the same query.") if @count
@select |= fields
expands = fields.find_all { |f| /\// =~ f }
expands.each do |e|
parts = e.split '/'
@expands |= [parts[0...-1].join('/')]
end
self
end | [
"def",
"select",
"(",
"*",
"fields",
")",
"raise",
"OData",
"::",
"NotSupportedError",
".",
"new",
"(",
"\"You cannot call both the `links` method and the `select` method in the same query.\"",
")",
"if",
"@links_navigation_property",
"raise",
"OData",
"::",
"NotSupportedError",
".",
"new",
"(",
"\"You cannot call both the `count` method and the `select` method in the same query.\"",
")",
"if",
"@count",
"@select",
"|=",
"fields",
"expands",
"=",
"fields",
".",
"find_all",
"{",
"|",
"f",
"|",
"/",
"\\/",
"/",
"=~",
"f",
"}",
"expands",
".",
"each",
"do",
"|",
"e",
"|",
"parts",
"=",
"e",
".",
"split",
"'/'",
"@expands",
"|=",
"[",
"parts",
"[",
"0",
"...",
"-",
"1",
"]",
".",
"join",
"(",
"'/'",
")",
"]",
"end",
"self",
"end"
]
| Used to customize the properties that are returned for "ad-hoc" queries
@param [Array<String>] properties to return
@example
svc.Products.select('Price', 'Rating') | [
"Used",
"to",
"customize",
"the",
"properties",
"that",
"are",
"returned",
"for",
"ad",
"-",
"hoc",
"queries"
]
| ca3d441494aa2f745c7f7fb2cd90173956f73663 | https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/query_builder.rb#L144-L157 | train |
jaredholdcroft/strava-api-v3 | lib/strava/api/v3/common.rb | Strava::Api::V3.Common.sanitize_request_parameters | def sanitize_request_parameters(parameters)
parameters.reduce({}) do |result, (key, value)|
# if the parameter is an array that contains non-enumerable values,
# turn it into a comma-separated list
# in Ruby 1.8.7, strings are enumerable, but we don't care
if value.is_a?(Array) && value.none? {|entry| entry.is_a?(Enumerable) && !entry.is_a?(String)}
value = value.join(",")
end
value = value.to_time if value.is_a? DateTime
value = value.to_i if value.is_a? Time
result.merge(key => value)
end
end | ruby | def sanitize_request_parameters(parameters)
parameters.reduce({}) do |result, (key, value)|
# if the parameter is an array that contains non-enumerable values,
# turn it into a comma-separated list
# in Ruby 1.8.7, strings are enumerable, but we don't care
if value.is_a?(Array) && value.none? {|entry| entry.is_a?(Enumerable) && !entry.is_a?(String)}
value = value.join(",")
end
value = value.to_time if value.is_a? DateTime
value = value.to_i if value.is_a? Time
result.merge(key => value)
end
end | [
"def",
"sanitize_request_parameters",
"(",
"parameters",
")",
"parameters",
".",
"reduce",
"(",
"{",
"}",
")",
"do",
"|",
"result",
",",
"(",
"key",
",",
"value",
")",
"|",
"if",
"value",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"value",
".",
"none?",
"{",
"|",
"entry",
"|",
"entry",
".",
"is_a?",
"(",
"Enumerable",
")",
"&&",
"!",
"entry",
".",
"is_a?",
"(",
"String",
")",
"}",
"value",
"=",
"value",
".",
"join",
"(",
"\",\"",
")",
"end",
"value",
"=",
"value",
".",
"to_time",
"if",
"value",
".",
"is_a?",
"DateTime",
"value",
"=",
"value",
".",
"to_i",
"if",
"value",
".",
"is_a?",
"Time",
"result",
".",
"merge",
"(",
"key",
"=>",
"value",
")",
"end",
"end"
]
| Sanitizes Ruby objects into Strava-compatible string values.
@param parameters a hash of parameters.
Returns a hash in which values that are arrays of non-enumerable values
(Strings, Symbols, Numbers, etc.) are turned into comma-separated strings. | [
"Sanitizes",
"Ruby",
"objects",
"into",
"Strava",
"-",
"compatible",
"string",
"values",
"."
]
| 13fb1411a8d999b56a3cfe3295e7af8696d8bdcf | https://github.com/jaredholdcroft/strava-api-v3/blob/13fb1411a8d999b56a3cfe3295e7af8696d8bdcf/lib/strava/api/v3/common.rb#L92-L105 | train |
jaredholdcroft/strava-api-v3 | lib/strava/api/v3/activity_extras.rb | Strava::Api::V3.ActivityExtras.list_activity_photos | def list_activity_photos(id, args = {}, options = {}, &block)
args['photo_sources'] = 'true'
# Fetches the connections for given object.
api_call("activities/#{id}/photos", args, 'get', options, &block)
end | ruby | def list_activity_photos(id, args = {}, options = {}, &block)
args['photo_sources'] = 'true'
# Fetches the connections for given object.
api_call("activities/#{id}/photos", args, 'get', options, &block)
end | [
"def",
"list_activity_photos",
"(",
"id",
",",
"args",
"=",
"{",
"}",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"args",
"[",
"'photo_sources'",
"]",
"=",
"'true'",
"api_call",
"(",
"\"activities/#{id}/photos\"",
",",
"args",
",",
"'get'",
",",
"options",
",",
"&",
"block",
")",
"end"
]
| Fetch list of photos from a specific activity, only if it is your activity
See {https://strava.github.io/api/v3/activity_photos/} for full details
@param id activity id
@param args any additional arguments
@param options (see #get_object)
@param block post processing code block
@return an array of photo objects. Both Strava and Instagram photos will be returned | [
"Fetch",
"list",
"of",
"photos",
"from",
"a",
"specific",
"activity",
"only",
"if",
"it",
"is",
"your",
"activity"
]
| 13fb1411a8d999b56a3cfe3295e7af8696d8bdcf | https://github.com/jaredholdcroft/strava-api-v3/blob/13fb1411a8d999b56a3cfe3295e7af8696d8bdcf/lib/strava/api/v3/activity_extras.rb#L47-L51 | train |
jaredholdcroft/strava-api-v3 | lib/strava/api/v3/stream.rb | Strava::Api::V3.Stream.retrieve_activity_streams | def retrieve_activity_streams(id, types, args = {}, options = {}, &block)
# Fetches the connections for given object.
api_call("activities/#{id}/streams/#{types}", args, 'get', options, &block)
end | ruby | def retrieve_activity_streams(id, types, args = {}, options = {}, &block)
# Fetches the connections for given object.
api_call("activities/#{id}/streams/#{types}", args, 'get', options, &block)
end | [
"def",
"retrieve_activity_streams",
"(",
"id",
",",
"types",
",",
"args",
"=",
"{",
"}",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"api_call",
"(",
"\"activities/#{id}/streams/#{types}\"",
",",
"args",
",",
"'get'",
",",
"options",
",",
"&",
"block",
")",
"end"
]
| Fetch information about a stream for a specific activity
See {https://strava.github.io/api/v3/streams/#activity} for full details
@param id activity id
@param args any additional arguments
@param options (see #get_object)
@param block post processing code block
@return an array of unordered stream objects | [
"Fetch",
"information",
"about",
"a",
"stream",
"for",
"a",
"specific",
"activity"
]
| 13fb1411a8d999b56a3cfe3295e7af8696d8bdcf | https://github.com/jaredholdcroft/strava-api-v3/blob/13fb1411a8d999b56a3cfe3295e7af8696d8bdcf/lib/strava/api/v3/stream.rb#L17-L20 | train |
jaredholdcroft/strava-api-v3 | lib/strava/api/v3/stream.rb | Strava::Api::V3.Stream.retrieve_effort_streams | def retrieve_effort_streams(id, types, args = {}, options = {}, &block)
# Fetches the connections for given object.
api_call("segment_efforts/#{id}/streams/#{types}", args, 'get', options, &block)
end | ruby | def retrieve_effort_streams(id, types, args = {}, options = {}, &block)
# Fetches the connections for given object.
api_call("segment_efforts/#{id}/streams/#{types}", args, 'get', options, &block)
end | [
"def",
"retrieve_effort_streams",
"(",
"id",
",",
"types",
",",
"args",
"=",
"{",
"}",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"api_call",
"(",
"\"segment_efforts/#{id}/streams/#{types}\"",
",",
"args",
",",
"'get'",
",",
"options",
",",
"&",
"block",
")",
"end"
]
| Fetch information about a subset of the activity streams that correspond to that effort
See {https://strava.github.io/api/v3/streams/#effort} for full details
@param id effort id
@param args any additional arguments
@param options (see #get_object)
@param block post processing code block
@return an array of unordered stream objects | [
"Fetch",
"information",
"about",
"a",
"subset",
"of",
"the",
"activity",
"streams",
"that",
"correspond",
"to",
"that",
"effort"
]
| 13fb1411a8d999b56a3cfe3295e7af8696d8bdcf | https://github.com/jaredholdcroft/strava-api-v3/blob/13fb1411a8d999b56a3cfe3295e7af8696d8bdcf/lib/strava/api/v3/stream.rb#L32-L35 | train |
jaredholdcroft/strava-api-v3 | lib/strava/api/v3/stream.rb | Strava::Api::V3.Stream.retrieve_segment_streams | def retrieve_segment_streams(id, types, args = {}, options = {}, &block)
# Fetches the connections for given object.
api_call("segments/#{id}/streams/#{types}", args, 'get', options, &block)
end | ruby | def retrieve_segment_streams(id, types, args = {}, options = {}, &block)
# Fetches the connections for given object.
api_call("segments/#{id}/streams/#{types}", args, 'get', options, &block)
end | [
"def",
"retrieve_segment_streams",
"(",
"id",
",",
"types",
",",
"args",
"=",
"{",
"}",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"api_call",
"(",
"\"segments/#{id}/streams/#{types}\"",
",",
"args",
",",
"'get'",
",",
"options",
",",
"&",
"block",
")",
"end"
]
| Fetch information about a stream for a specific segment
See {https://strava.github.io/api/v3/streams/#segment} for full details
@param id segment id
@param args any additional arguments
@param options (see #get_object)
@param block post processing code block
@return an array of unordered stream objects | [
"Fetch",
"information",
"about",
"a",
"stream",
"for",
"a",
"specific",
"segment"
]
| 13fb1411a8d999b56a3cfe3295e7af8696d8bdcf | https://github.com/jaredholdcroft/strava-api-v3/blob/13fb1411a8d999b56a3cfe3295e7af8696d8bdcf/lib/strava/api/v3/stream.rb#L62-L65 | train |
ckruse/CFPropertyList | lib/cfpropertylist/rbCFTypes.rb | CFPropertyList.CFDate.set_value | def set_value(value,format=CFDate::TIMESTAMP_UNIX)
if(format == CFDate::TIMESTAMP_UNIX) then
@value = Time.at(value)
else
@value = Time.at(value + CFDate::DATE_DIFF_APPLE_UNIX)
end
end | ruby | def set_value(value,format=CFDate::TIMESTAMP_UNIX)
if(format == CFDate::TIMESTAMP_UNIX) then
@value = Time.at(value)
else
@value = Time.at(value + CFDate::DATE_DIFF_APPLE_UNIX)
end
end | [
"def",
"set_value",
"(",
"value",
",",
"format",
"=",
"CFDate",
"::",
"TIMESTAMP_UNIX",
")",
"if",
"(",
"format",
"==",
"CFDate",
"::",
"TIMESTAMP_UNIX",
")",
"then",
"@value",
"=",
"Time",
".",
"at",
"(",
"value",
")",
"else",
"@value",
"=",
"Time",
".",
"at",
"(",
"value",
"+",
"CFDate",
"::",
"DATE_DIFF_APPLE_UNIX",
")",
"end",
"end"
]
| set value to defined state
set value with timestamp, either Apple or UNIX | [
"set",
"value",
"to",
"defined",
"state",
"set",
"value",
"with",
"timestamp",
"either",
"Apple",
"or",
"UNIX"
]
| fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134 | https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbCFTypes.rb#L176-L182 | train |
ckruse/CFPropertyList | lib/cfpropertylist/rbCFTypes.rb | CFPropertyList.CFDate.get_value | def get_value(format=CFDate::TIMESTAMP_UNIX)
if(format == CFDate::TIMESTAMP_UNIX) then
@value.to_i
else
@value.to_f - CFDate::DATE_DIFF_APPLE_UNIX
end
end | ruby | def get_value(format=CFDate::TIMESTAMP_UNIX)
if(format == CFDate::TIMESTAMP_UNIX) then
@value.to_i
else
@value.to_f - CFDate::DATE_DIFF_APPLE_UNIX
end
end | [
"def",
"get_value",
"(",
"format",
"=",
"CFDate",
"::",
"TIMESTAMP_UNIX",
")",
"if",
"(",
"format",
"==",
"CFDate",
"::",
"TIMESTAMP_UNIX",
")",
"then",
"@value",
".",
"to_i",
"else",
"@value",
".",
"to_f",
"-",
"CFDate",
"::",
"DATE_DIFF_APPLE_UNIX",
"end",
"end"
]
| get timestamp, either UNIX or Apple timestamp | [
"get",
"timestamp",
"either",
"UNIX",
"or",
"Apple",
"timestamp"
]
| fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134 | https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbCFTypes.rb#L185-L191 | train |
ckruse/CFPropertyList | lib/cfpropertylist/rbCFTypes.rb | CFPropertyList.CFArray.to_xml | def to_xml(parser)
n = parser.new_node('array')
@value.each do |v|
n = parser.append_node(n, v.to_xml(parser))
end
n
end | ruby | def to_xml(parser)
n = parser.new_node('array')
@value.each do |v|
n = parser.append_node(n, v.to_xml(parser))
end
n
end | [
"def",
"to_xml",
"(",
"parser",
")",
"n",
"=",
"parser",
".",
"new_node",
"(",
"'array'",
")",
"@value",
".",
"each",
"do",
"|",
"v",
"|",
"n",
"=",
"parser",
".",
"append_node",
"(",
"n",
",",
"v",
".",
"to_xml",
"(",
"parser",
")",
")",
"end",
"n",
"end"
]
| create a new array CFType
convert to XML | [
"create",
"a",
"new",
"array",
"CFType",
"convert",
"to",
"XML"
]
| fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134 | https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbCFTypes.rb#L278-L284 | train |
ckruse/CFPropertyList | lib/cfpropertylist/rbCFTypes.rb | CFPropertyList.CFDictionary.to_xml | def to_xml(parser)
n = parser.new_node('dict')
@value.each_pair do |key, value|
k = parser.append_node(parser.new_node('key'), parser.new_text(key.to_s))
n = parser.append_node(n, k)
n = parser.append_node(n, value.to_xml(parser))
end
n
end | ruby | def to_xml(parser)
n = parser.new_node('dict')
@value.each_pair do |key, value|
k = parser.append_node(parser.new_node('key'), parser.new_text(key.to_s))
n = parser.append_node(n, k)
n = parser.append_node(n, value.to_xml(parser))
end
n
end | [
"def",
"to_xml",
"(",
"parser",
")",
"n",
"=",
"parser",
".",
"new_node",
"(",
"'dict'",
")",
"@value",
".",
"each_pair",
"do",
"|",
"key",
",",
"value",
"|",
"k",
"=",
"parser",
".",
"append_node",
"(",
"parser",
".",
"new_node",
"(",
"'key'",
")",
",",
"parser",
".",
"new_text",
"(",
"key",
".",
"to_s",
")",
")",
"n",
"=",
"parser",
".",
"append_node",
"(",
"n",
",",
"k",
")",
"n",
"=",
"parser",
".",
"append_node",
"(",
"n",
",",
"value",
".",
"to_xml",
"(",
"parser",
")",
")",
"end",
"n",
"end"
]
| Create new CFDictonary type.
convert to XML | [
"Create",
"new",
"CFDictonary",
"type",
".",
"convert",
"to",
"XML"
]
| fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134 | https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbCFTypes.rb#L305-L313 | train |
ckruse/CFPropertyList | lib/cfpropertylist/rbBinaryCFPropertyList.rb | CFPropertyList.Binary.load | def load(opts)
@unique_table = {}
@count_objects = 0
@object_refs = 0
@written_object_count = 0
@object_table = []
@object_ref_size = 0
@offsets = []
fd = nil
if(opts.has_key?(:file))
fd = File.open(opts[:file],"rb")
file = opts[:file]
else
fd = StringIO.new(opts[:data],"rb")
file = "<string>"
end
# first, we read the trailer: 32 byte from the end
fd.seek(-32,IO::SEEK_END)
buff = fd.read(32)
offset_size, object_ref_size, number_of_objects, top_object, table_offset = buff.unpack "x6CCx4Nx4Nx4N"
# after that, get the offset table
fd.seek(table_offset, IO::SEEK_SET)
coded_offset_table = fd.read(number_of_objects * offset_size)
raise CFFormatError.new("#{file}: Format error!") unless coded_offset_table.bytesize == number_of_objects * offset_size
@count_objects = number_of_objects
# decode offset table
if(offset_size != 3)
formats = ["","C*","n*","","N*"]
@offsets = coded_offset_table.unpack(formats[offset_size])
else
@offsets = coded_offset_table.unpack("C*").each_slice(3).map {
|x,y,z| (x << 16) | (y << 8) | z
}
end
@object_ref_size = object_ref_size
val = read_binary_object_at(file,fd,top_object)
fd.close
val
end | ruby | def load(opts)
@unique_table = {}
@count_objects = 0
@object_refs = 0
@written_object_count = 0
@object_table = []
@object_ref_size = 0
@offsets = []
fd = nil
if(opts.has_key?(:file))
fd = File.open(opts[:file],"rb")
file = opts[:file]
else
fd = StringIO.new(opts[:data],"rb")
file = "<string>"
end
# first, we read the trailer: 32 byte from the end
fd.seek(-32,IO::SEEK_END)
buff = fd.read(32)
offset_size, object_ref_size, number_of_objects, top_object, table_offset = buff.unpack "x6CCx4Nx4Nx4N"
# after that, get the offset table
fd.seek(table_offset, IO::SEEK_SET)
coded_offset_table = fd.read(number_of_objects * offset_size)
raise CFFormatError.new("#{file}: Format error!") unless coded_offset_table.bytesize == number_of_objects * offset_size
@count_objects = number_of_objects
# decode offset table
if(offset_size != 3)
formats = ["","C*","n*","","N*"]
@offsets = coded_offset_table.unpack(formats[offset_size])
else
@offsets = coded_offset_table.unpack("C*").each_slice(3).map {
|x,y,z| (x << 16) | (y << 8) | z
}
end
@object_ref_size = object_ref_size
val = read_binary_object_at(file,fd,top_object)
fd.close
val
end | [
"def",
"load",
"(",
"opts",
")",
"@unique_table",
"=",
"{",
"}",
"@count_objects",
"=",
"0",
"@object_refs",
"=",
"0",
"@written_object_count",
"=",
"0",
"@object_table",
"=",
"[",
"]",
"@object_ref_size",
"=",
"0",
"@offsets",
"=",
"[",
"]",
"fd",
"=",
"nil",
"if",
"(",
"opts",
".",
"has_key?",
"(",
":file",
")",
")",
"fd",
"=",
"File",
".",
"open",
"(",
"opts",
"[",
":file",
"]",
",",
"\"rb\"",
")",
"file",
"=",
"opts",
"[",
":file",
"]",
"else",
"fd",
"=",
"StringIO",
".",
"new",
"(",
"opts",
"[",
":data",
"]",
",",
"\"rb\"",
")",
"file",
"=",
"\"<string>\"",
"end",
"fd",
".",
"seek",
"(",
"-",
"32",
",",
"IO",
"::",
"SEEK_END",
")",
"buff",
"=",
"fd",
".",
"read",
"(",
"32",
")",
"offset_size",
",",
"object_ref_size",
",",
"number_of_objects",
",",
"top_object",
",",
"table_offset",
"=",
"buff",
".",
"unpack",
"\"x6CCx4Nx4Nx4N\"",
"fd",
".",
"seek",
"(",
"table_offset",
",",
"IO",
"::",
"SEEK_SET",
")",
"coded_offset_table",
"=",
"fd",
".",
"read",
"(",
"number_of_objects",
"*",
"offset_size",
")",
"raise",
"CFFormatError",
".",
"new",
"(",
"\"#{file}: Format error!\"",
")",
"unless",
"coded_offset_table",
".",
"bytesize",
"==",
"number_of_objects",
"*",
"offset_size",
"@count_objects",
"=",
"number_of_objects",
"if",
"(",
"offset_size",
"!=",
"3",
")",
"formats",
"=",
"[",
"\"\"",
",",
"\"C*\"",
",",
"\"n*\"",
",",
"\"\"",
",",
"\"N*\"",
"]",
"@offsets",
"=",
"coded_offset_table",
".",
"unpack",
"(",
"formats",
"[",
"offset_size",
"]",
")",
"else",
"@offsets",
"=",
"coded_offset_table",
".",
"unpack",
"(",
"\"C*\"",
")",
".",
"each_slice",
"(",
"3",
")",
".",
"map",
"{",
"|",
"x",
",",
"y",
",",
"z",
"|",
"(",
"x",
"<<",
"16",
")",
"|",
"(",
"y",
"<<",
"8",
")",
"|",
"z",
"}",
"end",
"@object_ref_size",
"=",
"object_ref_size",
"val",
"=",
"read_binary_object_at",
"(",
"file",
",",
"fd",
",",
"top_object",
")",
"fd",
".",
"close",
"val",
"end"
]
| Read a binary plist file | [
"Read",
"a",
"binary",
"plist",
"file"
]
| fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134 | https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L9-L57 | train |
ckruse/CFPropertyList | lib/cfpropertylist/rbBinaryCFPropertyList.rb | CFPropertyList.Binary.to_str | def to_str(opts={})
@unique_table = {}
@count_objects = 0
@object_refs = 0
@written_object_count = 0
@object_table = []
@offsets = []
binary_str = "bplist00"
@object_refs = count_object_refs(opts[:root])
opts[:root].to_binary(self)
next_offset = 8
offsets = @object_table.map do |object|
offset = next_offset
next_offset += object.bytesize
offset
end
binary_str << @object_table.join
table_offset = next_offset
offset_size = Binary.bytes_needed(table_offset)
if offset_size < 8
# Fast path: encode the entire offset array at once.
binary_str << offsets.pack((%w(C n N N)[offset_size - 1]) + '*')
else
# Slow path: host may be little or big endian, must pack each offset
# separately.
offsets.each do |offset|
binary_str << "#{Binary.pack_it_with_size(offset_size,offset)}"
end
end
binary_str << [offset_size, object_ref_size(@object_refs)].pack("x6CC")
binary_str << [@object_table.size].pack("x4N")
binary_str << [0].pack("x4N")
binary_str << [table_offset].pack("x4N")
binary_str
end | ruby | def to_str(opts={})
@unique_table = {}
@count_objects = 0
@object_refs = 0
@written_object_count = 0
@object_table = []
@offsets = []
binary_str = "bplist00"
@object_refs = count_object_refs(opts[:root])
opts[:root].to_binary(self)
next_offset = 8
offsets = @object_table.map do |object|
offset = next_offset
next_offset += object.bytesize
offset
end
binary_str << @object_table.join
table_offset = next_offset
offset_size = Binary.bytes_needed(table_offset)
if offset_size < 8
# Fast path: encode the entire offset array at once.
binary_str << offsets.pack((%w(C n N N)[offset_size - 1]) + '*')
else
# Slow path: host may be little or big endian, must pack each offset
# separately.
offsets.each do |offset|
binary_str << "#{Binary.pack_it_with_size(offset_size,offset)}"
end
end
binary_str << [offset_size, object_ref_size(@object_refs)].pack("x6CC")
binary_str << [@object_table.size].pack("x4N")
binary_str << [0].pack("x4N")
binary_str << [table_offset].pack("x4N")
binary_str
end | [
"def",
"to_str",
"(",
"opts",
"=",
"{",
"}",
")",
"@unique_table",
"=",
"{",
"}",
"@count_objects",
"=",
"0",
"@object_refs",
"=",
"0",
"@written_object_count",
"=",
"0",
"@object_table",
"=",
"[",
"]",
"@offsets",
"=",
"[",
"]",
"binary_str",
"=",
"\"bplist00\"",
"@object_refs",
"=",
"count_object_refs",
"(",
"opts",
"[",
":root",
"]",
")",
"opts",
"[",
":root",
"]",
".",
"to_binary",
"(",
"self",
")",
"next_offset",
"=",
"8",
"offsets",
"=",
"@object_table",
".",
"map",
"do",
"|",
"object",
"|",
"offset",
"=",
"next_offset",
"next_offset",
"+=",
"object",
".",
"bytesize",
"offset",
"end",
"binary_str",
"<<",
"@object_table",
".",
"join",
"table_offset",
"=",
"next_offset",
"offset_size",
"=",
"Binary",
".",
"bytes_needed",
"(",
"table_offset",
")",
"if",
"offset_size",
"<",
"8",
"binary_str",
"<<",
"offsets",
".",
"pack",
"(",
"(",
"%w(",
"C",
"n",
"N",
"N",
")",
"[",
"offset_size",
"-",
"1",
"]",
")",
"+",
"'*'",
")",
"else",
"offsets",
".",
"each",
"do",
"|",
"offset",
"|",
"binary_str",
"<<",
"\"#{Binary.pack_it_with_size(offset_size,offset)}\"",
"end",
"end",
"binary_str",
"<<",
"[",
"offset_size",
",",
"object_ref_size",
"(",
"@object_refs",
")",
"]",
".",
"pack",
"(",
"\"x6CC\"",
")",
"binary_str",
"<<",
"[",
"@object_table",
".",
"size",
"]",
".",
"pack",
"(",
"\"x4N\"",
")",
"binary_str",
"<<",
"[",
"0",
"]",
".",
"pack",
"(",
"\"x4N\"",
")",
"binary_str",
"<<",
"[",
"table_offset",
"]",
".",
"pack",
"(",
"\"x4N\"",
")",
"binary_str",
"end"
]
| Convert CFPropertyList to binary format; since we have to count our objects we simply unique CFDictionary and CFArray | [
"Convert",
"CFPropertyList",
"to",
"binary",
"format",
";",
"since",
"we",
"have",
"to",
"count",
"our",
"objects",
"we",
"simply",
"unique",
"CFDictionary",
"and",
"CFArray"
]
| fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134 | https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L61-L105 | train |
ckruse/CFPropertyList | lib/cfpropertylist/rbBinaryCFPropertyList.rb | CFPropertyList.Binary.read_binary_int | def read_binary_int(fname,fd,length)
if length > 4
raise CFFormatError.new("Integer greater than 16 bytes: #{length}")
end
nbytes = 1 << length
buff = fd.read(nbytes)
CFInteger.new(
case length
when 0 then buff.unpack("C")[0]
when 1 then buff.unpack("n")[0]
when 2 then buff.unpack("N")[0]
# 8 byte integers are always signed
when 3 then buff.unpack("q>")[0]
# 16 byte integers are used to represent unsigned 8 byte integers
# where the unsigned value is stored in the lower 8 bytes and the
# upper 8 bytes are unused.
when 4 then buff.unpack("Q>Q>")[1]
end
)
end | ruby | def read_binary_int(fname,fd,length)
if length > 4
raise CFFormatError.new("Integer greater than 16 bytes: #{length}")
end
nbytes = 1 << length
buff = fd.read(nbytes)
CFInteger.new(
case length
when 0 then buff.unpack("C")[0]
when 1 then buff.unpack("n")[0]
when 2 then buff.unpack("N")[0]
# 8 byte integers are always signed
when 3 then buff.unpack("q>")[0]
# 16 byte integers are used to represent unsigned 8 byte integers
# where the unsigned value is stored in the lower 8 bytes and the
# upper 8 bytes are unused.
when 4 then buff.unpack("Q>Q>")[1]
end
)
end | [
"def",
"read_binary_int",
"(",
"fname",
",",
"fd",
",",
"length",
")",
"if",
"length",
">",
"4",
"raise",
"CFFormatError",
".",
"new",
"(",
"\"Integer greater than 16 bytes: #{length}\"",
")",
"end",
"nbytes",
"=",
"1",
"<<",
"length",
"buff",
"=",
"fd",
".",
"read",
"(",
"nbytes",
")",
"CFInteger",
".",
"new",
"(",
"case",
"length",
"when",
"0",
"then",
"buff",
".",
"unpack",
"(",
"\"C\"",
")",
"[",
"0",
"]",
"when",
"1",
"then",
"buff",
".",
"unpack",
"(",
"\"n\"",
")",
"[",
"0",
"]",
"when",
"2",
"then",
"buff",
".",
"unpack",
"(",
"\"N\"",
")",
"[",
"0",
"]",
"when",
"3",
"then",
"buff",
".",
"unpack",
"(",
"\"q>\"",
")",
"[",
"0",
"]",
"when",
"4",
"then",
"buff",
".",
"unpack",
"(",
"\"Q>Q>\"",
")",
"[",
"1",
"]",
"end",
")",
"end"
]
| read a binary int value | [
"read",
"a",
"binary",
"int",
"value"
]
| fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134 | https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L125-L147 | train |
ckruse/CFPropertyList | lib/cfpropertylist/rbBinaryCFPropertyList.rb | CFPropertyList.Binary.read_binary_real | def read_binary_real(fname,fd,length)
raise CFFormatError.new("Real greater than 8 bytes: #{length}") if length > 3
nbytes = 1 << length
buff = fd.read(nbytes)
CFReal.new(
case length
when 0 # 1 byte float? must be an error
raise CFFormatError.new("got #{length+1} byte float, must be an error!")
when 1 # 2 byte float? must be an error
raise CFFormatError.new("got #{length+1} byte float, must be an error!")
when 2 then
buff.reverse.unpack("e")[0]
when 3 then
buff.reverse.unpack("E")[0]
else
fail "unexpected length: #{length}"
end
)
end | ruby | def read_binary_real(fname,fd,length)
raise CFFormatError.new("Real greater than 8 bytes: #{length}") if length > 3
nbytes = 1 << length
buff = fd.read(nbytes)
CFReal.new(
case length
when 0 # 1 byte float? must be an error
raise CFFormatError.new("got #{length+1} byte float, must be an error!")
when 1 # 2 byte float? must be an error
raise CFFormatError.new("got #{length+1} byte float, must be an error!")
when 2 then
buff.reverse.unpack("e")[0]
when 3 then
buff.reverse.unpack("E")[0]
else
fail "unexpected length: #{length}"
end
)
end | [
"def",
"read_binary_real",
"(",
"fname",
",",
"fd",
",",
"length",
")",
"raise",
"CFFormatError",
".",
"new",
"(",
"\"Real greater than 8 bytes: #{length}\"",
")",
"if",
"length",
">",
"3",
"nbytes",
"=",
"1",
"<<",
"length",
"buff",
"=",
"fd",
".",
"read",
"(",
"nbytes",
")",
"CFReal",
".",
"new",
"(",
"case",
"length",
"when",
"0",
"raise",
"CFFormatError",
".",
"new",
"(",
"\"got #{length+1} byte float, must be an error!\"",
")",
"when",
"1",
"raise",
"CFFormatError",
".",
"new",
"(",
"\"got #{length+1} byte float, must be an error!\"",
")",
"when",
"2",
"then",
"buff",
".",
"reverse",
".",
"unpack",
"(",
"\"e\"",
")",
"[",
"0",
"]",
"when",
"3",
"then",
"buff",
".",
"reverse",
".",
"unpack",
"(",
"\"E\"",
")",
"[",
"0",
"]",
"else",
"fail",
"\"unexpected length: #{length}\"",
"end",
")",
"end"
]
| read a binary real value | [
"read",
"a",
"binary",
"real",
"value"
]
| fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134 | https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L151-L171 | train |
ckruse/CFPropertyList | lib/cfpropertylist/rbBinaryCFPropertyList.rb | CFPropertyList.Binary.read_binary_date | def read_binary_date(fname,fd,length)
raise CFFormatError.new("Date greater than 8 bytes: #{length}") if length > 3
nbytes = 1 << length
buff = fd.read(nbytes)
CFDate.new(
case length
when 0 then # 1 byte CFDate is an error
raise CFFormatError.new("#{length+1} byte CFDate, error")
when 1 then # 2 byte CFDate is an error
raise CFFormatError.new("#{length+1} byte CFDate, error")
when 2 then
buff.reverse.unpack("e")[0]
when 3 then
buff.reverse.unpack("E")[0]
end,
CFDate::TIMESTAMP_APPLE
)
end | ruby | def read_binary_date(fname,fd,length)
raise CFFormatError.new("Date greater than 8 bytes: #{length}") if length > 3
nbytes = 1 << length
buff = fd.read(nbytes)
CFDate.new(
case length
when 0 then # 1 byte CFDate is an error
raise CFFormatError.new("#{length+1} byte CFDate, error")
when 1 then # 2 byte CFDate is an error
raise CFFormatError.new("#{length+1} byte CFDate, error")
when 2 then
buff.reverse.unpack("e")[0]
when 3 then
buff.reverse.unpack("E")[0]
end,
CFDate::TIMESTAMP_APPLE
)
end | [
"def",
"read_binary_date",
"(",
"fname",
",",
"fd",
",",
"length",
")",
"raise",
"CFFormatError",
".",
"new",
"(",
"\"Date greater than 8 bytes: #{length}\"",
")",
"if",
"length",
">",
"3",
"nbytes",
"=",
"1",
"<<",
"length",
"buff",
"=",
"fd",
".",
"read",
"(",
"nbytes",
")",
"CFDate",
".",
"new",
"(",
"case",
"length",
"when",
"0",
"then",
"raise",
"CFFormatError",
".",
"new",
"(",
"\"#{length+1} byte CFDate, error\"",
")",
"when",
"1",
"then",
"raise",
"CFFormatError",
".",
"new",
"(",
"\"#{length+1} byte CFDate, error\"",
")",
"when",
"2",
"then",
"buff",
".",
"reverse",
".",
"unpack",
"(",
"\"e\"",
")",
"[",
"0",
"]",
"when",
"3",
"then",
"buff",
".",
"reverse",
".",
"unpack",
"(",
"\"E\"",
")",
"[",
"0",
"]",
"end",
",",
"CFDate",
"::",
"TIMESTAMP_APPLE",
")",
"end"
]
| read a binary date value | [
"read",
"a",
"binary",
"date",
"value"
]
| fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134 | https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L175-L194 | train |
ckruse/CFPropertyList | lib/cfpropertylist/rbBinaryCFPropertyList.rb | CFPropertyList.Binary.read_binary_data | def read_binary_data(fname,fd,length)
CFData.new(read_fd(fd, length), CFData::DATA_RAW)
end | ruby | def read_binary_data(fname,fd,length)
CFData.new(read_fd(fd, length), CFData::DATA_RAW)
end | [
"def",
"read_binary_data",
"(",
"fname",
",",
"fd",
",",
"length",
")",
"CFData",
".",
"new",
"(",
"read_fd",
"(",
"fd",
",",
"length",
")",
",",
"CFData",
"::",
"DATA_RAW",
")",
"end"
]
| Read a binary data value | [
"Read",
"a",
"binary",
"data",
"value"
]
| fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134 | https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L198-L200 | train |
ckruse/CFPropertyList | lib/cfpropertylist/rbBinaryCFPropertyList.rb | CFPropertyList.Binary.read_binary_string | def read_binary_string(fname,fd,length)
buff = read_fd fd, length
@unique_table[buff] = true unless @unique_table.has_key?(buff)
CFString.new(buff)
end | ruby | def read_binary_string(fname,fd,length)
buff = read_fd fd, length
@unique_table[buff] = true unless @unique_table.has_key?(buff)
CFString.new(buff)
end | [
"def",
"read_binary_string",
"(",
"fname",
",",
"fd",
",",
"length",
")",
"buff",
"=",
"read_fd",
"fd",
",",
"length",
"@unique_table",
"[",
"buff",
"]",
"=",
"true",
"unless",
"@unique_table",
".",
"has_key?",
"(",
"buff",
")",
"CFString",
".",
"new",
"(",
"buff",
")",
"end"
]
| Read a binary string value | [
"Read",
"a",
"binary",
"string",
"value"
]
| fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134 | https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L208-L212 | train |
ckruse/CFPropertyList | lib/cfpropertylist/rbBinaryCFPropertyList.rb | CFPropertyList.Binary.read_binary_unicode_string | def read_binary_unicode_string(fname,fd,length)
# The problem is: we get the length of the string IN CHARACTERS;
# since a char in UTF-16 can be 16 or 32 bit long, we don't really know
# how long the string is in bytes
buff = fd.read(2*length)
@unique_table[buff] = true unless @unique_table.has_key?(buff)
CFString.new(Binary.charset_convert(buff,"UTF-16BE","UTF-8"))
end | ruby | def read_binary_unicode_string(fname,fd,length)
# The problem is: we get the length of the string IN CHARACTERS;
# since a char in UTF-16 can be 16 or 32 bit long, we don't really know
# how long the string is in bytes
buff = fd.read(2*length)
@unique_table[buff] = true unless @unique_table.has_key?(buff)
CFString.new(Binary.charset_convert(buff,"UTF-16BE","UTF-8"))
end | [
"def",
"read_binary_unicode_string",
"(",
"fname",
",",
"fd",
",",
"length",
")",
"buff",
"=",
"fd",
".",
"read",
"(",
"2",
"*",
"length",
")",
"@unique_table",
"[",
"buff",
"]",
"=",
"true",
"unless",
"@unique_table",
".",
"has_key?",
"(",
"buff",
")",
"CFString",
".",
"new",
"(",
"Binary",
".",
"charset_convert",
"(",
"buff",
",",
"\"UTF-16BE\"",
",",
"\"UTF-8\"",
")",
")",
"end"
]
| Read a unicode string value, coded as UTF-16BE | [
"Read",
"a",
"unicode",
"string",
"value",
"coded",
"as",
"UTF",
"-",
"16BE"
]
| fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134 | https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L245-L253 | train |
ckruse/CFPropertyList | lib/cfpropertylist/rbBinaryCFPropertyList.rb | CFPropertyList.Binary.read_binary_array | def read_binary_array(fname,fd,length)
ary = []
# first: read object refs
if(length != 0)
buff = fd.read(length * @object_ref_size)
objects = unpack_with_size(@object_ref_size, buff) #buff.unpack(@object_ref_size == 1 ? "C*" : "n*")
# now: read objects
0.upto(length-1) do |i|
object = read_binary_object_at(fname,fd,objects[i])
ary.push object
end
end
CFArray.new(ary)
end | ruby | def read_binary_array(fname,fd,length)
ary = []
# first: read object refs
if(length != 0)
buff = fd.read(length * @object_ref_size)
objects = unpack_with_size(@object_ref_size, buff) #buff.unpack(@object_ref_size == 1 ? "C*" : "n*")
# now: read objects
0.upto(length-1) do |i|
object = read_binary_object_at(fname,fd,objects[i])
ary.push object
end
end
CFArray.new(ary)
end | [
"def",
"read_binary_array",
"(",
"fname",
",",
"fd",
",",
"length",
")",
"ary",
"=",
"[",
"]",
"if",
"(",
"length",
"!=",
"0",
")",
"buff",
"=",
"fd",
".",
"read",
"(",
"length",
"*",
"@object_ref_size",
")",
"objects",
"=",
"unpack_with_size",
"(",
"@object_ref_size",
",",
"buff",
")",
"0",
".",
"upto",
"(",
"length",
"-",
"1",
")",
"do",
"|",
"i",
"|",
"object",
"=",
"read_binary_object_at",
"(",
"fname",
",",
"fd",
",",
"objects",
"[",
"i",
"]",
")",
"ary",
".",
"push",
"object",
"end",
"end",
"CFArray",
".",
"new",
"(",
"ary",
")",
"end"
]
| Read an binary array value, including contained objects | [
"Read",
"an",
"binary",
"array",
"value",
"including",
"contained",
"objects"
]
| fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134 | https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L267-L283 | train |
ckruse/CFPropertyList | lib/cfpropertylist/rbBinaryCFPropertyList.rb | CFPropertyList.Binary.read_binary_dict | def read_binary_dict(fname,fd,length)
dict = {}
# first: read keys
if(length != 0) then
buff = fd.read(length * @object_ref_size)
keys = unpack_with_size(@object_ref_size, buff)
# second: read object refs
buff = fd.read(length * @object_ref_size)
objects = unpack_with_size(@object_ref_size, buff)
# read real keys and objects
0.upto(length-1) do |i|
key = read_binary_object_at(fname,fd,keys[i])
object = read_binary_object_at(fname,fd,objects[i])
dict[key.value] = object
end
end
CFDictionary.new(dict)
end | ruby | def read_binary_dict(fname,fd,length)
dict = {}
# first: read keys
if(length != 0) then
buff = fd.read(length * @object_ref_size)
keys = unpack_with_size(@object_ref_size, buff)
# second: read object refs
buff = fd.read(length * @object_ref_size)
objects = unpack_with_size(@object_ref_size, buff)
# read real keys and objects
0.upto(length-1) do |i|
key = read_binary_object_at(fname,fd,keys[i])
object = read_binary_object_at(fname,fd,objects[i])
dict[key.value] = object
end
end
CFDictionary.new(dict)
end | [
"def",
"read_binary_dict",
"(",
"fname",
",",
"fd",
",",
"length",
")",
"dict",
"=",
"{",
"}",
"if",
"(",
"length",
"!=",
"0",
")",
"then",
"buff",
"=",
"fd",
".",
"read",
"(",
"length",
"*",
"@object_ref_size",
")",
"keys",
"=",
"unpack_with_size",
"(",
"@object_ref_size",
",",
"buff",
")",
"buff",
"=",
"fd",
".",
"read",
"(",
"length",
"*",
"@object_ref_size",
")",
"objects",
"=",
"unpack_with_size",
"(",
"@object_ref_size",
",",
"buff",
")",
"0",
".",
"upto",
"(",
"length",
"-",
"1",
")",
"do",
"|",
"i",
"|",
"key",
"=",
"read_binary_object_at",
"(",
"fname",
",",
"fd",
",",
"keys",
"[",
"i",
"]",
")",
"object",
"=",
"read_binary_object_at",
"(",
"fname",
",",
"fd",
",",
"objects",
"[",
"i",
"]",
")",
"dict",
"[",
"key",
".",
"value",
"]",
"=",
"object",
"end",
"end",
"CFDictionary",
".",
"new",
"(",
"dict",
")",
"end"
]
| Read a dictionary value, including contained objects | [
"Read",
"a",
"dictionary",
"value",
"including",
"contained",
"objects"
]
| fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134 | https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L287-L308 | train |
ckruse/CFPropertyList | lib/cfpropertylist/rbBinaryCFPropertyList.rb | CFPropertyList.Binary.read_binary_object | def read_binary_object(fname,fd)
# first: read the marker byte
buff = fd.read(1)
object_length = buff.unpack("C*")
object_length = object_length[0] & 0xF
buff = buff.unpack("H*")
object_type = buff[0][0].chr
if(object_type != "0" && object_length == 15) then
object_length = read_binary_object(fname,fd)
object_length = object_length.value
end
case object_type
when '0' # null, false, true, fillbyte
read_binary_null_type(object_length)
when '1' # integer
read_binary_int(fname,fd,object_length)
when '2' # real
read_binary_real(fname,fd,object_length)
when '3' # date
read_binary_date(fname,fd,object_length)
when '4' # data
read_binary_data(fname,fd,object_length)
when '5' # byte string, usually utf8 encoded
read_binary_string(fname,fd,object_length)
when '6' # unicode string (utf16be)
read_binary_unicode_string(fname,fd,object_length)
when '8'
CFUid.new(read_binary_int(fname, fd, object_length).value)
when 'a' # array
read_binary_array(fname,fd,object_length)
when 'd' # dictionary
read_binary_dict(fname,fd,object_length)
end
end | ruby | def read_binary_object(fname,fd)
# first: read the marker byte
buff = fd.read(1)
object_length = buff.unpack("C*")
object_length = object_length[0] & 0xF
buff = buff.unpack("H*")
object_type = buff[0][0].chr
if(object_type != "0" && object_length == 15) then
object_length = read_binary_object(fname,fd)
object_length = object_length.value
end
case object_type
when '0' # null, false, true, fillbyte
read_binary_null_type(object_length)
when '1' # integer
read_binary_int(fname,fd,object_length)
when '2' # real
read_binary_real(fname,fd,object_length)
when '3' # date
read_binary_date(fname,fd,object_length)
when '4' # data
read_binary_data(fname,fd,object_length)
when '5' # byte string, usually utf8 encoded
read_binary_string(fname,fd,object_length)
when '6' # unicode string (utf16be)
read_binary_unicode_string(fname,fd,object_length)
when '8'
CFUid.new(read_binary_int(fname, fd, object_length).value)
when 'a' # array
read_binary_array(fname,fd,object_length)
when 'd' # dictionary
read_binary_dict(fname,fd,object_length)
end
end | [
"def",
"read_binary_object",
"(",
"fname",
",",
"fd",
")",
"buff",
"=",
"fd",
".",
"read",
"(",
"1",
")",
"object_length",
"=",
"buff",
".",
"unpack",
"(",
"\"C*\"",
")",
"object_length",
"=",
"object_length",
"[",
"0",
"]",
"&",
"0xF",
"buff",
"=",
"buff",
".",
"unpack",
"(",
"\"H*\"",
")",
"object_type",
"=",
"buff",
"[",
"0",
"]",
"[",
"0",
"]",
".",
"chr",
"if",
"(",
"object_type",
"!=",
"\"0\"",
"&&",
"object_length",
"==",
"15",
")",
"then",
"object_length",
"=",
"read_binary_object",
"(",
"fname",
",",
"fd",
")",
"object_length",
"=",
"object_length",
".",
"value",
"end",
"case",
"object_type",
"when",
"'0'",
"read_binary_null_type",
"(",
"object_length",
")",
"when",
"'1'",
"read_binary_int",
"(",
"fname",
",",
"fd",
",",
"object_length",
")",
"when",
"'2'",
"read_binary_real",
"(",
"fname",
",",
"fd",
",",
"object_length",
")",
"when",
"'3'",
"read_binary_date",
"(",
"fname",
",",
"fd",
",",
"object_length",
")",
"when",
"'4'",
"read_binary_data",
"(",
"fname",
",",
"fd",
",",
"object_length",
")",
"when",
"'5'",
"read_binary_string",
"(",
"fname",
",",
"fd",
",",
"object_length",
")",
"when",
"'6'",
"read_binary_unicode_string",
"(",
"fname",
",",
"fd",
",",
"object_length",
")",
"when",
"'8'",
"CFUid",
".",
"new",
"(",
"read_binary_int",
"(",
"fname",
",",
"fd",
",",
"object_length",
")",
".",
"value",
")",
"when",
"'a'",
"read_binary_array",
"(",
"fname",
",",
"fd",
",",
"object_length",
")",
"when",
"'d'",
"read_binary_dict",
"(",
"fname",
",",
"fd",
",",
"object_length",
")",
"end",
"end"
]
| Read an object type byte, decode it and delegate to the correct
reader function | [
"Read",
"an",
"object",
"type",
"byte",
"decode",
"it",
"and",
"delegate",
"to",
"the",
"correct",
"reader",
"function"
]
| fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134 | https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L313-L350 | train |
ckruse/CFPropertyList | lib/cfpropertylist/rbBinaryCFPropertyList.rb | CFPropertyList.Binary.string_to_binary | def string_to_binary(val)
val = val.to_s
@unique_table[val] ||= begin
if !Binary.ascii_string?(val)
val = Binary.charset_convert(val,"UTF-8","UTF-16BE")
bdata = Binary.type_bytes(0b0110, Binary.charset_strlen(val,"UTF-16BE"))
val.force_encoding("ASCII-8BIT") if val.respond_to?("encode")
@object_table[@written_object_count] = bdata << val
else
bdata = Binary.type_bytes(0b0101,val.bytesize)
@object_table[@written_object_count] = bdata << val
end
@written_object_count += 1
@written_object_count - 1
end
end | ruby | def string_to_binary(val)
val = val.to_s
@unique_table[val] ||= begin
if !Binary.ascii_string?(val)
val = Binary.charset_convert(val,"UTF-8","UTF-16BE")
bdata = Binary.type_bytes(0b0110, Binary.charset_strlen(val,"UTF-16BE"))
val.force_encoding("ASCII-8BIT") if val.respond_to?("encode")
@object_table[@written_object_count] = bdata << val
else
bdata = Binary.type_bytes(0b0101,val.bytesize)
@object_table[@written_object_count] = bdata << val
end
@written_object_count += 1
@written_object_count - 1
end
end | [
"def",
"string_to_binary",
"(",
"val",
")",
"val",
"=",
"val",
".",
"to_s",
"@unique_table",
"[",
"val",
"]",
"||=",
"begin",
"if",
"!",
"Binary",
".",
"ascii_string?",
"(",
"val",
")",
"val",
"=",
"Binary",
".",
"charset_convert",
"(",
"val",
",",
"\"UTF-8\"",
",",
"\"UTF-16BE\"",
")",
"bdata",
"=",
"Binary",
".",
"type_bytes",
"(",
"0b0110",
",",
"Binary",
".",
"charset_strlen",
"(",
"val",
",",
"\"UTF-16BE\"",
")",
")",
"val",
".",
"force_encoding",
"(",
"\"ASCII-8BIT\"",
")",
"if",
"val",
".",
"respond_to?",
"(",
"\"encode\"",
")",
"@object_table",
"[",
"@written_object_count",
"]",
"=",
"bdata",
"<<",
"val",
"else",
"bdata",
"=",
"Binary",
".",
"type_bytes",
"(",
"0b0101",
",",
"val",
".",
"bytesize",
")",
"@object_table",
"[",
"@written_object_count",
"]",
"=",
"bdata",
"<<",
"val",
"end",
"@written_object_count",
"+=",
"1",
"@written_object_count",
"-",
"1",
"end",
"end"
]
| Uniques and transforms a string value to binary format and adds it to the object table | [
"Uniques",
"and",
"transforms",
"a",
"string",
"value",
"to",
"binary",
"format",
"and",
"adds",
"it",
"to",
"the",
"object",
"table"
]
| fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134 | https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L450-L468 | train |
ckruse/CFPropertyList | lib/cfpropertylist/rbBinaryCFPropertyList.rb | CFPropertyList.Binary.int_to_binary | def int_to_binary(value)
# Note: nbytes is actually an exponent. number of bytes = 2**nbytes.
nbytes = 0
nbytes = 1 if value > 0xFF # 1 byte unsigned integer
nbytes += 1 if value > 0xFFFF # 4 byte unsigned integer
nbytes += 1 if value > 0xFFFFFFFF # 8 byte unsigned integer
nbytes += 1 if value > 0x7FFFFFFFFFFFFFFF # 8 byte unsigned integer, stored in lower half of 16 bytes
nbytes = 3 if value < 0 # signed integers always stored in 8 bytes
Binary.type_bytes(0b0001, nbytes) <<
if nbytes < 4
[value].pack(["C", "n", "N", "q>"][nbytes])
else # nbytes == 4
[0,value].pack("Q>Q>")
end
end | ruby | def int_to_binary(value)
# Note: nbytes is actually an exponent. number of bytes = 2**nbytes.
nbytes = 0
nbytes = 1 if value > 0xFF # 1 byte unsigned integer
nbytes += 1 if value > 0xFFFF # 4 byte unsigned integer
nbytes += 1 if value > 0xFFFFFFFF # 8 byte unsigned integer
nbytes += 1 if value > 0x7FFFFFFFFFFFFFFF # 8 byte unsigned integer, stored in lower half of 16 bytes
nbytes = 3 if value < 0 # signed integers always stored in 8 bytes
Binary.type_bytes(0b0001, nbytes) <<
if nbytes < 4
[value].pack(["C", "n", "N", "q>"][nbytes])
else # nbytes == 4
[0,value].pack("Q>Q>")
end
end | [
"def",
"int_to_binary",
"(",
"value",
")",
"nbytes",
"=",
"0",
"nbytes",
"=",
"1",
"if",
"value",
">",
"0xFF",
"nbytes",
"+=",
"1",
"if",
"value",
">",
"0xFFFF",
"nbytes",
"+=",
"1",
"if",
"value",
">",
"0xFFFFFFFF",
"nbytes",
"+=",
"1",
"if",
"value",
">",
"0x7FFFFFFFFFFFFFFF",
"nbytes",
"=",
"3",
"if",
"value",
"<",
"0",
"Binary",
".",
"type_bytes",
"(",
"0b0001",
",",
"nbytes",
")",
"<<",
"if",
"nbytes",
"<",
"4",
"[",
"value",
"]",
".",
"pack",
"(",
"[",
"\"C\"",
",",
"\"n\"",
",",
"\"N\"",
",",
"\"q>\"",
"]",
"[",
"nbytes",
"]",
")",
"else",
"[",
"0",
",",
"value",
"]",
".",
"pack",
"(",
"\"Q>Q>\"",
")",
"end",
"end"
]
| Codes an integer to binary format | [
"Codes",
"an",
"integer",
"to",
"binary",
"format"
]
| fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134 | https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L471-L486 | train |
ckruse/CFPropertyList | lib/cfpropertylist/rbBinaryCFPropertyList.rb | CFPropertyList.Binary.num_to_binary | def num_to_binary(value)
@object_table[@written_object_count] =
if value.is_a?(CFInteger)
int_to_binary(value.value)
else
real_to_binary(value.value)
end
@written_object_count += 1
@written_object_count - 1
end | ruby | def num_to_binary(value)
@object_table[@written_object_count] =
if value.is_a?(CFInteger)
int_to_binary(value.value)
else
real_to_binary(value.value)
end
@written_object_count += 1
@written_object_count - 1
end | [
"def",
"num_to_binary",
"(",
"value",
")",
"@object_table",
"[",
"@written_object_count",
"]",
"=",
"if",
"value",
".",
"is_a?",
"(",
"CFInteger",
")",
"int_to_binary",
"(",
"value",
".",
"value",
")",
"else",
"real_to_binary",
"(",
"value",
".",
"value",
")",
"end",
"@written_object_count",
"+=",
"1",
"@written_object_count",
"-",
"1",
"end"
]
| Converts a numeric value to binary and adds it to the object table | [
"Converts",
"a",
"numeric",
"value",
"to",
"binary",
"and",
"adds",
"it",
"to",
"the",
"object",
"table"
]
| fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134 | https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L494-L504 | train |
ckruse/CFPropertyList | lib/cfpropertylist/rbBinaryCFPropertyList.rb | CFPropertyList.Binary.array_to_binary | def array_to_binary(val)
saved_object_count = @written_object_count
@written_object_count += 1
#@object_refs += val.value.size
values = val.value.map { |v| v.to_binary(self) }
bdata = Binary.type_bytes(0b1010, val.value.size) <<
Binary.pack_int_array_with_size(object_ref_size(@object_refs),
values)
@object_table[saved_object_count] = bdata
saved_object_count
end | ruby | def array_to_binary(val)
saved_object_count = @written_object_count
@written_object_count += 1
#@object_refs += val.value.size
values = val.value.map { |v| v.to_binary(self) }
bdata = Binary.type_bytes(0b1010, val.value.size) <<
Binary.pack_int_array_with_size(object_ref_size(@object_refs),
values)
@object_table[saved_object_count] = bdata
saved_object_count
end | [
"def",
"array_to_binary",
"(",
"val",
")",
"saved_object_count",
"=",
"@written_object_count",
"@written_object_count",
"+=",
"1",
"values",
"=",
"val",
".",
"value",
".",
"map",
"{",
"|",
"v",
"|",
"v",
".",
"to_binary",
"(",
"self",
")",
"}",
"bdata",
"=",
"Binary",
".",
"type_bytes",
"(",
"0b1010",
",",
"val",
".",
"value",
".",
"size",
")",
"<<",
"Binary",
".",
"pack_int_array_with_size",
"(",
"object_ref_size",
"(",
"@object_refs",
")",
",",
"values",
")",
"@object_table",
"[",
"saved_object_count",
"]",
"=",
"bdata",
"saved_object_count",
"end"
]
| Convert array to binary format and add it to the object table | [
"Convert",
"array",
"to",
"binary",
"format",
"and",
"add",
"it",
"to",
"the",
"object",
"table"
]
| fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134 | https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L561-L573 | train |
ckruse/CFPropertyList | lib/cfpropertylist/rbBinaryCFPropertyList.rb | CFPropertyList.Binary.dict_to_binary | def dict_to_binary(val)
saved_object_count = @written_object_count
@written_object_count += 1
#@object_refs += val.value.keys.size * 2
keys_and_values = val.value.keys.map { |k| CFString.new(k).to_binary(self) }
keys_and_values.concat(val.value.values.map { |v| v.to_binary(self) })
bdata = Binary.type_bytes(0b1101,val.value.size) <<
Binary.pack_int_array_with_size(object_ref_size(@object_refs), keys_and_values)
@object_table[saved_object_count] = bdata
return saved_object_count
end | ruby | def dict_to_binary(val)
saved_object_count = @written_object_count
@written_object_count += 1
#@object_refs += val.value.keys.size * 2
keys_and_values = val.value.keys.map { |k| CFString.new(k).to_binary(self) }
keys_and_values.concat(val.value.values.map { |v| v.to_binary(self) })
bdata = Binary.type_bytes(0b1101,val.value.size) <<
Binary.pack_int_array_with_size(object_ref_size(@object_refs), keys_and_values)
@object_table[saved_object_count] = bdata
return saved_object_count
end | [
"def",
"dict_to_binary",
"(",
"val",
")",
"saved_object_count",
"=",
"@written_object_count",
"@written_object_count",
"+=",
"1",
"keys_and_values",
"=",
"val",
".",
"value",
".",
"keys",
".",
"map",
"{",
"|",
"k",
"|",
"CFString",
".",
"new",
"(",
"k",
")",
".",
"to_binary",
"(",
"self",
")",
"}",
"keys_and_values",
".",
"concat",
"(",
"val",
".",
"value",
".",
"values",
".",
"map",
"{",
"|",
"v",
"|",
"v",
".",
"to_binary",
"(",
"self",
")",
"}",
")",
"bdata",
"=",
"Binary",
".",
"type_bytes",
"(",
"0b1101",
",",
"val",
".",
"value",
".",
"size",
")",
"<<",
"Binary",
".",
"pack_int_array_with_size",
"(",
"object_ref_size",
"(",
"@object_refs",
")",
",",
"keys_and_values",
")",
"@object_table",
"[",
"saved_object_count",
"]",
"=",
"bdata",
"return",
"saved_object_count",
"end"
]
| Convert dictionary to binary format and add it to the object table | [
"Convert",
"dictionary",
"to",
"binary",
"format",
"and",
"add",
"it",
"to",
"the",
"object",
"table"
]
| fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134 | https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L576-L590 | train |
qoobaa/s3 | lib/s3/connection.rb | S3.Connection.request | def request(method, options)
host = options.fetch(:host, S3.host)
path = options.fetch(:path)
body = options.fetch(:body, nil)
params = options.fetch(:params, {})
headers = options.fetch(:headers, {})
# Must be done before adding params
# Encodes all characters except forward-slash (/) and explicitly legal URL characters
path = Addressable::URI.escape(path)
if params
params = params.is_a?(String) ? params : self.class.parse_params(params)
path << "?#{params}"
end
request = Request.new(@chunk_size, method.to_s.upcase, !!body, method.to_s.upcase != "HEAD", path)
headers = self.class.parse_headers(headers)
headers.each do |key, value|
request[key] = value
end
if body
if body.respond_to?(:read)
request.body_stream = body
else
request.body = body
end
request.content_length = body.respond_to?(:lstat) ? body.stat.size : body.size
end
send_request(host, request)
end | ruby | def request(method, options)
host = options.fetch(:host, S3.host)
path = options.fetch(:path)
body = options.fetch(:body, nil)
params = options.fetch(:params, {})
headers = options.fetch(:headers, {})
# Must be done before adding params
# Encodes all characters except forward-slash (/) and explicitly legal URL characters
path = Addressable::URI.escape(path)
if params
params = params.is_a?(String) ? params : self.class.parse_params(params)
path << "?#{params}"
end
request = Request.new(@chunk_size, method.to_s.upcase, !!body, method.to_s.upcase != "HEAD", path)
headers = self.class.parse_headers(headers)
headers.each do |key, value|
request[key] = value
end
if body
if body.respond_to?(:read)
request.body_stream = body
else
request.body = body
end
request.content_length = body.respond_to?(:lstat) ? body.stat.size : body.size
end
send_request(host, request)
end | [
"def",
"request",
"(",
"method",
",",
"options",
")",
"host",
"=",
"options",
".",
"fetch",
"(",
":host",
",",
"S3",
".",
"host",
")",
"path",
"=",
"options",
".",
"fetch",
"(",
":path",
")",
"body",
"=",
"options",
".",
"fetch",
"(",
":body",
",",
"nil",
")",
"params",
"=",
"options",
".",
"fetch",
"(",
":params",
",",
"{",
"}",
")",
"headers",
"=",
"options",
".",
"fetch",
"(",
":headers",
",",
"{",
"}",
")",
"path",
"=",
"Addressable",
"::",
"URI",
".",
"escape",
"(",
"path",
")",
"if",
"params",
"params",
"=",
"params",
".",
"is_a?",
"(",
"String",
")",
"?",
"params",
":",
"self",
".",
"class",
".",
"parse_params",
"(",
"params",
")",
"path",
"<<",
"\"?#{params}\"",
"end",
"request",
"=",
"Request",
".",
"new",
"(",
"@chunk_size",
",",
"method",
".",
"to_s",
".",
"upcase",
",",
"!",
"!",
"body",
",",
"method",
".",
"to_s",
".",
"upcase",
"!=",
"\"HEAD\"",
",",
"path",
")",
"headers",
"=",
"self",
".",
"class",
".",
"parse_headers",
"(",
"headers",
")",
"headers",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"request",
"[",
"key",
"]",
"=",
"value",
"end",
"if",
"body",
"if",
"body",
".",
"respond_to?",
"(",
":read",
")",
"request",
".",
"body_stream",
"=",
"body",
"else",
"request",
".",
"body",
"=",
"body",
"end",
"request",
".",
"content_length",
"=",
"body",
".",
"respond_to?",
"(",
":lstat",
")",
"?",
"body",
".",
"stat",
".",
"size",
":",
"body",
".",
"size",
"end",
"send_request",
"(",
"host",
",",
"request",
")",
"end"
]
| Creates new connection object.
==== Options
* <tt>:access_key_id</tt> - Access key id (REQUIRED)
* <tt>:secret_access_key</tt> - Secret access key (REQUIRED)
* <tt>:use_ssl</tt> - Use https or http protocol (false by
default)
* <tt>:debug</tt> - Display debug information on the STDOUT
(false by default)
* <tt>:timeout</tt> - Timeout to use by the Net::HTTP object
(60 by default)
* <tt>:proxy</tt> - Hash for Net::HTTP Proxy settings
{ :host => "proxy.mydomain.com", :port => "80, :user => "user_a", :password => "secret" }
* <tt>:chunk_size</tt> - Size of a chunk when streaming
(1048576 (1 MiB) by default)
Makes request with given HTTP method, sets missing parameters,
adds signature to request header and returns response object
(Net::HTTPResponse)
==== Parameters
* <tt>method</tt> - HTTP Method symbol, can be <tt>:get</tt>,
<tt>:put</tt>, <tt>:delete</tt>
==== Options:
* <tt>:host</tt> - Hostname to connecto to, defaults
to <tt>s3.amazonaws.com</tt>
* <tt>:path</tt> - path to send request to (REQUIRED)
* <tt>:body</tt> - Request body, only meaningful for
<tt>:put</tt> request
* <tt>:params</tt> - Parameters to add to query string for
request, can be String or Hash
* <tt>:headers</tt> - Hash of headers fields to add to request
header
==== Returns
Net::HTTPResponse object -- response from the server | [
"Creates",
"new",
"connection",
"object",
"."
]
| 2c1960a0b012f6ad1c9d1e5baf49c4148b5472fa | https://github.com/qoobaa/s3/blob/2c1960a0b012f6ad1c9d1e5baf49c4148b5472fa/lib/s3/connection.rb#L56-L89 | train |
qoobaa/s3 | lib/s3/parser.rb | S3.Parser.parse_acl | def parse_acl(xml)
grants = {}
rexml_document(xml).elements.each("AccessControlPolicy/AccessControlList/Grant") do |grant|
grants.merge!(extract_grantee(grant))
end
grants
end | ruby | def parse_acl(xml)
grants = {}
rexml_document(xml).elements.each("AccessControlPolicy/AccessControlList/Grant") do |grant|
grants.merge!(extract_grantee(grant))
end
grants
end | [
"def",
"parse_acl",
"(",
"xml",
")",
"grants",
"=",
"{",
"}",
"rexml_document",
"(",
"xml",
")",
".",
"elements",
".",
"each",
"(",
"\"AccessControlPolicy/AccessControlList/Grant\"",
")",
"do",
"|",
"grant",
"|",
"grants",
".",
"merge!",
"(",
"extract_grantee",
"(",
"grant",
")",
")",
"end",
"grants",
"end"
]
| Parse acl response and return hash with grantee and their permissions | [
"Parse",
"acl",
"response",
"and",
"return",
"hash",
"with",
"grantee",
"and",
"their",
"permissions"
]
| 2c1960a0b012f6ad1c9d1e5baf49c4148b5472fa | https://github.com/qoobaa/s3/blob/2c1960a0b012f6ad1c9d1e5baf49c4148b5472fa/lib/s3/parser.rb#L54-L60 | train |
qoobaa/s3 | lib/s3/object.rb | S3.Object.temporary_url | def temporary_url(expires_at = Time.now + 3600)
signature = Signature.generate_temporary_url_signature(:bucket => name,
:resource => key,
:expires_at => expires_at,
:secret_access_key => secret_access_key)
"#{url}?AWSAccessKeyId=#{self.bucket.service.access_key_id}&Expires=#{expires_at.to_i.to_s}&Signature=#{signature}"
end | ruby | def temporary_url(expires_at = Time.now + 3600)
signature = Signature.generate_temporary_url_signature(:bucket => name,
:resource => key,
:expires_at => expires_at,
:secret_access_key => secret_access_key)
"#{url}?AWSAccessKeyId=#{self.bucket.service.access_key_id}&Expires=#{expires_at.to_i.to_s}&Signature=#{signature}"
end | [
"def",
"temporary_url",
"(",
"expires_at",
"=",
"Time",
".",
"now",
"+",
"3600",
")",
"signature",
"=",
"Signature",
".",
"generate_temporary_url_signature",
"(",
":bucket",
"=>",
"name",
",",
":resource",
"=>",
"key",
",",
":expires_at",
"=>",
"expires_at",
",",
":secret_access_key",
"=>",
"secret_access_key",
")",
"\"#{url}?AWSAccessKeyId=#{self.bucket.service.access_key_id}&Expires=#{expires_at.to_i.to_s}&Signature=#{signature}\"",
"end"
]
| Returns a temporary url to the object that expires on the
timestamp given. Defaults to one hour expire time. | [
"Returns",
"a",
"temporary",
"url",
"to",
"the",
"object",
"that",
"expires",
"on",
"the",
"timestamp",
"given",
".",
"Defaults",
"to",
"one",
"hour",
"expire",
"time",
"."
]
| 2c1960a0b012f6ad1c9d1e5baf49c4148b5472fa | https://github.com/qoobaa/s3/blob/2c1960a0b012f6ad1c9d1e5baf49c4148b5472fa/lib/s3/object.rb#L126-L133 | train |
qoobaa/s3 | lib/s3/bucket.rb | S3.Bucket.save | def save(options = {})
options = {:location => options} unless options.is_a?(Hash)
create_bucket_configuration(options)
true
end | ruby | def save(options = {})
options = {:location => options} unless options.is_a?(Hash)
create_bucket_configuration(options)
true
end | [
"def",
"save",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":location",
"=>",
"options",
"}",
"unless",
"options",
".",
"is_a?",
"(",
"Hash",
")",
"create_bucket_configuration",
"(",
"options",
")",
"true",
"end"
]
| Saves the newly built bucket.
==== Options
* <tt>:location</tt> - location of the bucket
(<tt>:eu</tt> or <tt>us</tt>)
* Any other options are passed through to
Connection#request | [
"Saves",
"the",
"newly",
"built",
"bucket",
"."
]
| 2c1960a0b012f6ad1c9d1e5baf49c4148b5472fa | https://github.com/qoobaa/s3/blob/2c1960a0b012f6ad1c9d1e5baf49c4148b5472fa/lib/s3/bucket.rb#L85-L89 | train |
AtelierConvivialite/webtranslateit | lib/web_translate_it/string.rb | WebTranslateIt.String.translation_for | def translation_for(locale)
success = true
tries ||= 3
translation = self.translations.detect{ |t| t.locale == locale }
return translation if translation
return nil if self.new_record
request = Net::HTTP::Get.new("/api/projects/#{Connection.api_key}/strings/#{self.id}/locales/#{locale}/translations.yaml")
WebTranslateIt::Util.add_fields(request)
begin
response = Util.handle_response(Connection.http_connection.request(request), true, true)
hash = YAML.load(response)
return nil if hash.empty?
translation = WebTranslateIt::Translation.new(hash)
return translation
rescue Timeout::Error
puts "Request timeout. Will retry in 5 seconds."
if (tries -= 1) > 0
sleep(5)
retry
else
success = false
end
end
success
end | ruby | def translation_for(locale)
success = true
tries ||= 3
translation = self.translations.detect{ |t| t.locale == locale }
return translation if translation
return nil if self.new_record
request = Net::HTTP::Get.new("/api/projects/#{Connection.api_key}/strings/#{self.id}/locales/#{locale}/translations.yaml")
WebTranslateIt::Util.add_fields(request)
begin
response = Util.handle_response(Connection.http_connection.request(request), true, true)
hash = YAML.load(response)
return nil if hash.empty?
translation = WebTranslateIt::Translation.new(hash)
return translation
rescue Timeout::Error
puts "Request timeout. Will retry in 5 seconds."
if (tries -= 1) > 0
sleep(5)
retry
else
success = false
end
end
success
end | [
"def",
"translation_for",
"(",
"locale",
")",
"success",
"=",
"true",
"tries",
"||=",
"3",
"translation",
"=",
"self",
".",
"translations",
".",
"detect",
"{",
"|",
"t",
"|",
"t",
".",
"locale",
"==",
"locale",
"}",
"return",
"translation",
"if",
"translation",
"return",
"nil",
"if",
"self",
".",
"new_record",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"\"/api/projects/#{Connection.api_key}/strings/#{self.id}/locales/#{locale}/translations.yaml\"",
")",
"WebTranslateIt",
"::",
"Util",
".",
"add_fields",
"(",
"request",
")",
"begin",
"response",
"=",
"Util",
".",
"handle_response",
"(",
"Connection",
".",
"http_connection",
".",
"request",
"(",
"request",
")",
",",
"true",
",",
"true",
")",
"hash",
"=",
"YAML",
".",
"load",
"(",
"response",
")",
"return",
"nil",
"if",
"hash",
".",
"empty?",
"translation",
"=",
"WebTranslateIt",
"::",
"Translation",
".",
"new",
"(",
"hash",
")",
"return",
"translation",
"rescue",
"Timeout",
"::",
"Error",
"puts",
"\"Request timeout. Will retry in 5 seconds.\"",
"if",
"(",
"tries",
"-=",
"1",
")",
">",
"0",
"sleep",
"(",
"5",
")",
"retry",
"else",
"success",
"=",
"false",
"end",
"end",
"success",
"end"
]
| Gets a Translation for a String
Implementation Example:
WebTranslateIt::Connection.new('secret_api_token') do
string = WebTranslateIt::String.find(1234)
puts string.translation_for("fr") #=> A Translation object
end | [
"Gets",
"a",
"Translation",
"for",
"a",
"String"
]
| 6dcae8eec5386dbb8047c2518971aa461d9b3456 | https://github.com/AtelierConvivialite/webtranslateit/blob/6dcae8eec5386dbb8047c2518971aa461d9b3456/lib/web_translate_it/string.rb#L183-L208 | train |
AtelierConvivialite/webtranslateit | lib/web_translate_it/translation_file.rb | WebTranslateIt.TranslationFile.fetch | def fetch(http_connection, force = false)
success = true
tries ||= 3
display = []
display.push(self.file_path)
display.push "#{StringUtil.checksumify(self.local_checksum.to_s)}..#{StringUtil.checksumify(self.remote_checksum.to_s)}"
if !File.exist?(self.file_path) or force or self.remote_checksum != self.local_checksum
begin
request = Net::HTTP::Get.new(api_url)
WebTranslateIt::Util.add_fields(request)
FileUtils.mkpath(self.file_path.split('/')[0..-2].join('/')) unless File.exist?(self.file_path) or self.file_path.split('/')[0..-2].join('/') == ""
begin
response = http_connection.request(request)
File.open(self.file_path, 'wb'){ |file| file << response.body } if response.code.to_i == 200
display.push Util.handle_response(response)
rescue Timeout::Error
puts StringUtil.failure("Request timeout. Will retry in 5 seconds.")
if (tries -= 1) > 0
sleep(5)
retry
else
success = false
end
rescue
display.push StringUtil.failure("An error occured: #{$!}")
success = false
end
end
else
display.push StringUtil.success("Skipped")
end
print ArrayUtil.to_columns(display)
return success
end | ruby | def fetch(http_connection, force = false)
success = true
tries ||= 3
display = []
display.push(self.file_path)
display.push "#{StringUtil.checksumify(self.local_checksum.to_s)}..#{StringUtil.checksumify(self.remote_checksum.to_s)}"
if !File.exist?(self.file_path) or force or self.remote_checksum != self.local_checksum
begin
request = Net::HTTP::Get.new(api_url)
WebTranslateIt::Util.add_fields(request)
FileUtils.mkpath(self.file_path.split('/')[0..-2].join('/')) unless File.exist?(self.file_path) or self.file_path.split('/')[0..-2].join('/') == ""
begin
response = http_connection.request(request)
File.open(self.file_path, 'wb'){ |file| file << response.body } if response.code.to_i == 200
display.push Util.handle_response(response)
rescue Timeout::Error
puts StringUtil.failure("Request timeout. Will retry in 5 seconds.")
if (tries -= 1) > 0
sleep(5)
retry
else
success = false
end
rescue
display.push StringUtil.failure("An error occured: #{$!}")
success = false
end
end
else
display.push StringUtil.success("Skipped")
end
print ArrayUtil.to_columns(display)
return success
end | [
"def",
"fetch",
"(",
"http_connection",
",",
"force",
"=",
"false",
")",
"success",
"=",
"true",
"tries",
"||=",
"3",
"display",
"=",
"[",
"]",
"display",
".",
"push",
"(",
"self",
".",
"file_path",
")",
"display",
".",
"push",
"\"#{StringUtil.checksumify(self.local_checksum.to_s)}..#{StringUtil.checksumify(self.remote_checksum.to_s)}\"",
"if",
"!",
"File",
".",
"exist?",
"(",
"self",
".",
"file_path",
")",
"or",
"force",
"or",
"self",
".",
"remote_checksum",
"!=",
"self",
".",
"local_checksum",
"begin",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"api_url",
")",
"WebTranslateIt",
"::",
"Util",
".",
"add_fields",
"(",
"request",
")",
"FileUtils",
".",
"mkpath",
"(",
"self",
".",
"file_path",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"..",
"-",
"2",
"]",
".",
"join",
"(",
"'/'",
")",
")",
"unless",
"File",
".",
"exist?",
"(",
"self",
".",
"file_path",
")",
"or",
"self",
".",
"file_path",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"..",
"-",
"2",
"]",
".",
"join",
"(",
"'/'",
")",
"==",
"\"\"",
"begin",
"response",
"=",
"http_connection",
".",
"request",
"(",
"request",
")",
"File",
".",
"open",
"(",
"self",
".",
"file_path",
",",
"'wb'",
")",
"{",
"|",
"file",
"|",
"file",
"<<",
"response",
".",
"body",
"}",
"if",
"response",
".",
"code",
".",
"to_i",
"==",
"200",
"display",
".",
"push",
"Util",
".",
"handle_response",
"(",
"response",
")",
"rescue",
"Timeout",
"::",
"Error",
"puts",
"StringUtil",
".",
"failure",
"(",
"\"Request timeout. Will retry in 5 seconds.\"",
")",
"if",
"(",
"tries",
"-=",
"1",
")",
">",
"0",
"sleep",
"(",
"5",
")",
"retry",
"else",
"success",
"=",
"false",
"end",
"rescue",
"display",
".",
"push",
"StringUtil",
".",
"failure",
"(",
"\"An error occured: #{$!}\"",
")",
"success",
"=",
"false",
"end",
"end",
"else",
"display",
".",
"push",
"StringUtil",
".",
"success",
"(",
"\"Skipped\"",
")",
"end",
"print",
"ArrayUtil",
".",
"to_columns",
"(",
"display",
")",
"return",
"success",
"end"
]
| Fetch a language file.
By default it will make a conditional GET Request, using the `If-Modified-Since` tag.
You can force the method to re-download your file by passing `true` as a second argument
Example of implementation:
configuration = WebTranslateIt::Configuration.new
file = configuration.files.first
file.fetch # the first time, will return the content of the language file with a status 200 OK
file.fetch # returns nothing, with a status 304 Not Modified
file.fetch(true) # force to re-download the file, will return the content of the file with a 200 OK | [
"Fetch",
"a",
"language",
"file",
".",
"By",
"default",
"it",
"will",
"make",
"a",
"conditional",
"GET",
"Request",
"using",
"the",
"If",
"-",
"Modified",
"-",
"Since",
"tag",
".",
"You",
"can",
"force",
"the",
"method",
"to",
"re",
"-",
"download",
"your",
"file",
"by",
"passing",
"true",
"as",
"a",
"second",
"argument"
]
| 6dcae8eec5386dbb8047c2518971aa461d9b3456 | https://github.com/AtelierConvivialite/webtranslateit/blob/6dcae8eec5386dbb8047c2518971aa461d9b3456/lib/web_translate_it/translation_file.rb#L39-L72 | train |
AtelierConvivialite/webtranslateit | lib/web_translate_it/translation_file.rb | WebTranslateIt.TranslationFile.upload | def upload(http_connection, merge=false, ignore_missing=false, label=nil, low_priority=false, minor_changes=false, force=false)
success = true
tries ||= 3
display = []
display.push(self.file_path)
display.push "#{StringUtil.checksumify(self.local_checksum.to_s)}..#{StringUtil.checksumify(self.remote_checksum.to_s)}"
if File.exists?(self.file_path)
if force or self.remote_checksum != self.local_checksum
File.open(self.file_path) do |file|
begin
request = Net::HTTP::Put::Multipart.new(api_url, {"file" => UploadIO.new(file, "text/plain", file.path), "merge" => merge, "ignore_missing" => ignore_missing, "label" => label, "low_priority" => low_priority, "minor_changes" => minor_changes })
WebTranslateIt::Util.add_fields(request)
display.push Util.handle_response(http_connection.request(request))
rescue Timeout::Error
puts StringUtil.failure("Request timeout. Will retry in 5 seconds.")
if (tries -= 1) > 0
sleep(5)
retry
else
success = false
end
rescue
display.push StringUtil.failure("An error occured: #{$!}")
success = false
end
end
else
display.push StringUtil.success("Skipped")
end
puts ArrayUtil.to_columns(display)
else
puts StringUtil.failure("Can't push #{self.file_path}. File doesn't exist.")
end
return success
end | ruby | def upload(http_connection, merge=false, ignore_missing=false, label=nil, low_priority=false, minor_changes=false, force=false)
success = true
tries ||= 3
display = []
display.push(self.file_path)
display.push "#{StringUtil.checksumify(self.local_checksum.to_s)}..#{StringUtil.checksumify(self.remote_checksum.to_s)}"
if File.exists?(self.file_path)
if force or self.remote_checksum != self.local_checksum
File.open(self.file_path) do |file|
begin
request = Net::HTTP::Put::Multipart.new(api_url, {"file" => UploadIO.new(file, "text/plain", file.path), "merge" => merge, "ignore_missing" => ignore_missing, "label" => label, "low_priority" => low_priority, "minor_changes" => minor_changes })
WebTranslateIt::Util.add_fields(request)
display.push Util.handle_response(http_connection.request(request))
rescue Timeout::Error
puts StringUtil.failure("Request timeout. Will retry in 5 seconds.")
if (tries -= 1) > 0
sleep(5)
retry
else
success = false
end
rescue
display.push StringUtil.failure("An error occured: #{$!}")
success = false
end
end
else
display.push StringUtil.success("Skipped")
end
puts ArrayUtil.to_columns(display)
else
puts StringUtil.failure("Can't push #{self.file_path}. File doesn't exist.")
end
return success
end | [
"def",
"upload",
"(",
"http_connection",
",",
"merge",
"=",
"false",
",",
"ignore_missing",
"=",
"false",
",",
"label",
"=",
"nil",
",",
"low_priority",
"=",
"false",
",",
"minor_changes",
"=",
"false",
",",
"force",
"=",
"false",
")",
"success",
"=",
"true",
"tries",
"||=",
"3",
"display",
"=",
"[",
"]",
"display",
".",
"push",
"(",
"self",
".",
"file_path",
")",
"display",
".",
"push",
"\"#{StringUtil.checksumify(self.local_checksum.to_s)}..#{StringUtil.checksumify(self.remote_checksum.to_s)}\"",
"if",
"File",
".",
"exists?",
"(",
"self",
".",
"file_path",
")",
"if",
"force",
"or",
"self",
".",
"remote_checksum",
"!=",
"self",
".",
"local_checksum",
"File",
".",
"open",
"(",
"self",
".",
"file_path",
")",
"do",
"|",
"file",
"|",
"begin",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Put",
"::",
"Multipart",
".",
"new",
"(",
"api_url",
",",
"{",
"\"file\"",
"=>",
"UploadIO",
".",
"new",
"(",
"file",
",",
"\"text/plain\"",
",",
"file",
".",
"path",
")",
",",
"\"merge\"",
"=>",
"merge",
",",
"\"ignore_missing\"",
"=>",
"ignore_missing",
",",
"\"label\"",
"=>",
"label",
",",
"\"low_priority\"",
"=>",
"low_priority",
",",
"\"minor_changes\"",
"=>",
"minor_changes",
"}",
")",
"WebTranslateIt",
"::",
"Util",
".",
"add_fields",
"(",
"request",
")",
"display",
".",
"push",
"Util",
".",
"handle_response",
"(",
"http_connection",
".",
"request",
"(",
"request",
")",
")",
"rescue",
"Timeout",
"::",
"Error",
"puts",
"StringUtil",
".",
"failure",
"(",
"\"Request timeout. Will retry in 5 seconds.\"",
")",
"if",
"(",
"tries",
"-=",
"1",
")",
">",
"0",
"sleep",
"(",
"5",
")",
"retry",
"else",
"success",
"=",
"false",
"end",
"rescue",
"display",
".",
"push",
"StringUtil",
".",
"failure",
"(",
"\"An error occured: #{$!}\"",
")",
"success",
"=",
"false",
"end",
"end",
"else",
"display",
".",
"push",
"StringUtil",
".",
"success",
"(",
"\"Skipped\"",
")",
"end",
"puts",
"ArrayUtil",
".",
"to_columns",
"(",
"display",
")",
"else",
"puts",
"StringUtil",
".",
"failure",
"(",
"\"Can't push #{self.file_path}. File doesn't exist.\"",
")",
"end",
"return",
"success",
"end"
]
| Update a language file to Web Translate It by performing a PUT Request.
Example of implementation:
configuration = WebTranslateIt::Configuration.new
locale = configuration.locales.first
file = configuration.files.first
file.upload # should respond the HTTP code 202 Accepted
Note that the request might or might not eventually be acted upon, as it might be disallowed when processing
actually takes place. This is due to the fact that language file imports are handled by background processing. | [
"Update",
"a",
"language",
"file",
"to",
"Web",
"Translate",
"It",
"by",
"performing",
"a",
"PUT",
"Request",
"."
]
| 6dcae8eec5386dbb8047c2518971aa461d9b3456 | https://github.com/AtelierConvivialite/webtranslateit/blob/6dcae8eec5386dbb8047c2518971aa461d9b3456/lib/web_translate_it/translation_file.rb#L85-L119 | train |
AtelierConvivialite/webtranslateit | lib/web_translate_it/translation_file.rb | WebTranslateIt.TranslationFile.create | def create(http_connection, low_priority=false)
success = true
tries ||= 3
display = []
display.push file_path
display.push "#{StringUtil.checksumify(self.local_checksum.to_s)}..[ ]"
if File.exists?(self.file_path)
File.open(self.file_path) do |file|
begin
request = Net::HTTP::Post::Multipart.new(api_url_for_create, { "name" => self.file_path, "file" => UploadIO.new(file, "text/plain", file.path), "low_priority" => low_priority })
WebTranslateIt::Util.add_fields(request)
display.push Util.handle_response(http_connection.request(request))
puts ArrayUtil.to_columns(display)
rescue Timeout::Error
puts StringUtil.failure("Request timeout. Will retry in 5 seconds.")
if (tries -= 1) > 0
sleep(5)
retry
else
success = false
end
rescue
display.push StringUtil.failure("An error occured: #{$!}")
success = false
end
end
else
puts StringUtil.failure("\nFile #{self.file_path} doesn't exist!")
end
return success
end | ruby | def create(http_connection, low_priority=false)
success = true
tries ||= 3
display = []
display.push file_path
display.push "#{StringUtil.checksumify(self.local_checksum.to_s)}..[ ]"
if File.exists?(self.file_path)
File.open(self.file_path) do |file|
begin
request = Net::HTTP::Post::Multipart.new(api_url_for_create, { "name" => self.file_path, "file" => UploadIO.new(file, "text/plain", file.path), "low_priority" => low_priority })
WebTranslateIt::Util.add_fields(request)
display.push Util.handle_response(http_connection.request(request))
puts ArrayUtil.to_columns(display)
rescue Timeout::Error
puts StringUtil.failure("Request timeout. Will retry in 5 seconds.")
if (tries -= 1) > 0
sleep(5)
retry
else
success = false
end
rescue
display.push StringUtil.failure("An error occured: #{$!}")
success = false
end
end
else
puts StringUtil.failure("\nFile #{self.file_path} doesn't exist!")
end
return success
end | [
"def",
"create",
"(",
"http_connection",
",",
"low_priority",
"=",
"false",
")",
"success",
"=",
"true",
"tries",
"||=",
"3",
"display",
"=",
"[",
"]",
"display",
".",
"push",
"file_path",
"display",
".",
"push",
"\"#{StringUtil.checksumify(self.local_checksum.to_s)}..[ ]\"",
"if",
"File",
".",
"exists?",
"(",
"self",
".",
"file_path",
")",
"File",
".",
"open",
"(",
"self",
".",
"file_path",
")",
"do",
"|",
"file",
"|",
"begin",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
"::",
"Multipart",
".",
"new",
"(",
"api_url_for_create",
",",
"{",
"\"name\"",
"=>",
"self",
".",
"file_path",
",",
"\"file\"",
"=>",
"UploadIO",
".",
"new",
"(",
"file",
",",
"\"text/plain\"",
",",
"file",
".",
"path",
")",
",",
"\"low_priority\"",
"=>",
"low_priority",
"}",
")",
"WebTranslateIt",
"::",
"Util",
".",
"add_fields",
"(",
"request",
")",
"display",
".",
"push",
"Util",
".",
"handle_response",
"(",
"http_connection",
".",
"request",
"(",
"request",
")",
")",
"puts",
"ArrayUtil",
".",
"to_columns",
"(",
"display",
")",
"rescue",
"Timeout",
"::",
"Error",
"puts",
"StringUtil",
".",
"failure",
"(",
"\"Request timeout. Will retry in 5 seconds.\"",
")",
"if",
"(",
"tries",
"-=",
"1",
")",
">",
"0",
"sleep",
"(",
"5",
")",
"retry",
"else",
"success",
"=",
"false",
"end",
"rescue",
"display",
".",
"push",
"StringUtil",
".",
"failure",
"(",
"\"An error occured: #{$!}\"",
")",
"success",
"=",
"false",
"end",
"end",
"else",
"puts",
"StringUtil",
".",
"failure",
"(",
"\"\\nFile #{self.file_path} doesn't exist!\"",
")",
"end",
"return",
"success",
"end"
]
| Create a master language file to Web Translate It by performing a POST Request.
Example of implementation:
configuration = WebTranslateIt::Configuration.new
file = TranslationFile.new(nil, file_path, nil, configuration.api_key)
file.create # should respond the HTTP code 201 Created
Note that the request might or might not eventually be acted upon, as it might be disallowed when processing
actually takes place. This is due to the fact that language file imports are handled by background processing. | [
"Create",
"a",
"master",
"language",
"file",
"to",
"Web",
"Translate",
"It",
"by",
"performing",
"a",
"POST",
"Request",
"."
]
| 6dcae8eec5386dbb8047c2518971aa461d9b3456 | https://github.com/AtelierConvivialite/webtranslateit/blob/6dcae8eec5386dbb8047c2518971aa461d9b3456/lib/web_translate_it/translation_file.rb#L132-L162 | train |
AtelierConvivialite/webtranslateit | lib/web_translate_it/translation_file.rb | WebTranslateIt.TranslationFile.delete | def delete(http_connection)
success = true
tries ||= 3
display = []
display.push file_path
if File.exists?(self.file_path)
File.open(self.file_path) do |file|
begin
request = Net::HTTP::Delete.new(api_url_for_delete)
WebTranslateIt::Util.add_fields(request)
display.push Util.handle_response(http_connection.request(request))
puts ArrayUtil.to_columns(display)
rescue Timeout::Error
puts StringUtil.failure("Request timeout. Will retry in 5 seconds.")
if (tries -= 1) > 0
sleep(5)
retry
else
success = false
end
rescue
display.push StringUtil.failure("An error occured: #{$!}")
success = false
end
end
else
puts StringUtil.failure("\nFile #{self.file_path} doesn't exist!")
end
return success
end | ruby | def delete(http_connection)
success = true
tries ||= 3
display = []
display.push file_path
if File.exists?(self.file_path)
File.open(self.file_path) do |file|
begin
request = Net::HTTP::Delete.new(api_url_for_delete)
WebTranslateIt::Util.add_fields(request)
display.push Util.handle_response(http_connection.request(request))
puts ArrayUtil.to_columns(display)
rescue Timeout::Error
puts StringUtil.failure("Request timeout. Will retry in 5 seconds.")
if (tries -= 1) > 0
sleep(5)
retry
else
success = false
end
rescue
display.push StringUtil.failure("An error occured: #{$!}")
success = false
end
end
else
puts StringUtil.failure("\nFile #{self.file_path} doesn't exist!")
end
return success
end | [
"def",
"delete",
"(",
"http_connection",
")",
"success",
"=",
"true",
"tries",
"||=",
"3",
"display",
"=",
"[",
"]",
"display",
".",
"push",
"file_path",
"if",
"File",
".",
"exists?",
"(",
"self",
".",
"file_path",
")",
"File",
".",
"open",
"(",
"self",
".",
"file_path",
")",
"do",
"|",
"file",
"|",
"begin",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Delete",
".",
"new",
"(",
"api_url_for_delete",
")",
"WebTranslateIt",
"::",
"Util",
".",
"add_fields",
"(",
"request",
")",
"display",
".",
"push",
"Util",
".",
"handle_response",
"(",
"http_connection",
".",
"request",
"(",
"request",
")",
")",
"puts",
"ArrayUtil",
".",
"to_columns",
"(",
"display",
")",
"rescue",
"Timeout",
"::",
"Error",
"puts",
"StringUtil",
".",
"failure",
"(",
"\"Request timeout. Will retry in 5 seconds.\"",
")",
"if",
"(",
"tries",
"-=",
"1",
")",
">",
"0",
"sleep",
"(",
"5",
")",
"retry",
"else",
"success",
"=",
"false",
"end",
"rescue",
"display",
".",
"push",
"StringUtil",
".",
"failure",
"(",
"\"An error occured: #{$!}\"",
")",
"success",
"=",
"false",
"end",
"end",
"else",
"puts",
"StringUtil",
".",
"failure",
"(",
"\"\\nFile #{self.file_path} doesn't exist!\"",
")",
"end",
"return",
"success",
"end"
]
| Delete a master language file from Web Translate It by performing a DELETE Request. | [
"Delete",
"a",
"master",
"language",
"file",
"from",
"Web",
"Translate",
"It",
"by",
"performing",
"a",
"DELETE",
"Request",
"."
]
| 6dcae8eec5386dbb8047c2518971aa461d9b3456 | https://github.com/AtelierConvivialite/webtranslateit/blob/6dcae8eec5386dbb8047c2518971aa461d9b3456/lib/web_translate_it/translation_file.rb#L166-L195 | train |
stephenb/sendgrid | lib/sendgrid.rb | SendGrid.ClassMethods.sendgrid_enable | def sendgrid_enable(*options)
self.default_sg_options = Array.new unless self.default_sg_options
options.each { |option| self.default_sg_options << option if VALID_OPTIONS.include?(option) }
end | ruby | def sendgrid_enable(*options)
self.default_sg_options = Array.new unless self.default_sg_options
options.each { |option| self.default_sg_options << option if VALID_OPTIONS.include?(option) }
end | [
"def",
"sendgrid_enable",
"(",
"*",
"options",
")",
"self",
".",
"default_sg_options",
"=",
"Array",
".",
"new",
"unless",
"self",
".",
"default_sg_options",
"options",
".",
"each",
"{",
"|",
"option",
"|",
"self",
".",
"default_sg_options",
"<<",
"option",
"if",
"VALID_OPTIONS",
".",
"include?",
"(",
"option",
")",
"}",
"end"
]
| Enables a default option for all emails.
See documentation for details.
Supported options:
* :opentrack
* :clicktrack
* :ganalytics
* :gravatar
* :subscriptiontrack
* :footer
* :spamcheck | [
"Enables",
"a",
"default",
"option",
"for",
"all",
"emails",
".",
"See",
"documentation",
"for",
"details",
"."
]
| 8b718643d02ba1cd957b8a7835dd9d75c3681ac7 | https://github.com/stephenb/sendgrid/blob/8b718643d02ba1cd957b8a7835dd9d75c3681ac7/lib/sendgrid.rb#L66-L69 | train |
ruby-concurrency/thread_safe | lib/thread_safe/atomic_reference_cache_backend.rb | ThreadSafe.AtomicReferenceCacheBackend.clear | def clear
return self unless current_table = table
current_table_size = current_table.size
deleted_count = i = 0
while i < current_table_size
if !(node = current_table.volatile_get(i))
i += 1
elsif (node_hash = node.hash) == MOVED
current_table = node.key
current_table_size = current_table.size
elsif Node.locked_hash?(node_hash)
decrement_size(deleted_count) # opportunistically update count
deleted_count = 0
node.try_await_lock(current_table, i)
else
current_table.try_lock_via_hash(i, node, node_hash) do
begin
deleted_count += 1 if NULL != node.value # recheck under lock
node.value = nil
end while node = node.next
current_table.volatile_set(i, nil)
i += 1
end
end
end
decrement_size(deleted_count)
self
end | ruby | def clear
return self unless current_table = table
current_table_size = current_table.size
deleted_count = i = 0
while i < current_table_size
if !(node = current_table.volatile_get(i))
i += 1
elsif (node_hash = node.hash) == MOVED
current_table = node.key
current_table_size = current_table.size
elsif Node.locked_hash?(node_hash)
decrement_size(deleted_count) # opportunistically update count
deleted_count = 0
node.try_await_lock(current_table, i)
else
current_table.try_lock_via_hash(i, node, node_hash) do
begin
deleted_count += 1 if NULL != node.value # recheck under lock
node.value = nil
end while node = node.next
current_table.volatile_set(i, nil)
i += 1
end
end
end
decrement_size(deleted_count)
self
end | [
"def",
"clear",
"return",
"self",
"unless",
"current_table",
"=",
"table",
"current_table_size",
"=",
"current_table",
".",
"size",
"deleted_count",
"=",
"i",
"=",
"0",
"while",
"i",
"<",
"current_table_size",
"if",
"!",
"(",
"node",
"=",
"current_table",
".",
"volatile_get",
"(",
"i",
")",
")",
"i",
"+=",
"1",
"elsif",
"(",
"node_hash",
"=",
"node",
".",
"hash",
")",
"==",
"MOVED",
"current_table",
"=",
"node",
".",
"key",
"current_table_size",
"=",
"current_table",
".",
"size",
"elsif",
"Node",
".",
"locked_hash?",
"(",
"node_hash",
")",
"decrement_size",
"(",
"deleted_count",
")",
"deleted_count",
"=",
"0",
"node",
".",
"try_await_lock",
"(",
"current_table",
",",
"i",
")",
"else",
"current_table",
".",
"try_lock_via_hash",
"(",
"i",
",",
"node",
",",
"node_hash",
")",
"do",
"begin",
"deleted_count",
"+=",
"1",
"if",
"NULL",
"!=",
"node",
".",
"value",
"node",
".",
"value",
"=",
"nil",
"end",
"while",
"node",
"=",
"node",
".",
"next",
"current_table",
".",
"volatile_set",
"(",
"i",
",",
"nil",
")",
"i",
"+=",
"1",
"end",
"end",
"end",
"decrement_size",
"(",
"deleted_count",
")",
"self",
"end"
]
| Implementation for clear. Steps through each bin, removing all nodes. | [
"Implementation",
"for",
"clear",
".",
"Steps",
"through",
"each",
"bin",
"removing",
"all",
"nodes",
"."
]
| 39fc4a490c7ed881657ea49cd37d293de13b6d4e | https://github.com/ruby-concurrency/thread_safe/blob/39fc4a490c7ed881657ea49cd37d293de13b6d4e/lib/thread_safe/atomic_reference_cache_backend.rb#L529-L556 | train |
ruby-concurrency/thread_safe | lib/thread_safe/atomic_reference_cache_backend.rb | ThreadSafe.AtomicReferenceCacheBackend.initialize_table | def initialize_table
until current_table ||= table
if (size_ctrl = size_control) == NOW_RESIZING
Thread.pass # lost initialization race; just spin
else
try_in_resize_lock(current_table, size_ctrl) do
initial_size = size_ctrl > 0 ? size_ctrl : DEFAULT_CAPACITY
current_table = self.table = Table.new(initial_size)
initial_size - (initial_size >> 2) # 75% load factor
end
end
end
current_table
end | ruby | def initialize_table
until current_table ||= table
if (size_ctrl = size_control) == NOW_RESIZING
Thread.pass # lost initialization race; just spin
else
try_in_resize_lock(current_table, size_ctrl) do
initial_size = size_ctrl > 0 ? size_ctrl : DEFAULT_CAPACITY
current_table = self.table = Table.new(initial_size)
initial_size - (initial_size >> 2) # 75% load factor
end
end
end
current_table
end | [
"def",
"initialize_table",
"until",
"current_table",
"||=",
"table",
"if",
"(",
"size_ctrl",
"=",
"size_control",
")",
"==",
"NOW_RESIZING",
"Thread",
".",
"pass",
"else",
"try_in_resize_lock",
"(",
"current_table",
",",
"size_ctrl",
")",
"do",
"initial_size",
"=",
"size_ctrl",
">",
"0",
"?",
"size_ctrl",
":",
"DEFAULT_CAPACITY",
"current_table",
"=",
"self",
".",
"table",
"=",
"Table",
".",
"new",
"(",
"initial_size",
")",
"initial_size",
"-",
"(",
"initial_size",
">>",
"2",
")",
"end",
"end",
"end",
"current_table",
"end"
]
| Initializes table, using the size recorded in +size_control+. | [
"Initializes",
"table",
"using",
"the",
"size",
"recorded",
"in",
"+",
"size_control",
"+",
"."
]
| 39fc4a490c7ed881657ea49cd37d293de13b6d4e | https://github.com/ruby-concurrency/thread_safe/blob/39fc4a490c7ed881657ea49cd37d293de13b6d4e/lib/thread_safe/atomic_reference_cache_backend.rb#L761-L774 | train |
ruby-concurrency/thread_safe | lib/thread_safe/atomic_reference_cache_backend.rb | ThreadSafe.AtomicReferenceCacheBackend.check_for_resize | def check_for_resize
while (current_table = table) && MAX_CAPACITY > (table_size = current_table.size) && NOW_RESIZING != (size_ctrl = size_control) && size_ctrl < @counter.sum
try_in_resize_lock(current_table, size_ctrl) do
self.table = rebuild(current_table)
(table_size << 1) - (table_size >> 1) # 75% load factor
end
end
end | ruby | def check_for_resize
while (current_table = table) && MAX_CAPACITY > (table_size = current_table.size) && NOW_RESIZING != (size_ctrl = size_control) && size_ctrl < @counter.sum
try_in_resize_lock(current_table, size_ctrl) do
self.table = rebuild(current_table)
(table_size << 1) - (table_size >> 1) # 75% load factor
end
end
end | [
"def",
"check_for_resize",
"while",
"(",
"current_table",
"=",
"table",
")",
"&&",
"MAX_CAPACITY",
">",
"(",
"table_size",
"=",
"current_table",
".",
"size",
")",
"&&",
"NOW_RESIZING",
"!=",
"(",
"size_ctrl",
"=",
"size_control",
")",
"&&",
"size_ctrl",
"<",
"@counter",
".",
"sum",
"try_in_resize_lock",
"(",
"current_table",
",",
"size_ctrl",
")",
"do",
"self",
".",
"table",
"=",
"rebuild",
"(",
"current_table",
")",
"(",
"table_size",
"<<",
"1",
")",
"-",
"(",
"table_size",
">>",
"1",
")",
"end",
"end",
"end"
]
| If table is too small and not already resizing, creates next table and
transfers bins. Rechecks occupancy after a transfer to see if another
resize is already needed because resizings are lagging additions. | [
"If",
"table",
"is",
"too",
"small",
"and",
"not",
"already",
"resizing",
"creates",
"next",
"table",
"and",
"transfers",
"bins",
".",
"Rechecks",
"occupancy",
"after",
"a",
"transfer",
"to",
"see",
"if",
"another",
"resize",
"is",
"already",
"needed",
"because",
"resizings",
"are",
"lagging",
"additions",
"."
]
| 39fc4a490c7ed881657ea49cd37d293de13b6d4e | https://github.com/ruby-concurrency/thread_safe/blob/39fc4a490c7ed881657ea49cd37d293de13b6d4e/lib/thread_safe/atomic_reference_cache_backend.rb#L779-L786 | train |
ruby-concurrency/thread_safe | lib/thread_safe/atomic_reference_cache_backend.rb | ThreadSafe.AtomicReferenceCacheBackend.split_old_bin | def split_old_bin(table, new_table, i, node, node_hash, forwarder)
table.try_lock_via_hash(i, node, node_hash) do
split_bin(new_table, i, node, node_hash)
table.volatile_set(i, forwarder)
end
end | ruby | def split_old_bin(table, new_table, i, node, node_hash, forwarder)
table.try_lock_via_hash(i, node, node_hash) do
split_bin(new_table, i, node, node_hash)
table.volatile_set(i, forwarder)
end
end | [
"def",
"split_old_bin",
"(",
"table",
",",
"new_table",
",",
"i",
",",
"node",
",",
"node_hash",
",",
"forwarder",
")",
"table",
".",
"try_lock_via_hash",
"(",
"i",
",",
"node",
",",
"node_hash",
")",
"do",
"split_bin",
"(",
"new_table",
",",
"i",
",",
"node",
",",
"node_hash",
")",
"table",
".",
"volatile_set",
"(",
"i",
",",
"forwarder",
")",
"end",
"end"
]
| Splits a normal bin with list headed by e into lo and hi parts; installs in given table. | [
"Splits",
"a",
"normal",
"bin",
"with",
"list",
"headed",
"by",
"e",
"into",
"lo",
"and",
"hi",
"parts",
";",
"installs",
"in",
"given",
"table",
"."
]
| 39fc4a490c7ed881657ea49cd37d293de13b6d4e | https://github.com/ruby-concurrency/thread_safe/blob/39fc4a490c7ed881657ea49cd37d293de13b6d4e/lib/thread_safe/atomic_reference_cache_backend.rb#L860-L865 | train |
knife-block/knife-block | lib/chef/knife/block.rb | GreenAndSecure.BlockList.run | def run
GreenAndSecure::check_block_setup
puts "The available chef servers are:"
servers.each do |server|
if server == current_server then
puts "\t* #{server} [ Currently Selected ]"
else
puts "\t* #{server}"
end
end
end | ruby | def run
GreenAndSecure::check_block_setup
puts "The available chef servers are:"
servers.each do |server|
if server == current_server then
puts "\t* #{server} [ Currently Selected ]"
else
puts "\t* #{server}"
end
end
end | [
"def",
"run",
"GreenAndSecure",
"::",
"check_block_setup",
"puts",
"\"The available chef servers are:\"",
"servers",
".",
"each",
"do",
"|",
"server",
"|",
"if",
"server",
"==",
"current_server",
"then",
"puts",
"\"\\t* #{server} [ Currently Selected ]\"",
"else",
"puts",
"\"\\t* #{server}\"",
"end",
"end",
"end"
]
| list the available environments | [
"list",
"the",
"available",
"environments"
]
| 9ee7f991c7f8400b608e65f6dffa0bd4cf1b2524 | https://github.com/knife-block/knife-block/blob/9ee7f991c7f8400b608e65f6dffa0bd4cf1b2524/lib/chef/knife/block.rb#L144-L154 | train |
sidoh/alexa_verifier | lib/alexa_verifier/verifier.rb | AlexaVerifier.Verifier.valid? | def valid?(request)
begin
valid!(request)
rescue AlexaVerifier::BaseError => e
puts e
return false
end
true
end | ruby | def valid?(request)
begin
valid!(request)
rescue AlexaVerifier::BaseError => e
puts e
return false
end
true
end | [
"def",
"valid?",
"(",
"request",
")",
"begin",
"valid!",
"(",
"request",
")",
"rescue",
"AlexaVerifier",
"::",
"BaseError",
"=>",
"e",
"puts",
"e",
"return",
"false",
"end",
"true",
"end"
]
| Validate a request object from Rack.
Return a boolean.
@param [Rack::Request::Env] request a Rack HTTP Request
@return [Boolean] is the request valid? | [
"Validate",
"a",
"request",
"object",
"from",
"Rack",
".",
"Return",
"a",
"boolean",
"."
]
| bfb49d091cfbef661f9b1ff7a858cb5d9d09f473 | https://github.com/sidoh/alexa_verifier/blob/bfb49d091cfbef661f9b1ff7a858cb5d9d09f473/lib/alexa_verifier/verifier.rb#L49-L59 | train |
sidoh/alexa_verifier | lib/alexa_verifier/verifier.rb | AlexaVerifier.Verifier.check_that_request_is_timely | def check_that_request_is_timely(raw_body)
request_json = JSON.parse(raw_body)
raise AlexaVerifier::InvalidRequestError, 'Timestamp field not present in request' if request_json.fetch('request', {}).fetch('timestamp', nil).nil?
request_is_timely = (Time.parse(request_json['request']['timestamp'].to_s) >= (Time.now - REQUEST_THRESHOLD))
raise AlexaVerifier::InvalidRequestError, "Request is from more than #{REQUEST_THRESHOLD} seconds ago" unless request_is_timely
end | ruby | def check_that_request_is_timely(raw_body)
request_json = JSON.parse(raw_body)
raise AlexaVerifier::InvalidRequestError, 'Timestamp field not present in request' if request_json.fetch('request', {}).fetch('timestamp', nil).nil?
request_is_timely = (Time.parse(request_json['request']['timestamp'].to_s) >= (Time.now - REQUEST_THRESHOLD))
raise AlexaVerifier::InvalidRequestError, "Request is from more than #{REQUEST_THRESHOLD} seconds ago" unless request_is_timely
end | [
"def",
"check_that_request_is_timely",
"(",
"raw_body",
")",
"request_json",
"=",
"JSON",
".",
"parse",
"(",
"raw_body",
")",
"raise",
"AlexaVerifier",
"::",
"InvalidRequestError",
",",
"'Timestamp field not present in request'",
"if",
"request_json",
".",
"fetch",
"(",
"'request'",
",",
"{",
"}",
")",
".",
"fetch",
"(",
"'timestamp'",
",",
"nil",
")",
".",
"nil?",
"request_is_timely",
"=",
"(",
"Time",
".",
"parse",
"(",
"request_json",
"[",
"'request'",
"]",
"[",
"'timestamp'",
"]",
".",
"to_s",
")",
">=",
"(",
"Time",
".",
"now",
"-",
"REQUEST_THRESHOLD",
")",
")",
"raise",
"AlexaVerifier",
"::",
"InvalidRequestError",
",",
"\"Request is from more than #{REQUEST_THRESHOLD} seconds ago\"",
"unless",
"request_is_timely",
"end"
]
| Prevent replays of requests by checking that they are timely.
@param [String] raw_body the raw body of our https request
@raise [AlexaVerifier::InvalidRequestError] raised when the timestamp is not timely, or is not set | [
"Prevent",
"replays",
"of",
"requests",
"by",
"checking",
"that",
"they",
"are",
"timely",
"."
]
| bfb49d091cfbef661f9b1ff7a858cb5d9d09f473 | https://github.com/sidoh/alexa_verifier/blob/bfb49d091cfbef661f9b1ff7a858cb5d9d09f473/lib/alexa_verifier/verifier.rb#L80-L87 | train |
sidoh/alexa_verifier | lib/alexa_verifier/verifier.rb | AlexaVerifier.Verifier.check_that_request_is_valid | def check_that_request_is_valid(signature_certificate_url, request, raw_body)
certificate, chain = AlexaVerifier::CertificateStore.fetch(signature_certificate_url) if @configuration.verify_certificate? || @configuration.verify_signature?
begin
AlexaVerifier::Verifier::CertificateVerifier.valid!(certificate, chain) if @configuration.verify_certificate?
check_that_request_was_signed(certificate.public_key, request, raw_body) if @configuration.verify_signature?
rescue AlexaVerifier::InvalidCertificateError, AlexaVerifier::InvalidRequestError => error
# We don't want to cache a certificate that fails our checks as it could lock us out of valid requests for the cache length
AlexaVerifier::CertificateStore.delete(signature_certificate_url)
raise error
end
end | ruby | def check_that_request_is_valid(signature_certificate_url, request, raw_body)
certificate, chain = AlexaVerifier::CertificateStore.fetch(signature_certificate_url) if @configuration.verify_certificate? || @configuration.verify_signature?
begin
AlexaVerifier::Verifier::CertificateVerifier.valid!(certificate, chain) if @configuration.verify_certificate?
check_that_request_was_signed(certificate.public_key, request, raw_body) if @configuration.verify_signature?
rescue AlexaVerifier::InvalidCertificateError, AlexaVerifier::InvalidRequestError => error
# We don't want to cache a certificate that fails our checks as it could lock us out of valid requests for the cache length
AlexaVerifier::CertificateStore.delete(signature_certificate_url)
raise error
end
end | [
"def",
"check_that_request_is_valid",
"(",
"signature_certificate_url",
",",
"request",
",",
"raw_body",
")",
"certificate",
",",
"chain",
"=",
"AlexaVerifier",
"::",
"CertificateStore",
".",
"fetch",
"(",
"signature_certificate_url",
")",
"if",
"@configuration",
".",
"verify_certificate?",
"||",
"@configuration",
".",
"verify_signature?",
"begin",
"AlexaVerifier",
"::",
"Verifier",
"::",
"CertificateVerifier",
".",
"valid!",
"(",
"certificate",
",",
"chain",
")",
"if",
"@configuration",
".",
"verify_certificate?",
"check_that_request_was_signed",
"(",
"certificate",
".",
"public_key",
",",
"request",
",",
"raw_body",
")",
"if",
"@configuration",
".",
"verify_signature?",
"rescue",
"AlexaVerifier",
"::",
"InvalidCertificateError",
",",
"AlexaVerifier",
"::",
"InvalidRequestError",
"=>",
"error",
"AlexaVerifier",
"::",
"CertificateStore",
".",
"delete",
"(",
"signature_certificate_url",
")",
"raise",
"error",
"end",
"end"
]
| Check that our request is valid.
@param [String] signature_certificate_url the url for our signing certificate
@param [Rack::Request::Env] request the request object
@param [String] raw_body the raw body of our https request | [
"Check",
"that",
"our",
"request",
"is",
"valid",
"."
]
| bfb49d091cfbef661f9b1ff7a858cb5d9d09f473 | https://github.com/sidoh/alexa_verifier/blob/bfb49d091cfbef661f9b1ff7a858cb5d9d09f473/lib/alexa_verifier/verifier.rb#L94-L107 | train |
sidoh/alexa_verifier | lib/alexa_verifier/verifier.rb | AlexaVerifier.Verifier.check_that_request_was_signed | def check_that_request_was_signed(certificate_public_key, request, raw_body)
signed_by_certificate = certificate_public_key.verify(
OpenSSL::Digest::SHA1.new,
Base64.decode64(request.env['HTTP_SIGNATURE']),
raw_body
)
raise AlexaVerifier::InvalidRequestError, 'Signature does not match certificate provided' unless signed_by_certificate
end | ruby | def check_that_request_was_signed(certificate_public_key, request, raw_body)
signed_by_certificate = certificate_public_key.verify(
OpenSSL::Digest::SHA1.new,
Base64.decode64(request.env['HTTP_SIGNATURE']),
raw_body
)
raise AlexaVerifier::InvalidRequestError, 'Signature does not match certificate provided' unless signed_by_certificate
end | [
"def",
"check_that_request_was_signed",
"(",
"certificate_public_key",
",",
"request",
",",
"raw_body",
")",
"signed_by_certificate",
"=",
"certificate_public_key",
".",
"verify",
"(",
"OpenSSL",
"::",
"Digest",
"::",
"SHA1",
".",
"new",
",",
"Base64",
".",
"decode64",
"(",
"request",
".",
"env",
"[",
"'HTTP_SIGNATURE'",
"]",
")",
",",
"raw_body",
")",
"raise",
"AlexaVerifier",
"::",
"InvalidRequestError",
",",
"'Signature does not match certificate provided'",
"unless",
"signed_by_certificate",
"end"
]
| Check that our request was signed by a given public key.
@param [OpenSSL::PKey::PKey] certificate_public_key the public key we are checking
@param [Rack::Request::Env] request the request object we are checking
@param [String] raw_body the raw body of our https request
@raise [AlexaVerifier::InvalidRequestError] raised if our signature does not match the certificate provided | [
"Check",
"that",
"our",
"request",
"was",
"signed",
"by",
"a",
"given",
"public",
"key",
"."
]
| bfb49d091cfbef661f9b1ff7a858cb5d9d09f473 | https://github.com/sidoh/alexa_verifier/blob/bfb49d091cfbef661f9b1ff7a858cb5d9d09f473/lib/alexa_verifier/verifier.rb#L115-L123 | train |
kevinrood/teamcity_formatter | lib/team_city_formatter/formatter.rb | TeamCityFormatter.Formatter.before_feature_element | def before_feature_element(cuke_feature_element)
if cuke_feature_element.is_a?(Cucumber::Core::Ast::Scenario)
before_scenario(cuke_feature_element)
elsif cuke_feature_element.is_a?(Cucumber::Core::Ast::ScenarioOutline)
before_scenario_outline(cuke_feature_element)
else
raise("unsupported feature element `#{cuke_feature_element.class.name}`")
end
end | ruby | def before_feature_element(cuke_feature_element)
if cuke_feature_element.is_a?(Cucumber::Core::Ast::Scenario)
before_scenario(cuke_feature_element)
elsif cuke_feature_element.is_a?(Cucumber::Core::Ast::ScenarioOutline)
before_scenario_outline(cuke_feature_element)
else
raise("unsupported feature element `#{cuke_feature_element.class.name}`")
end
end | [
"def",
"before_feature_element",
"(",
"cuke_feature_element",
")",
"if",
"cuke_feature_element",
".",
"is_a?",
"(",
"Cucumber",
"::",
"Core",
"::",
"Ast",
"::",
"Scenario",
")",
"before_scenario",
"(",
"cuke_feature_element",
")",
"elsif",
"cuke_feature_element",
".",
"is_a?",
"(",
"Cucumber",
"::",
"Core",
"::",
"Ast",
"::",
"ScenarioOutline",
")",
"before_scenario_outline",
"(",
"cuke_feature_element",
")",
"else",
"raise",
"(",
"\"unsupported feature element `#{cuke_feature_element.class.name}`\"",
")",
"end",
"end"
]
| this method gets called before a scenario or scenario outline
we dispatch to our own more specific methods | [
"this",
"method",
"gets",
"called",
"before",
"a",
"scenario",
"or",
"scenario",
"outline",
"we",
"dispatch",
"to",
"our",
"own",
"more",
"specific",
"methods"
]
| d4f2e35b508479b6469f3a7e1d1779948abb4ccb | https://github.com/kevinrood/teamcity_formatter/blob/d4f2e35b508479b6469f3a7e1d1779948abb4ccb/lib/team_city_formatter/formatter.rb#L30-L38 | train |
kevinrood/teamcity_formatter | lib/team_city_formatter/formatter.rb | TeamCityFormatter.Formatter.after_feature_element | def after_feature_element(cuke_feature_element)
if cuke_feature_element.is_a?(Cucumber::Formatter::LegacyApi::Ast::Scenario)
after_scenario(cuke_feature_element)
elsif cuke_feature_element.is_a?(Cucumber::Formatter::LegacyApi::Ast::ScenarioOutline)
after_scenario_outline(cuke_feature_element)
else
raise("unsupported feature element `#{cuke_feature_element.class.name}`")
end
@exception = nil
@scenario = nil
@scenario_outline = nil
end | ruby | def after_feature_element(cuke_feature_element)
if cuke_feature_element.is_a?(Cucumber::Formatter::LegacyApi::Ast::Scenario)
after_scenario(cuke_feature_element)
elsif cuke_feature_element.is_a?(Cucumber::Formatter::LegacyApi::Ast::ScenarioOutline)
after_scenario_outline(cuke_feature_element)
else
raise("unsupported feature element `#{cuke_feature_element.class.name}`")
end
@exception = nil
@scenario = nil
@scenario_outline = nil
end | [
"def",
"after_feature_element",
"(",
"cuke_feature_element",
")",
"if",
"cuke_feature_element",
".",
"is_a?",
"(",
"Cucumber",
"::",
"Formatter",
"::",
"LegacyApi",
"::",
"Ast",
"::",
"Scenario",
")",
"after_scenario",
"(",
"cuke_feature_element",
")",
"elsif",
"cuke_feature_element",
".",
"is_a?",
"(",
"Cucumber",
"::",
"Formatter",
"::",
"LegacyApi",
"::",
"Ast",
"::",
"ScenarioOutline",
")",
"after_scenario_outline",
"(",
"cuke_feature_element",
")",
"else",
"raise",
"(",
"\"unsupported feature element `#{cuke_feature_element.class.name}`\"",
")",
"end",
"@exception",
"=",
"nil",
"@scenario",
"=",
"nil",
"@scenario_outline",
"=",
"nil",
"end"
]
| this method gets called after a scenario or scenario outline
we dispatch to our own more specific methods | [
"this",
"method",
"gets",
"called",
"after",
"a",
"scenario",
"or",
"scenario",
"outline",
"we",
"dispatch",
"to",
"our",
"own",
"more",
"specific",
"methods"
]
| d4f2e35b508479b6469f3a7e1d1779948abb4ccb | https://github.com/kevinrood/teamcity_formatter/blob/d4f2e35b508479b6469f3a7e1d1779948abb4ccb/lib/team_city_formatter/formatter.rb#L42-L54 | train |
kevinrood/teamcity_formatter | lib/team_city_formatter/formatter.rb | TeamCityFormatter.Formatter.before_table_row | def before_table_row(cuke_table_row)
if cuke_table_row.is_a?(Cucumber::Formatter::LegacyApi::ExampleTableRow)
is_not_header_row = (@scenario_outline.example_column_names != cuke_table_row.values)
if is_not_header_row
example = @scenario_outline.examples.find { |example| example.column_values == cuke_table_row.values }
test_name = scenario_outline_test_name(@scenario_outline.name, example.column_values)
@logger.test_started(test_name)
end
end
end | ruby | def before_table_row(cuke_table_row)
if cuke_table_row.is_a?(Cucumber::Formatter::LegacyApi::ExampleTableRow)
is_not_header_row = (@scenario_outline.example_column_names != cuke_table_row.values)
if is_not_header_row
example = @scenario_outline.examples.find { |example| example.column_values == cuke_table_row.values }
test_name = scenario_outline_test_name(@scenario_outline.name, example.column_values)
@logger.test_started(test_name)
end
end
end | [
"def",
"before_table_row",
"(",
"cuke_table_row",
")",
"if",
"cuke_table_row",
".",
"is_a?",
"(",
"Cucumber",
"::",
"Formatter",
"::",
"LegacyApi",
"::",
"ExampleTableRow",
")",
"is_not_header_row",
"=",
"(",
"@scenario_outline",
".",
"example_column_names",
"!=",
"cuke_table_row",
".",
"values",
")",
"if",
"is_not_header_row",
"example",
"=",
"@scenario_outline",
".",
"examples",
".",
"find",
"{",
"|",
"example",
"|",
"example",
".",
"column_values",
"==",
"cuke_table_row",
".",
"values",
"}",
"test_name",
"=",
"scenario_outline_test_name",
"(",
"@scenario_outline",
".",
"name",
",",
"example",
".",
"column_values",
")",
"@logger",
".",
"test_started",
"(",
"test_name",
")",
"end",
"end",
"end"
]
| this method is called before a scenario outline row OR step data table row | [
"this",
"method",
"is",
"called",
"before",
"a",
"scenario",
"outline",
"row",
"OR",
"step",
"data",
"table",
"row"
]
| d4f2e35b508479b6469f3a7e1d1779948abb4ccb | https://github.com/kevinrood/teamcity_formatter/blob/d4f2e35b508479b6469f3a7e1d1779948abb4ccb/lib/team_city_formatter/formatter.rb#L57-L66 | train |
kevinrood/teamcity_formatter | lib/team_city_formatter/formatter.rb | TeamCityFormatter.Formatter.after_table_row | def after_table_row(cuke_table_row)
if cuke_table_row.is_a?(Cucumber::Formatter::LegacyApi::Ast::ExampleTableRow)
is_not_header_row = (@scenario_outline.example_column_names != cuke_table_row.cells)
if is_not_header_row
# treat scenario-level exception as example exception
# the exception could have been raised in a background section
exception = (@exception || cuke_table_row.exception)
example = @scenario_outline.examples.find { |example| example.column_values == cuke_table_row.cells }
test_name = scenario_outline_test_name(@scenario_outline.name, example.column_values)
if exception
if exception.is_a? ::Cucumber::Pending
@logger.test_ignored(test_name, 'Pending test')
else
@logger.test_failed(test_name, exception)
end
end
@logger.test_finished(test_name)
@exception = nil
end
end
end | ruby | def after_table_row(cuke_table_row)
if cuke_table_row.is_a?(Cucumber::Formatter::LegacyApi::Ast::ExampleTableRow)
is_not_header_row = (@scenario_outline.example_column_names != cuke_table_row.cells)
if is_not_header_row
# treat scenario-level exception as example exception
# the exception could have been raised in a background section
exception = (@exception || cuke_table_row.exception)
example = @scenario_outline.examples.find { |example| example.column_values == cuke_table_row.cells }
test_name = scenario_outline_test_name(@scenario_outline.name, example.column_values)
if exception
if exception.is_a? ::Cucumber::Pending
@logger.test_ignored(test_name, 'Pending test')
else
@logger.test_failed(test_name, exception)
end
end
@logger.test_finished(test_name)
@exception = nil
end
end
end | [
"def",
"after_table_row",
"(",
"cuke_table_row",
")",
"if",
"cuke_table_row",
".",
"is_a?",
"(",
"Cucumber",
"::",
"Formatter",
"::",
"LegacyApi",
"::",
"Ast",
"::",
"ExampleTableRow",
")",
"is_not_header_row",
"=",
"(",
"@scenario_outline",
".",
"example_column_names",
"!=",
"cuke_table_row",
".",
"cells",
")",
"if",
"is_not_header_row",
"exception",
"=",
"(",
"@exception",
"||",
"cuke_table_row",
".",
"exception",
")",
"example",
"=",
"@scenario_outline",
".",
"examples",
".",
"find",
"{",
"|",
"example",
"|",
"example",
".",
"column_values",
"==",
"cuke_table_row",
".",
"cells",
"}",
"test_name",
"=",
"scenario_outline_test_name",
"(",
"@scenario_outline",
".",
"name",
",",
"example",
".",
"column_values",
")",
"if",
"exception",
"if",
"exception",
".",
"is_a?",
"::",
"Cucumber",
"::",
"Pending",
"@logger",
".",
"test_ignored",
"(",
"test_name",
",",
"'Pending test'",
")",
"else",
"@logger",
".",
"test_failed",
"(",
"test_name",
",",
"exception",
")",
"end",
"end",
"@logger",
".",
"test_finished",
"(",
"test_name",
")",
"@exception",
"=",
"nil",
"end",
"end",
"end"
]
| this method is called after a scenario outline row OR step data table row | [
"this",
"method",
"is",
"called",
"after",
"a",
"scenario",
"outline",
"row",
"OR",
"step",
"data",
"table",
"row"
]
| d4f2e35b508479b6469f3a7e1d1779948abb4ccb | https://github.com/kevinrood/teamcity_formatter/blob/d4f2e35b508479b6469f3a7e1d1779948abb4ccb/lib/team_city_formatter/formatter.rb#L69-L90 | train |
weppos/tabs_on_rails | lib/tabs_on_rails/tabs.rb | TabsOnRails.Tabs.render | def render(&block)
raise LocalJumpError, "no block given" unless block_given?
options = @options.dup
open_tabs_options = options.delete(:open_tabs) || {}
close_tabs_options = options.delete(:close_tabs) || {}
"".tap do |html|
html << open_tabs(open_tabs_options).to_s
html << @context.capture(self, &block)
html << close_tabs(close_tabs_options).to_s
end.html_safe
end | ruby | def render(&block)
raise LocalJumpError, "no block given" unless block_given?
options = @options.dup
open_tabs_options = options.delete(:open_tabs) || {}
close_tabs_options = options.delete(:close_tabs) || {}
"".tap do |html|
html << open_tabs(open_tabs_options).to_s
html << @context.capture(self, &block)
html << close_tabs(close_tabs_options).to_s
end.html_safe
end | [
"def",
"render",
"(",
"&",
"block",
")",
"raise",
"LocalJumpError",
",",
"\"no block given\"",
"unless",
"block_given?",
"options",
"=",
"@options",
".",
"dup",
"open_tabs_options",
"=",
"options",
".",
"delete",
"(",
":open_tabs",
")",
"||",
"{",
"}",
"close_tabs_options",
"=",
"options",
".",
"delete",
"(",
":close_tabs",
")",
"||",
"{",
"}",
"\"\"",
".",
"tap",
"do",
"|",
"html",
"|",
"html",
"<<",
"open_tabs",
"(",
"open_tabs_options",
")",
".",
"to_s",
"html",
"<<",
"@context",
".",
"capture",
"(",
"self",
",",
"&",
"block",
")",
"html",
"<<",
"close_tabs",
"(",
"close_tabs_options",
")",
".",
"to_s",
"end",
".",
"html_safe",
"end"
]
| Renders the tab stack using the current builder.
Returns the String HTML content. | [
"Renders",
"the",
"tab",
"stack",
"using",
"the",
"current",
"builder",
"."
]
| ccd1c1027dc73ba261a558147e53be43de9dc1e6 | https://github.com/weppos/tabs_on_rails/blob/ccd1c1027dc73ba261a558147e53be43de9dc1e6/lib/tabs_on_rails/tabs.rb#L50-L62 | train |
0sc/activestorage-cloudinary-service | lib/active_storage/service/cloudinary_service.rb | ActiveStorage.Service::CloudinaryService.download | def download(key, &block)
source = cloudinary_url_for_key(key)
if block_given?
instrument :streaming_download, key: key do
stream_download(source, &block)
end
else
instrument :download, key: key do
Cloudinary::Downloader.download(source)
end
end
end | ruby | def download(key, &block)
source = cloudinary_url_for_key(key)
if block_given?
instrument :streaming_download, key: key do
stream_download(source, &block)
end
else
instrument :download, key: key do
Cloudinary::Downloader.download(source)
end
end
end | [
"def",
"download",
"(",
"key",
",",
"&",
"block",
")",
"source",
"=",
"cloudinary_url_for_key",
"(",
"key",
")",
"if",
"block_given?",
"instrument",
":streaming_download",
",",
"key",
":",
"key",
"do",
"stream_download",
"(",
"source",
",",
"&",
"block",
")",
"end",
"else",
"instrument",
":download",
",",
"key",
":",
"key",
"do",
"Cloudinary",
"::",
"Downloader",
".",
"download",
"(",
"source",
")",
"end",
"end",
"end"
]
| Return the content of the file at the +key+. | [
"Return",
"the",
"content",
"of",
"the",
"file",
"at",
"the",
"+",
"key",
"+",
"."
]
| df27e24bac8f7642627ccd44c0ad3c4231f32973 | https://github.com/0sc/activestorage-cloudinary-service/blob/df27e24bac8f7642627ccd44c0ad3c4231f32973/lib/active_storage/service/cloudinary_service.rb#L29-L41 | train |
0sc/activestorage-cloudinary-service | lib/active_storage/service/cloudinary_service.rb | ActiveStorage.Service::CloudinaryService.download_chunk | def download_chunk(key, range)
instrument :download_chunk, key: key, range: range do
source = cloudinary_url_for_key(key)
download_range(source, range)
end
end | ruby | def download_chunk(key, range)
instrument :download_chunk, key: key, range: range do
source = cloudinary_url_for_key(key)
download_range(source, range)
end
end | [
"def",
"download_chunk",
"(",
"key",
",",
"range",
")",
"instrument",
":download_chunk",
",",
"key",
":",
"key",
",",
"range",
":",
"range",
"do",
"source",
"=",
"cloudinary_url_for_key",
"(",
"key",
")",
"download_range",
"(",
"source",
",",
"range",
")",
"end",
"end"
]
| Return the partial content in the byte +range+ of the file at the +key+. | [
"Return",
"the",
"partial",
"content",
"in",
"the",
"byte",
"+",
"range",
"+",
"of",
"the",
"file",
"at",
"the",
"+",
"key",
"+",
"."
]
| df27e24bac8f7642627ccd44c0ad3c4231f32973 | https://github.com/0sc/activestorage-cloudinary-service/blob/df27e24bac8f7642627ccd44c0ad3c4231f32973/lib/active_storage/service/cloudinary_service.rb#L44-L49 | train |
0sc/activestorage-cloudinary-service | lib/active_storage/service/cloudinary_service.rb | ActiveStorage.Service::CloudinaryService.url_for_direct_upload | def url_for_direct_upload(key, expires_in:, content_type:, content_length:, checksum:)
instrument :url_for_direct_upload, key: key do
options = {
expires_in: expires_in,
content_type: content_type,
content_length: content_length,
checksum: checksum,
resource_type: 'auto'
}
# FIXME: Cloudinary Ruby SDK does't expose an api for signed upload url
# The expected url is similar to the private_download_url
# with download replaced with upload
signed_download_url_for_public_id(key, options)
.sub(/download/, 'upload')
end
end | ruby | def url_for_direct_upload(key, expires_in:, content_type:, content_length:, checksum:)
instrument :url_for_direct_upload, key: key do
options = {
expires_in: expires_in,
content_type: content_type,
content_length: content_length,
checksum: checksum,
resource_type: 'auto'
}
# FIXME: Cloudinary Ruby SDK does't expose an api for signed upload url
# The expected url is similar to the private_download_url
# with download replaced with upload
signed_download_url_for_public_id(key, options)
.sub(/download/, 'upload')
end
end | [
"def",
"url_for_direct_upload",
"(",
"key",
",",
"expires_in",
":",
",",
"content_type",
":",
",",
"content_length",
":",
",",
"checksum",
":",
")",
"instrument",
":url_for_direct_upload",
",",
"key",
":",
"key",
"do",
"options",
"=",
"{",
"expires_in",
":",
"expires_in",
",",
"content_type",
":",
"content_type",
",",
"content_length",
":",
"content_length",
",",
"checksum",
":",
"checksum",
",",
"resource_type",
":",
"'auto'",
"}",
"signed_download_url_for_public_id",
"(",
"key",
",",
"options",
")",
".",
"sub",
"(",
"/",
"/",
",",
"'upload'",
")",
"end",
"end"
]
| Returns a signed, temporary URL that a direct upload file can be PUT to on the +key+.
The URL will be valid for the amount of seconds specified in +expires_in+.
You must also provide the +content_type+, +content_length+, and +checksum+ of the file
that will be uploaded. All these attributes will be validated by the service upon upload. | [
"Returns",
"a",
"signed",
"temporary",
"URL",
"that",
"a",
"direct",
"upload",
"file",
"can",
"be",
"PUT",
"to",
"on",
"the",
"+",
"key",
"+",
".",
"The",
"URL",
"will",
"be",
"valid",
"for",
"the",
"amount",
"of",
"seconds",
"specified",
"in",
"+",
"expires_in",
"+",
".",
"You",
"must",
"also",
"provide",
"the",
"+",
"content_type",
"+",
"+",
"content_length",
"+",
"and",
"+",
"checksum",
"+",
"of",
"the",
"file",
"that",
"will",
"be",
"uploaded",
".",
"All",
"these",
"attributes",
"will",
"be",
"validated",
"by",
"the",
"service",
"upon",
"upload",
"."
]
| df27e24bac8f7642627ccd44c0ad3c4231f32973 | https://github.com/0sc/activestorage-cloudinary-service/blob/df27e24bac8f7642627ccd44c0ad3c4231f32973/lib/active_storage/service/cloudinary_service.rb#L91-L107 | train |
ali-sheiba/opta_sd | lib/opta_sd/core.rb | OptaSD.Core.parse_json | def parse_json(response)
data = JSON.parse(response)
fail OptaSD::Error.new(data), ErrorMessage.get_message(data['errorCode'].to_i) if data['errorCode']
data
end | ruby | def parse_json(response)
data = JSON.parse(response)
fail OptaSD::Error.new(data), ErrorMessage.get_message(data['errorCode'].to_i) if data['errorCode']
data
end | [
"def",
"parse_json",
"(",
"response",
")",
"data",
"=",
"JSON",
".",
"parse",
"(",
"response",
")",
"fail",
"OptaSD",
"::",
"Error",
".",
"new",
"(",
"data",
")",
",",
"ErrorMessage",
".",
"get_message",
"(",
"data",
"[",
"'errorCode'",
"]",
".",
"to_i",
")",
"if",
"data",
"[",
"'errorCode'",
"]",
"data",
"end"
]
| Parse JSON Response | [
"Parse",
"JSON",
"Response"
]
| eddba8e9c13b35717b37facd2906cfe1bb5ef771 | https://github.com/ali-sheiba/opta_sd/blob/eddba8e9c13b35717b37facd2906cfe1bb5ef771/lib/opta_sd/core.rb#L30-L34 | train |
ali-sheiba/opta_sd | lib/opta_sd/core.rb | OptaSD.Core.parse_xml | def parse_xml(response)
data = Nokogiri::XML(response) do |config| config.strict.noblanks end
fail OptaSD::Error.new(xml_error_to_hast(data)), ErrorMessage.get_message(data.children.first.content.to_i) if data.css('errorCode').first.present?
data
end | ruby | def parse_xml(response)
data = Nokogiri::XML(response) do |config| config.strict.noblanks end
fail OptaSD::Error.new(xml_error_to_hast(data)), ErrorMessage.get_message(data.children.first.content.to_i) if data.css('errorCode').first.present?
data
end | [
"def",
"parse_xml",
"(",
"response",
")",
"data",
"=",
"Nokogiri",
"::",
"XML",
"(",
"response",
")",
"do",
"|",
"config",
"|",
"config",
".",
"strict",
".",
"noblanks",
"end",
"fail",
"OptaSD",
"::",
"Error",
".",
"new",
"(",
"xml_error_to_hast",
"(",
"data",
")",
")",
",",
"ErrorMessage",
".",
"get_message",
"(",
"data",
".",
"children",
".",
"first",
".",
"content",
".",
"to_i",
")",
"if",
"data",
".",
"css",
"(",
"'errorCode'",
")",
".",
"first",
".",
"present?",
"data",
"end"
]
| Parse XML Response | [
"Parse",
"XML",
"Response"
]
| eddba8e9c13b35717b37facd2906cfe1bb5ef771 | https://github.com/ali-sheiba/opta_sd/blob/eddba8e9c13b35717b37facd2906cfe1bb5ef771/lib/opta_sd/core.rb#L37-L41 | train |
reiseburo/hermann | lib/hermann/producer.rb | Hermann.Producer.push | def push(value, opts={})
topic = opts[:topic] || @topic
result = nil
if value.kind_of? Array
return value.map { |e| self.push(e, opts) }
end
if Hermann.jruby?
result = @internal.push_single(value, topic, opts[:partition_key], nil)
unless result.nil?
@children << result
end
# Reaping children on the push just to make sure that it does get
# called correctly and we don't leak memory
reap_children
else
# Ticking reactor to make sure that we don't inadvertantly let the
# librdkafka callback queue overflow
tick_reactor
result = create_result
@internal.push_single(value, topic, opts[:partition_key].to_s, result)
end
return result
end | ruby | def push(value, opts={})
topic = opts[:topic] || @topic
result = nil
if value.kind_of? Array
return value.map { |e| self.push(e, opts) }
end
if Hermann.jruby?
result = @internal.push_single(value, topic, opts[:partition_key], nil)
unless result.nil?
@children << result
end
# Reaping children on the push just to make sure that it does get
# called correctly and we don't leak memory
reap_children
else
# Ticking reactor to make sure that we don't inadvertantly let the
# librdkafka callback queue overflow
tick_reactor
result = create_result
@internal.push_single(value, topic, opts[:partition_key].to_s, result)
end
return result
end | [
"def",
"push",
"(",
"value",
",",
"opts",
"=",
"{",
"}",
")",
"topic",
"=",
"opts",
"[",
":topic",
"]",
"||",
"@topic",
"result",
"=",
"nil",
"if",
"value",
".",
"kind_of?",
"Array",
"return",
"value",
".",
"map",
"{",
"|",
"e",
"|",
"self",
".",
"push",
"(",
"e",
",",
"opts",
")",
"}",
"end",
"if",
"Hermann",
".",
"jruby?",
"result",
"=",
"@internal",
".",
"push_single",
"(",
"value",
",",
"topic",
",",
"opts",
"[",
":partition_key",
"]",
",",
"nil",
")",
"unless",
"result",
".",
"nil?",
"@children",
"<<",
"result",
"end",
"reap_children",
"else",
"tick_reactor",
"result",
"=",
"create_result",
"@internal",
".",
"push_single",
"(",
"value",
",",
"topic",
",",
"opts",
"[",
":partition_key",
"]",
".",
"to_s",
",",
"result",
")",
"end",
"return",
"result",
"end"
]
| Push a value onto the Kafka topic passed to this +Producer+
@param [Object] value A single object to push
@param [Hash] opts to pass to push method
@option opts [String] :topic The topic to push messages to
:partition_key The string to partition by
@return [Hermann::Result] A future-like object which will store the
result from the broker | [
"Push",
"a",
"value",
"onto",
"the",
"Kafka",
"topic",
"passed",
"to",
"this",
"+",
"Producer",
"+"
]
| d822ae541aabc24c2fd211f7ef5efba37179ed98 | https://github.com/reiseburo/hermann/blob/d822ae541aabc24c2fd211f7ef5efba37179ed98/lib/hermann/producer.rb#L57-L82 | train |
reiseburo/hermann | lib/hermann/producer.rb | Hermann.Producer.tick_reactor | def tick_reactor(timeout=0)
begin
execute_tick(rounded_timeout(timeout))
rescue StandardError => ex
@children.each do |child|
# Skip over any children that should already be reaped for other
# reasons
next if (Hermann.jruby? ? child.fulfilled? : child.completed?)
# Propagate errors to the remaining children
child.internal_set_error(ex)
end
end
# Reaping the children at this point will also reap any children marked
# as errored by an exception out of #execute_tick
return reap_children
end | ruby | def tick_reactor(timeout=0)
begin
execute_tick(rounded_timeout(timeout))
rescue StandardError => ex
@children.each do |child|
# Skip over any children that should already be reaped for other
# reasons
next if (Hermann.jruby? ? child.fulfilled? : child.completed?)
# Propagate errors to the remaining children
child.internal_set_error(ex)
end
end
# Reaping the children at this point will also reap any children marked
# as errored by an exception out of #execute_tick
return reap_children
end | [
"def",
"tick_reactor",
"(",
"timeout",
"=",
"0",
")",
"begin",
"execute_tick",
"(",
"rounded_timeout",
"(",
"timeout",
")",
")",
"rescue",
"StandardError",
"=>",
"ex",
"@children",
".",
"each",
"do",
"|",
"child",
"|",
"next",
"if",
"(",
"Hermann",
".",
"jruby?",
"?",
"child",
".",
"fulfilled?",
":",
"child",
".",
"completed?",
")",
"child",
".",
"internal_set_error",
"(",
"ex",
")",
"end",
"end",
"return",
"reap_children",
"end"
]
| Tick the underlying librdkafka reacter and clean up any unreaped but
reapable children results
@param [FixNum] timeout Seconds to block on the internal reactor
@return [FixNum] Number of +Hermann::Result+ children reaped | [
"Tick",
"the",
"underlying",
"librdkafka",
"reacter",
"and",
"clean",
"up",
"any",
"unreaped",
"but",
"reapable",
"children",
"results"
]
| d822ae541aabc24c2fd211f7ef5efba37179ed98 | https://github.com/reiseburo/hermann/blob/d822ae541aabc24c2fd211f7ef5efba37179ed98/lib/hermann/producer.rb#L98-L115 | train |
reiseburo/hermann | lib/hermann/producer.rb | Hermann.Producer.execute_tick | def execute_tick(timeout)
if timeout == 0
@internal.tick(0)
else
(timeout * 2).times do
# We're going to Thread#sleep in Ruby to avoid a
# pthread_cond_timedwait(3) inside of librdkafka
events = @internal.tick(0)
# If we find events, break out early
break if events > 0
sleep 0.5
end
end
end | ruby | def execute_tick(timeout)
if timeout == 0
@internal.tick(0)
else
(timeout * 2).times do
# We're going to Thread#sleep in Ruby to avoid a
# pthread_cond_timedwait(3) inside of librdkafka
events = @internal.tick(0)
# If we find events, break out early
break if events > 0
sleep 0.5
end
end
end | [
"def",
"execute_tick",
"(",
"timeout",
")",
"if",
"timeout",
"==",
"0",
"@internal",
".",
"tick",
"(",
"0",
")",
"else",
"(",
"timeout",
"*",
"2",
")",
".",
"times",
"do",
"events",
"=",
"@internal",
".",
"tick",
"(",
"0",
")",
"break",
"if",
"events",
">",
"0",
"sleep",
"0.5",
"end",
"end",
"end"
]
| Perform the actual reactor tick
@raises [StandardError] in case of underlying failures in librdkafka | [
"Perform",
"the",
"actual",
"reactor",
"tick"
]
| d822ae541aabc24c2fd211f7ef5efba37179ed98 | https://github.com/reiseburo/hermann/blob/d822ae541aabc24c2fd211f7ef5efba37179ed98/lib/hermann/producer.rb#L140-L153 | train |
chaadow/activestorage-openstack | lib/active_storage/service/open_stack_service.rb | ActiveStorage.Service::OpenStackService.change_content_type | def change_content_type(key, content_type)
client.post_object(container,
key,
'Content-Type' => content_type)
true
rescue Fog::OpenStack::Storage::NotFound
false
end | ruby | def change_content_type(key, content_type)
client.post_object(container,
key,
'Content-Type' => content_type)
true
rescue Fog::OpenStack::Storage::NotFound
false
end | [
"def",
"change_content_type",
"(",
"key",
",",
"content_type",
")",
"client",
".",
"post_object",
"(",
"container",
",",
"key",
",",
"'Content-Type'",
"=>",
"content_type",
")",
"true",
"rescue",
"Fog",
"::",
"OpenStack",
"::",
"Storage",
"::",
"NotFound",
"false",
"end"
]
| Non-standard method to change the content type of an existing object | [
"Non",
"-",
"standard",
"method",
"to",
"change",
"the",
"content",
"type",
"of",
"an",
"existing",
"object"
]
| 91f002351b35d19e1ce3a372221b6da324390a35 | https://github.com/chaadow/activestorage-openstack/blob/91f002351b35d19e1ce3a372221b6da324390a35/lib/active_storage/service/open_stack_service.rb#L120-L127 | train |
reidmorrison/jruby-jms | lib/jms/oracle_a_q_connection_factory.rb | JMS.OracleAQConnectionFactory.create_connection | def create_connection(*args)
# Since username and password are not assigned (see lib/jms/connection.rb:200)
# and connection_factory.create_connection expects 2 arguments when username is not null ...
if args.length == 2
@username = args[0]
@password = args[1]
end
# Full Qualified name causes a Java exception
#cf = oracle.jms.AQjmsFactory.getConnectionFactory(@url, java.util.Properties.new)
cf = AQjmsFactory.getConnectionFactory(@url, java.util.Properties.new)
if username
cf.createConnection(@username, @password)
else
cf.createConnection()
end
end | ruby | def create_connection(*args)
# Since username and password are not assigned (see lib/jms/connection.rb:200)
# and connection_factory.create_connection expects 2 arguments when username is not null ...
if args.length == 2
@username = args[0]
@password = args[1]
end
# Full Qualified name causes a Java exception
#cf = oracle.jms.AQjmsFactory.getConnectionFactory(@url, java.util.Properties.new)
cf = AQjmsFactory.getConnectionFactory(@url, java.util.Properties.new)
if username
cf.createConnection(@username, @password)
else
cf.createConnection()
end
end | [
"def",
"create_connection",
"(",
"*",
"args",
")",
"if",
"args",
".",
"length",
"==",
"2",
"@username",
"=",
"args",
"[",
"0",
"]",
"@password",
"=",
"args",
"[",
"1",
"]",
"end",
"cf",
"=",
"AQjmsFactory",
".",
"getConnectionFactory",
"(",
"@url",
",",
"java",
".",
"util",
".",
"Properties",
".",
"new",
")",
"if",
"username",
"cf",
".",
"createConnection",
"(",
"@username",
",",
"@password",
")",
"else",
"cf",
".",
"createConnection",
"(",
")",
"end",
"end"
]
| Creates a connection per standard JMS 1.1 techniques from the Oracle AQ JMS Interface | [
"Creates",
"a",
"connection",
"per",
"standard",
"JMS",
"1",
".",
"1",
"techniques",
"from",
"the",
"Oracle",
"AQ",
"JMS",
"Interface"
]
| cdc2ce1daf643474110146a7505dad5e427030d3 | https://github.com/reidmorrison/jruby-jms/blob/cdc2ce1daf643474110146a7505dad5e427030d3/lib/jms/oracle_a_q_connection_factory.rb#L11-L28 | train |
reidmorrison/jruby-jms | lib/jms/session_pool.rb | JMS.SessionPool.session | def session(&block)
s = nil
begin
s = @pool.checkout
block.call(s)
rescue javax.jms.JMSException => e
s.close rescue nil
@pool.remove(s)
s = nil # Do not check back in since we have removed it
raise e
ensure
@pool.checkin(s) if s
end
end | ruby | def session(&block)
s = nil
begin
s = @pool.checkout
block.call(s)
rescue javax.jms.JMSException => e
s.close rescue nil
@pool.remove(s)
s = nil # Do not check back in since we have removed it
raise e
ensure
@pool.checkin(s) if s
end
end | [
"def",
"session",
"(",
"&",
"block",
")",
"s",
"=",
"nil",
"begin",
"s",
"=",
"@pool",
".",
"checkout",
"block",
".",
"call",
"(",
"s",
")",
"rescue",
"javax",
".",
"jms",
".",
"JMSException",
"=>",
"e",
"s",
".",
"close",
"rescue",
"nil",
"@pool",
".",
"remove",
"(",
"s",
")",
"s",
"=",
"nil",
"raise",
"e",
"ensure",
"@pool",
".",
"checkin",
"(",
"s",
")",
"if",
"s",
"end",
"end"
]
| Obtain a session from the pool and pass it to the supplied block
The session is automatically returned to the pool once the block completes
In the event a JMS Exception is thrown the session will be closed and removed
from the pool to prevent re-using sessions that are no longer valid | [
"Obtain",
"a",
"session",
"from",
"the",
"pool",
"and",
"pass",
"it",
"to",
"the",
"supplied",
"block",
"The",
"session",
"is",
"automatically",
"returned",
"to",
"the",
"pool",
"once",
"the",
"block",
"completes"
]
| cdc2ce1daf643474110146a7505dad5e427030d3 | https://github.com/reidmorrison/jruby-jms/blob/cdc2ce1daf643474110146a7505dad5e427030d3/lib/jms/session_pool.rb#L66-L79 | train |
reidmorrison/jruby-jms | lib/jms/session_pool.rb | JMS.SessionPool.consumer | def consumer(params, &block)
session do |s|
begin
consumer = s.consumer(params)
block.call(s, consumer)
ensure
consumer.close if consumer
end
end
end | ruby | def consumer(params, &block)
session do |s|
begin
consumer = s.consumer(params)
block.call(s, consumer)
ensure
consumer.close if consumer
end
end
end | [
"def",
"consumer",
"(",
"params",
",",
"&",
"block",
")",
"session",
"do",
"|",
"s",
"|",
"begin",
"consumer",
"=",
"s",
".",
"consumer",
"(",
"params",
")",
"block",
".",
"call",
"(",
"s",
",",
"consumer",
")",
"ensure",
"consumer",
".",
"close",
"if",
"consumer",
"end",
"end",
"end"
]
| Obtain a session from the pool and create a MessageConsumer.
Pass both into the supplied block.
Once the block is complete the consumer is closed and the session is
returned to the pool.
Parameters:
queue_name: [String] Name of the Queue to return
[Symbol] Create temporary queue
Mandatory unless :topic_name is supplied
Or,
topic_name: [String] Name of the Topic to write to or subscribe to
[Symbol] Create temporary topic
Mandatory unless :queue_name is supplied
Or,
destination: [javaxJms::Destination] Destination to use
selector: Filter which messages should be returned from the queue
Default: All messages
no_local: Determine whether messages published by its own connection
should be delivered to it
Default: false
Example
session_pool.consumer(queue_name: 'MyQueue') do |session, consumer|
message = consumer.receive(timeout)
puts message.data if message
end | [
"Obtain",
"a",
"session",
"from",
"the",
"pool",
"and",
"create",
"a",
"MessageConsumer",
".",
"Pass",
"both",
"into",
"the",
"supplied",
"block",
".",
"Once",
"the",
"block",
"is",
"complete",
"the",
"consumer",
"is",
"closed",
"and",
"the",
"session",
"is",
"returned",
"to",
"the",
"pool",
"."
]
| cdc2ce1daf643474110146a7505dad5e427030d3 | https://github.com/reidmorrison/jruby-jms/blob/cdc2ce1daf643474110146a7505dad5e427030d3/lib/jms/session_pool.rb#L108-L117 | train |
reidmorrison/jruby-jms | lib/jms/session_pool.rb | JMS.SessionPool.producer | def producer(params, &block)
session do |s|
begin
producer = s.producer(params)
block.call(s, producer)
ensure
producer.close if producer
end
end
end | ruby | def producer(params, &block)
session do |s|
begin
producer = s.producer(params)
block.call(s, producer)
ensure
producer.close if producer
end
end
end | [
"def",
"producer",
"(",
"params",
",",
"&",
"block",
")",
"session",
"do",
"|",
"s",
"|",
"begin",
"producer",
"=",
"s",
".",
"producer",
"(",
"params",
")",
"block",
".",
"call",
"(",
"s",
",",
"producer",
")",
"ensure",
"producer",
".",
"close",
"if",
"producer",
"end",
"end",
"end"
]
| Obtain a session from the pool and create a MessageProducer.
Pass both into the supplied block.
Once the block is complete the producer is closed and the session is
returned to the pool.
Parameters:
queue_name: [String] Name of the Queue to return
[Symbol] Create temporary queue
Mandatory unless :topic_name is supplied
Or,
topic_name: [String] Name of the Topic to write to or subscribe to
[Symbol] Create temporary topic
Mandatory unless :queue_name is supplied
Or,
destination: [javaxJms::Destination] Destination to use
Example
session_pool.producer(queue_name: 'ExampleQueue') do |session, producer|
producer.send(session.message("Hello World"))
end | [
"Obtain",
"a",
"session",
"from",
"the",
"pool",
"and",
"create",
"a",
"MessageProducer",
".",
"Pass",
"both",
"into",
"the",
"supplied",
"block",
".",
"Once",
"the",
"block",
"is",
"complete",
"the",
"producer",
"is",
"closed",
"and",
"the",
"session",
"is",
"returned",
"to",
"the",
"pool",
"."
]
| cdc2ce1daf643474110146a7505dad5e427030d3 | https://github.com/reidmorrison/jruby-jms/blob/cdc2ce1daf643474110146a7505dad5e427030d3/lib/jms/session_pool.rb#L139-L148 | train |
reidmorrison/jruby-jms | lib/jms/connection.rb | JMS.Connection.fetch_dependencies | def fetch_dependencies(jar_list)
jar_list.each do |jar|
logger.debug "Loading Jar File:#{jar}"
begin
require jar
rescue Exception => exc
logger.error "Failed to Load Jar File:#{jar}", exc
end
end if jar_list
require 'jms/mq_workaround'
require 'jms/imports'
require 'jms/message_listener_impl'
require 'jms/message'
require 'jms/text_message'
require 'jms/map_message'
require 'jms/bytes_message'
require 'jms/object_message'
require 'jms/session'
require 'jms/message_consumer'
require 'jms/message_producer'
require 'jms/queue_browser'
end | ruby | def fetch_dependencies(jar_list)
jar_list.each do |jar|
logger.debug "Loading Jar File:#{jar}"
begin
require jar
rescue Exception => exc
logger.error "Failed to Load Jar File:#{jar}", exc
end
end if jar_list
require 'jms/mq_workaround'
require 'jms/imports'
require 'jms/message_listener_impl'
require 'jms/message'
require 'jms/text_message'
require 'jms/map_message'
require 'jms/bytes_message'
require 'jms/object_message'
require 'jms/session'
require 'jms/message_consumer'
require 'jms/message_producer'
require 'jms/queue_browser'
end | [
"def",
"fetch_dependencies",
"(",
"jar_list",
")",
"jar_list",
".",
"each",
"do",
"|",
"jar",
"|",
"logger",
".",
"debug",
"\"Loading Jar File:#{jar}\"",
"begin",
"require",
"jar",
"rescue",
"Exception",
"=>",
"exc",
"logger",
".",
"error",
"\"Failed to Load Jar File:#{jar}\"",
",",
"exc",
"end",
"end",
"if",
"jar_list",
"require",
"'jms/mq_workaround'",
"require",
"'jms/imports'",
"require",
"'jms/message_listener_impl'",
"require",
"'jms/message'",
"require",
"'jms/text_message'",
"require",
"'jms/map_message'",
"require",
"'jms/bytes_message'",
"require",
"'jms/object_message'",
"require",
"'jms/session'",
"require",
"'jms/message_consumer'",
"require",
"'jms/message_producer'",
"require",
"'jms/queue_browser'",
"end"
]
| Load the required jar files for this JMS Provider and
load JRuby extensions for those classes
Rather than copying the JMS jar files into the JRuby lib, load them
on demand. JRuby JMS extensions are only loaded once the jar files have been
loaded.
Can be called multiple times if required, although it would not be performant
to do so regularly.
Parameter: jar_list is an Array of the path and filenames to jar files
to load for this JMS Provider
Returns nil | [
"Load",
"the",
"required",
"jar",
"files",
"for",
"this",
"JMS",
"Provider",
"and",
"load",
"JRuby",
"extensions",
"for",
"those",
"classes"
]
| cdc2ce1daf643474110146a7505dad5e427030d3 | https://github.com/reidmorrison/jruby-jms/blob/cdc2ce1daf643474110146a7505dad5e427030d3/lib/jms/connection.rb#L89-L111 | train |
reidmorrison/jruby-jms | lib/jms/connection.rb | JMS.Connection.session | def session(params={}, &block)
raise(ArgumentError, 'Missing mandatory Block when calling JMS::Connection#session') unless block
session = self.create_session(params)
begin
block.call(session)
ensure
session.close
end
end | ruby | def session(params={}, &block)
raise(ArgumentError, 'Missing mandatory Block when calling JMS::Connection#session') unless block
session = self.create_session(params)
begin
block.call(session)
ensure
session.close
end
end | [
"def",
"session",
"(",
"params",
"=",
"{",
"}",
",",
"&",
"block",
")",
"raise",
"(",
"ArgumentError",
",",
"'Missing mandatory Block when calling JMS::Connection#session'",
")",
"unless",
"block",
"session",
"=",
"self",
".",
"create_session",
"(",
"params",
")",
"begin",
"block",
".",
"call",
"(",
"session",
")",
"ensure",
"session",
".",
"close",
"end",
"end"
]
| Create a session over this connection.
It is recommended to create separate sessions for each thread
If a block of code is passed in, it will be called and then the session is automatically
closed on completion of the code block
Parameters:
transacted: [true|false]
Determines whether transactions are supported within this session.
I.e. Whether commit or rollback can be called
Default: false
Note: :options below are ignored if this value is set to :true
options: any of the JMS::Session constants:
Note: :options are ignored if transacted: true
JMS::Session::AUTO_ACKNOWLEDGE
With this acknowledgment mode, the session automatically acknowledges
a client's receipt of a message either when the session has successfully
returned from a call to receive or when the message listener the session has
called to process the message successfully returns.
JMS::Session::CLIENT_ACKNOWLEDGE
With this acknowledgment mode, the client acknowledges a consumed
message by calling the message's acknowledge method.
JMS::Session::DUPS_OK_ACKNOWLEDGE
This acknowledgment mode instructs the session to lazily acknowledge
the delivery of messages.
JMS::Session::SESSION_TRANSACTED
This value is returned from the method getAcknowledgeMode if the
session is transacted.
Default: JMS::Session::AUTO_ACKNOWLEDGE | [
"Create",
"a",
"session",
"over",
"this",
"connection",
".",
"It",
"is",
"recommended",
"to",
"create",
"separate",
"sessions",
"for",
"each",
"thread",
"If",
"a",
"block",
"of",
"code",
"is",
"passed",
"in",
"it",
"will",
"be",
"called",
"and",
"then",
"the",
"session",
"is",
"automatically",
"closed",
"on",
"completion",
"of",
"the",
"code",
"block"
]
| cdc2ce1daf643474110146a7505dad5e427030d3 | https://github.com/reidmorrison/jruby-jms/blob/cdc2ce1daf643474110146a7505dad5e427030d3/lib/jms/connection.rb#L254-L262 | train |
reidmorrison/jruby-jms | lib/jms/connection.rb | JMS.Connection.create_session | def create_session(params={})
transacted = params[:transacted] || false
options = params[:options] || JMS::Session::AUTO_ACKNOWLEDGE
@jms_connection.create_session(transacted, options)
end | ruby | def create_session(params={})
transacted = params[:transacted] || false
options = params[:options] || JMS::Session::AUTO_ACKNOWLEDGE
@jms_connection.create_session(transacted, options)
end | [
"def",
"create_session",
"(",
"params",
"=",
"{",
"}",
")",
"transacted",
"=",
"params",
"[",
":transacted",
"]",
"||",
"false",
"options",
"=",
"params",
"[",
":options",
"]",
"||",
"JMS",
"::",
"Session",
"::",
"AUTO_ACKNOWLEDGE",
"@jms_connection",
".",
"create_session",
"(",
"transacted",
",",
"options",
")",
"end"
]
| Create a session over this connection.
It is recommended to create separate sessions for each thread
Note: Remember to call close on the returned session when it is no longer
needed. Rather use JMS::Connection#session with a block whenever
possible
Parameters:
transacted: true or false
Determines whether transactions are supported within this session.
I.e. Whether commit or rollback can be called
Default: false
Note: :options below are ignored if this value is set to :true
options: any of the JMS::Session constants:
Note: :options are ignored if transacted: true
JMS::Session::AUTO_ACKNOWLEDGE
With this acknowledgment mode, the session automatically acknowledges
a client's receipt of a message either when the session has successfully
returned from a call to receive or when the message listener the session has
called to process the message successfully returns.
JMS::Session::CLIENT_ACKNOWLEDGE
With this acknowledgment mode, the client acknowledges a consumed
message by calling the message's acknowledge method.
JMS::Session::DUPS_OK_ACKNOWLEDGE
This acknowledgment mode instructs the session to lazily acknowledge
the delivery of messages.
JMS::Session::SESSION_TRANSACTED
This value is returned from the method getAcknowledgeMode if the
session is transacted.
Default: JMS::Session::AUTO_ACKNOWLEDGE | [
"Create",
"a",
"session",
"over",
"this",
"connection",
".",
"It",
"is",
"recommended",
"to",
"create",
"separate",
"sessions",
"for",
"each",
"thread"
]
| cdc2ce1daf643474110146a7505dad5e427030d3 | https://github.com/reidmorrison/jruby-jms/blob/cdc2ce1daf643474110146a7505dad5e427030d3/lib/jms/connection.rb#L296-L300 | train |
reidmorrison/jruby-jms | lib/jms/connection.rb | JMS.Connection.on_message | def on_message(params, &block)
raise 'JMS::Connection must be connected prior to calling JMS::Connection::on_message' unless @sessions && @consumers
consumer_count = params[:session_count] || 1
consumer_count.times do
session = self.create_session(params)
consumer = session.consumer(params)
if session.transacted?
consumer.on_message(params) do |message|
begin
block.call(message) ? session.commit : session.rollback
rescue => exc
session.rollback
throw exc
end
end
else
consumer.on_message(params, &block)
end
@consumers << consumer
@sessions << session
end
end | ruby | def on_message(params, &block)
raise 'JMS::Connection must be connected prior to calling JMS::Connection::on_message' unless @sessions && @consumers
consumer_count = params[:session_count] || 1
consumer_count.times do
session = self.create_session(params)
consumer = session.consumer(params)
if session.transacted?
consumer.on_message(params) do |message|
begin
block.call(message) ? session.commit : session.rollback
rescue => exc
session.rollback
throw exc
end
end
else
consumer.on_message(params, &block)
end
@consumers << consumer
@sessions << session
end
end | [
"def",
"on_message",
"(",
"params",
",",
"&",
"block",
")",
"raise",
"'JMS::Connection must be connected prior to calling JMS::Connection::on_message'",
"unless",
"@sessions",
"&&",
"@consumers",
"consumer_count",
"=",
"params",
"[",
":session_count",
"]",
"||",
"1",
"consumer_count",
".",
"times",
"do",
"session",
"=",
"self",
".",
"create_session",
"(",
"params",
")",
"consumer",
"=",
"session",
".",
"consumer",
"(",
"params",
")",
"if",
"session",
".",
"transacted?",
"consumer",
".",
"on_message",
"(",
"params",
")",
"do",
"|",
"message",
"|",
"begin",
"block",
".",
"call",
"(",
"message",
")",
"?",
"session",
".",
"commit",
":",
"session",
".",
"rollback",
"rescue",
"=>",
"exc",
"session",
".",
"rollback",
"throw",
"exc",
"end",
"end",
"else",
"consumer",
".",
"on_message",
"(",
"params",
",",
"&",
"block",
")",
"end",
"@consumers",
"<<",
"consumer",
"@sessions",
"<<",
"session",
"end",
"end"
]
| Receive messages in a separate thread when they arrive
Allows messages to be received Asynchronously in a separate thread.
This method will return to the caller before messages are processed.
It is then the callers responsibility to keep the program active so that messages
can then be processed.
Session Parameters:
transacted: true or false
Determines whether transactions are supported within this session.
I.e. Whether commit or rollback can be called
Default: false
Note: :options below are ignored if this value is set to :true
options: any of the JMS::Session constants:
Note: :options are ignored if transacted: true
JMS::Session::AUTO_ACKNOWLEDGE
With this acknowledgment mode, the session automatically acknowledges
a client's receipt of a message either when the session has successfully
returned from a call to receive or when the message listener the session has
called to process the message successfully returns.
JMS::Session::CLIENT_ACKNOWLEDGE
With this acknowledgment mode, the client acknowledges a consumed
message by calling the message's acknowledge method.
JMS::Session::DUPS_OK_ACKNOWLEDGE
This acknowledgment mode instructs the session to lazily acknowledge
the delivery of messages.
JMS::Session::SESSION_TRANSACTED
This value is returned from the method getAcknowledgeMode if the
session is transacted.
Default: JMS::Session::AUTO_ACKNOWLEDGE
:session_count : Number of sessions to create, each with their own consumer which
in turn will call the supplied code block.
Note: The supplied block must be thread safe since it will be called
by several threads at the same time.
I.e. Don't change instance variables etc. without the
necessary semaphores etc.
Default: 1
Consumer Parameters:
queue_name: String: Name of the Queue to return
Symbol: temporary: Create temporary queue
Mandatory unless :topic_name is supplied
Or,
topic_name: String: Name of the Topic to write to or subscribe to
Symbol: temporary: Create temporary topic
Mandatory unless :queue_name is supplied
Or,
destination:Explicit javaxJms::Destination to use
selector: Filter which messages should be returned from the queue
Default: All messages
no_local: Determine whether messages published by its own connection
should be delivered to the supplied block
Default: false
:statistics Capture statistics on how many messages have been read
true : This method will capture statistics on the number of messages received
and the time it took to process them.
The timer starts when each() is called and finishes when either the last message was received,
or when Destination::statistics is called. In this case MessageConsumer::statistics
can be called several times during processing without affecting the end time.
Also, the start time and message count is not reset until MessageConsumer::each
is called again with statistics: true
Usage: For transacted sessions the block supplied must return either true or false:
true => The session is committed
false => The session is rolled back
Any Exception => The session is rolled back
Note: Separately invoke Connection#on_exception so that connection failures can be handled
since on_message will Not be called if the connection is lost | [
"Receive",
"messages",
"in",
"a",
"separate",
"thread",
"when",
"they",
"arrive"
]
| cdc2ce1daf643474110146a7505dad5e427030d3 | https://github.com/reidmorrison/jruby-jms/blob/cdc2ce1daf643474110146a7505dad5e427030d3/lib/jms/connection.rb#L441-L463 | train |
reidmorrison/jruby-jms | lib/jms/message_listener_impl.rb | JMS.MessageListenerImpl.statistics | def statistics
raise(ArgumentError, 'First call MessageConsumer::on_message with statistics: true before calling MessageConsumer::statistics()') unless @message_count
duration = (@last_time || Time.now) - @start_time
{
messages: @message_count,
duration: duration,
messages_per_second: (@message_count/duration).to_i
}
end | ruby | def statistics
raise(ArgumentError, 'First call MessageConsumer::on_message with statistics: true before calling MessageConsumer::statistics()') unless @message_count
duration = (@last_time || Time.now) - @start_time
{
messages: @message_count,
duration: duration,
messages_per_second: (@message_count/duration).to_i
}
end | [
"def",
"statistics",
"raise",
"(",
"ArgumentError",
",",
"'First call MessageConsumer::on_message with statistics: true before calling MessageConsumer::statistics()'",
")",
"unless",
"@message_count",
"duration",
"=",
"(",
"@last_time",
"||",
"Time",
".",
"now",
")",
"-",
"@start_time",
"{",
"messages",
":",
"@message_count",
",",
"duration",
":",
"duration",
",",
"messages_per_second",
":",
"(",
"@message_count",
"/",
"duration",
")",
".",
"to_i",
"}",
"end"
]
| Return Statistics gathered for this listener | [
"Return",
"Statistics",
"gathered",
"for",
"this",
"listener"
]
| cdc2ce1daf643474110146a7505dad5e427030d3 | https://github.com/reidmorrison/jruby-jms/blob/cdc2ce1daf643474110146a7505dad5e427030d3/lib/jms/message_listener_impl.rb#L53-L61 | train |
cloudfoundry-attic/cf | lib/micro/plugin.rb | CFMicro.McfCommand.override | def override(config, option, escape=false, &blk)
# override if given on the command line
if opt = input[option]
opt = CFMicro.escape_path(opt) if escape
config[option] = opt
end
config[option] = yield unless config[option]
end | ruby | def override(config, option, escape=false, &blk)
# override if given on the command line
if opt = input[option]
opt = CFMicro.escape_path(opt) if escape
config[option] = opt
end
config[option] = yield unless config[option]
end | [
"def",
"override",
"(",
"config",
",",
"option",
",",
"escape",
"=",
"false",
",",
"&",
"blk",
")",
"if",
"opt",
"=",
"input",
"[",
"option",
"]",
"opt",
"=",
"CFMicro",
".",
"escape_path",
"(",
"opt",
")",
"if",
"escape",
"config",
"[",
"option",
"]",
"=",
"opt",
"end",
"config",
"[",
"option",
"]",
"=",
"yield",
"unless",
"config",
"[",
"option",
"]",
"end"
]
| override with command line arguments and yield the block in case the option isn't set | [
"override",
"with",
"command",
"line",
"arguments",
"and",
"yield",
"the",
"block",
"in",
"case",
"the",
"option",
"isn",
"t",
"set"
]
| 2b47b522e9d5600876ebfd6465d5575265dcc601 | https://github.com/cloudfoundry-attic/cf/blob/2b47b522e9d5600876ebfd6465d5575265dcc601/lib/micro/plugin.rb#L153-L160 | train |
cloudfoundry-attic/cf | lib/manifests/loader/resolver.rb | CFManifests.Resolver.resolve_lexically | def resolve_lexically(resolver, val, ctx)
case val
when Hash
new = {}
val.each do |k, v|
new[k] = resolve_lexically(resolver, v, [val] + ctx)
end
new
when Array
val.collect do |v|
resolve_lexically(resolver, v, ctx)
end
when String
val.gsub(/\$\{([^\}]+)\}/) do
resolve_symbol(resolver, $1, ctx)
end
else
val
end
end | ruby | def resolve_lexically(resolver, val, ctx)
case val
when Hash
new = {}
val.each do |k, v|
new[k] = resolve_lexically(resolver, v, [val] + ctx)
end
new
when Array
val.collect do |v|
resolve_lexically(resolver, v, ctx)
end
when String
val.gsub(/\$\{([^\}]+)\}/) do
resolve_symbol(resolver, $1, ctx)
end
else
val
end
end | [
"def",
"resolve_lexically",
"(",
"resolver",
",",
"val",
",",
"ctx",
")",
"case",
"val",
"when",
"Hash",
"new",
"=",
"{",
"}",
"val",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"new",
"[",
"k",
"]",
"=",
"resolve_lexically",
"(",
"resolver",
",",
"v",
",",
"[",
"val",
"]",
"+",
"ctx",
")",
"end",
"new",
"when",
"Array",
"val",
".",
"collect",
"do",
"|",
"v",
"|",
"resolve_lexically",
"(",
"resolver",
",",
"v",
",",
"ctx",
")",
"end",
"when",
"String",
"val",
".",
"gsub",
"(",
"/",
"\\$",
"\\{",
"\\}",
"\\}",
"/",
")",
"do",
"resolve_symbol",
"(",
"resolver",
",",
"$1",
",",
"ctx",
")",
"end",
"else",
"val",
"end",
"end"
]
| resolve symbols, with hashes introducing new lexical symbols | [
"resolve",
"symbols",
"with",
"hashes",
"introducing",
"new",
"lexical",
"symbols"
]
| 2b47b522e9d5600876ebfd6465d5575265dcc601 | https://github.com/cloudfoundry-attic/cf/blob/2b47b522e9d5600876ebfd6465d5575265dcc601/lib/manifests/loader/resolver.rb#L16-L37 | train |
cloudfoundry-attic/cf | lib/manifests/loader/resolver.rb | CFManifests.Resolver.resolve_symbol | def resolve_symbol(resolver, sym, ctx)
if found = find_symbol(sym.to_sym, ctx)
resolve_lexically(resolver, found, ctx)
found
elsif dynamic = resolver.resolve_symbol(sym)
dynamic
else
fail("Unknown symbol in manifest: #{sym}")
end
end | ruby | def resolve_symbol(resolver, sym, ctx)
if found = find_symbol(sym.to_sym, ctx)
resolve_lexically(resolver, found, ctx)
found
elsif dynamic = resolver.resolve_symbol(sym)
dynamic
else
fail("Unknown symbol in manifest: #{sym}")
end
end | [
"def",
"resolve_symbol",
"(",
"resolver",
",",
"sym",
",",
"ctx",
")",
"if",
"found",
"=",
"find_symbol",
"(",
"sym",
".",
"to_sym",
",",
"ctx",
")",
"resolve_lexically",
"(",
"resolver",
",",
"found",
",",
"ctx",
")",
"found",
"elsif",
"dynamic",
"=",
"resolver",
".",
"resolve_symbol",
"(",
"sym",
")",
"dynamic",
"else",
"fail",
"(",
"\"Unknown symbol in manifest: #{sym}\"",
")",
"end",
"end"
]
| resolve a symbol to its value, and then resolve that value | [
"resolve",
"a",
"symbol",
"to",
"its",
"value",
"and",
"then",
"resolve",
"that",
"value"
]
| 2b47b522e9d5600876ebfd6465d5575265dcc601 | https://github.com/cloudfoundry-attic/cf/blob/2b47b522e9d5600876ebfd6465d5575265dcc601/lib/manifests/loader/resolver.rb#L40-L49 | train |
cloudfoundry-attic/cf | lib/manifests/loader/resolver.rb | CFManifests.Resolver.find_symbol | def find_symbol(sym, ctx)
ctx.each do |h|
if val = resolve_in(h, sym)
return val
end
end
nil
end | ruby | def find_symbol(sym, ctx)
ctx.each do |h|
if val = resolve_in(h, sym)
return val
end
end
nil
end | [
"def",
"find_symbol",
"(",
"sym",
",",
"ctx",
")",
"ctx",
".",
"each",
"do",
"|",
"h",
"|",
"if",
"val",
"=",
"resolve_in",
"(",
"h",
",",
"sym",
")",
"return",
"val",
"end",
"end",
"nil",
"end"
]
| search for a symbol introduced in the lexical context | [
"search",
"for",
"a",
"symbol",
"introduced",
"in",
"the",
"lexical",
"context"
]
| 2b47b522e9d5600876ebfd6465d5575265dcc601 | https://github.com/cloudfoundry-attic/cf/blob/2b47b522e9d5600876ebfd6465d5575265dcc601/lib/manifests/loader/resolver.rb#L52-L60 | train |
cloudfoundry-attic/cf | lib/manifests/loader/resolver.rb | CFManifests.Resolver.find_in_hash | def find_in_hash(hash, where)
what = hash
where.each do |x|
return nil unless what.is_a?(Hash)
what = what[x]
end
what
end | ruby | def find_in_hash(hash, where)
what = hash
where.each do |x|
return nil unless what.is_a?(Hash)
what = what[x]
end
what
end | [
"def",
"find_in_hash",
"(",
"hash",
",",
"where",
")",
"what",
"=",
"hash",
"where",
".",
"each",
"do",
"|",
"x",
"|",
"return",
"nil",
"unless",
"what",
".",
"is_a?",
"(",
"Hash",
")",
"what",
"=",
"what",
"[",
"x",
"]",
"end",
"what",
"end"
]
| helper for following a path of values in a hash | [
"helper",
"for",
"following",
"a",
"path",
"of",
"values",
"in",
"a",
"hash"
]
| 2b47b522e9d5600876ebfd6465d5575265dcc601 | https://github.com/cloudfoundry-attic/cf/blob/2b47b522e9d5600876ebfd6465d5575265dcc601/lib/manifests/loader/resolver.rb#L69-L77 | train |
cloudfoundry-attic/cf | lib/manifests/loader/builder.rb | CFManifests.Builder.build | def build(file)
manifest = YAML.load_file file
raise CFManifests::InvalidManifest.new(file) unless manifest
Array(manifest["inherit"]).each do |path|
manifest = merge_parent(path, manifest)
end
manifest.delete("inherit")
manifest
end | ruby | def build(file)
manifest = YAML.load_file file
raise CFManifests::InvalidManifest.new(file) unless manifest
Array(manifest["inherit"]).each do |path|
manifest = merge_parent(path, manifest)
end
manifest.delete("inherit")
manifest
end | [
"def",
"build",
"(",
"file",
")",
"manifest",
"=",
"YAML",
".",
"load_file",
"file",
"raise",
"CFManifests",
"::",
"InvalidManifest",
".",
"new",
"(",
"file",
")",
"unless",
"manifest",
"Array",
"(",
"manifest",
"[",
"\"inherit\"",
"]",
")",
".",
"each",
"do",
"|",
"path",
"|",
"manifest",
"=",
"merge_parent",
"(",
"path",
",",
"manifest",
")",
"end",
"manifest",
".",
"delete",
"(",
"\"inherit\"",
")",
"manifest",
"end"
]
| parse a manifest and merge with its inherited manifests | [
"parse",
"a",
"manifest",
"and",
"merge",
"with",
"its",
"inherited",
"manifests"
]
| 2b47b522e9d5600876ebfd6465d5575265dcc601 | https://github.com/cloudfoundry-attic/cf/blob/2b47b522e9d5600876ebfd6465d5575265dcc601/lib/manifests/loader/builder.rb#L6-L17 | train |
cloudfoundry-attic/cf | lib/manifests/loader/builder.rb | CFManifests.Builder.merge_manifest | def merge_manifest(parent, child)
merge = proc do |_, old, new|
if new.is_a?(Hash) && old.is_a?(Hash)
old.merge(new, &merge)
else
new
end
end
parent.merge(child, &merge)
end | ruby | def merge_manifest(parent, child)
merge = proc do |_, old, new|
if new.is_a?(Hash) && old.is_a?(Hash)
old.merge(new, &merge)
else
new
end
end
parent.merge(child, &merge)
end | [
"def",
"merge_manifest",
"(",
"parent",
",",
"child",
")",
"merge",
"=",
"proc",
"do",
"|",
"_",
",",
"old",
",",
"new",
"|",
"if",
"new",
".",
"is_a?",
"(",
"Hash",
")",
"&&",
"old",
".",
"is_a?",
"(",
"Hash",
")",
"old",
".",
"merge",
"(",
"new",
",",
"&",
"merge",
")",
"else",
"new",
"end",
"end",
"parent",
".",
"merge",
"(",
"child",
",",
"&",
"merge",
")",
"end"
]
| deep hash merge | [
"deep",
"hash",
"merge"
]
| 2b47b522e9d5600876ebfd6465d5575265dcc601 | https://github.com/cloudfoundry-attic/cf/blob/2b47b522e9d5600876ebfd6465d5575265dcc601/lib/manifests/loader/builder.rb#L27-L37 | train |
plu/simctl | lib/simctl/list.rb | SimCtl.List.where | def where(filter)
return self if filter.nil?
select do |item|
matches = true
filter.each do |key, value|
matches &= case value
when Regexp
item.send(key) =~ value
else
item.send(key) == value
end
end
matches
end
end | ruby | def where(filter)
return self if filter.nil?
select do |item|
matches = true
filter.each do |key, value|
matches &= case value
when Regexp
item.send(key) =~ value
else
item.send(key) == value
end
end
matches
end
end | [
"def",
"where",
"(",
"filter",
")",
"return",
"self",
"if",
"filter",
".",
"nil?",
"select",
"do",
"|",
"item",
"|",
"matches",
"=",
"true",
"filter",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"matches",
"&=",
"case",
"value",
"when",
"Regexp",
"item",
".",
"send",
"(",
"key",
")",
"=~",
"value",
"else",
"item",
".",
"send",
"(",
"key",
")",
"==",
"value",
"end",
"end",
"matches",
"end",
"end"
]
| Filters an array of objects by a given hash. The keys of
the hash must be methods implemented by the objects. The
values of the hash are compared to the values the object
returns when calling the methods.
@param filter [Hash] the filters that should be applied
@return [Array] the filtered array. | [
"Filters",
"an",
"array",
"of",
"objects",
"by",
"a",
"given",
"hash",
".",
"The",
"keys",
"of",
"the",
"hash",
"must",
"be",
"methods",
"implemented",
"by",
"the",
"objects",
".",
"The",
"values",
"of",
"the",
"hash",
"are",
"compared",
"to",
"the",
"values",
"the",
"object",
"returns",
"when",
"calling",
"the",
"methods",
"."
]
| 7f64887935d0a6a3caa0630e167f7b3711b67857 | https://github.com/plu/simctl/blob/7f64887935d0a6a3caa0630e167f7b3711b67857/lib/simctl/list.rb#L10-L24 | train |
plu/simctl | lib/simctl/device.rb | SimCtl.Device.reload | def reload
device = SimCtl.device(udid: udid)
device.instance_variables.each do |ivar|
instance_variable_set(ivar, device.instance_variable_get(ivar))
end
end | ruby | def reload
device = SimCtl.device(udid: udid)
device.instance_variables.each do |ivar|
instance_variable_set(ivar, device.instance_variable_get(ivar))
end
end | [
"def",
"reload",
"device",
"=",
"SimCtl",
".",
"device",
"(",
"udid",
":",
"udid",
")",
"device",
".",
"instance_variables",
".",
"each",
"do",
"|",
"ivar",
"|",
"instance_variable_set",
"(",
"ivar",
",",
"device",
".",
"instance_variable_get",
"(",
"ivar",
")",
")",
"end",
"end"
]
| Reloads the device information
@return [void] | [
"Reloads",
"the",
"device",
"information"
]
| 7f64887935d0a6a3caa0630e167f7b3711b67857 | https://github.com/plu/simctl/blob/7f64887935d0a6a3caa0630e167f7b3711b67857/lib/simctl/device.rb#L131-L136 | train |
plu/simctl | lib/simctl/device.rb | SimCtl.Device.wait | def wait(timeout = SimCtl.default_timeout)
Timeout.timeout(timeout) do
loop do
break if yield SimCtl.device(udid: udid)
end
end
reload
end | ruby | def wait(timeout = SimCtl.default_timeout)
Timeout.timeout(timeout) do
loop do
break if yield SimCtl.device(udid: udid)
end
end
reload
end | [
"def",
"wait",
"(",
"timeout",
"=",
"SimCtl",
".",
"default_timeout",
")",
"Timeout",
".",
"timeout",
"(",
"timeout",
")",
"do",
"loop",
"do",
"break",
"if",
"yield",
"SimCtl",
".",
"device",
"(",
"udid",
":",
"udid",
")",
"end",
"end",
"reload",
"end"
]
| Reloads the device until the given block returns true
@return [void] | [
"Reloads",
"the",
"device",
"until",
"the",
"given",
"block",
"returns",
"true"
]
| 7f64887935d0a6a3caa0630e167f7b3711b67857 | https://github.com/plu/simctl/blob/7f64887935d0a6a3caa0630e167f7b3711b67857/lib/simctl/device.rb#L204-L211 | train |
plu/simctl | lib/simctl/device_settings.rb | SimCtl.DeviceSettings.disable_keyboard_helpers | def disable_keyboard_helpers
edit_plist(path.preferences_plist) do |plist|
%w[
KeyboardAllowPaddle
KeyboardAssistant
KeyboardAutocapitalization
KeyboardAutocorrection
KeyboardCapsLock
KeyboardCheckSpelling
KeyboardPeriodShortcut
KeyboardPrediction
KeyboardShowPredictionBar
].each do |key|
plist[key] = false
end
end
end | ruby | def disable_keyboard_helpers
edit_plist(path.preferences_plist) do |plist|
%w[
KeyboardAllowPaddle
KeyboardAssistant
KeyboardAutocapitalization
KeyboardAutocorrection
KeyboardCapsLock
KeyboardCheckSpelling
KeyboardPeriodShortcut
KeyboardPrediction
KeyboardShowPredictionBar
].each do |key|
plist[key] = false
end
end
end | [
"def",
"disable_keyboard_helpers",
"edit_plist",
"(",
"path",
".",
"preferences_plist",
")",
"do",
"|",
"plist",
"|",
"%w[",
"KeyboardAllowPaddle",
"KeyboardAssistant",
"KeyboardAutocapitalization",
"KeyboardAutocorrection",
"KeyboardCapsLock",
"KeyboardCheckSpelling",
"KeyboardPeriodShortcut",
"KeyboardPrediction",
"KeyboardShowPredictionBar",
"]",
".",
"each",
"do",
"|",
"key",
"|",
"plist",
"[",
"key",
"]",
"=",
"false",
"end",
"end",
"end"
]
| Disables the keyboard helpers
@return [void] | [
"Disables",
"the",
"keyboard",
"helpers"
]
| 7f64887935d0a6a3caa0630e167f7b3711b67857 | https://github.com/plu/simctl/blob/7f64887935d0a6a3caa0630e167f7b3711b67857/lib/simctl/device_settings.rb#L14-L30 | train |
plu/simctl | lib/simctl/device_settings.rb | SimCtl.DeviceSettings.set_language | def set_language(language)
edit_plist(path.global_preferences_plist) do |plist|
key = 'AppleLanguages'
plist[key] = [] unless plist.key?(key)
plist[key].unshift(language).uniq!
end
end | ruby | def set_language(language)
edit_plist(path.global_preferences_plist) do |plist|
key = 'AppleLanguages'
plist[key] = [] unless plist.key?(key)
plist[key].unshift(language).uniq!
end
end | [
"def",
"set_language",
"(",
"language",
")",
"edit_plist",
"(",
"path",
".",
"global_preferences_plist",
")",
"do",
"|",
"plist",
"|",
"key",
"=",
"'AppleLanguages'",
"plist",
"[",
"key",
"]",
"=",
"[",
"]",
"unless",
"plist",
".",
"key?",
"(",
"key",
")",
"plist",
"[",
"key",
"]",
".",
"unshift",
"(",
"language",
")",
".",
"uniq!",
"end",
"end"
]
| Sets the device language
@return [void] | [
"Sets",
"the",
"device",
"language"
]
| 7f64887935d0a6a3caa0630e167f7b3711b67857 | https://github.com/plu/simctl/blob/7f64887935d0a6a3caa0630e167f7b3711b67857/lib/simctl/device_settings.rb#L53-L59 | train |
dicom/ruby-dicom | lib/dicom/parent.rb | DICOM.Parent.count_all | def count_all
# Iterate over all elements, and repeat recursively for all elements which themselves contain children.
total_count = count
@tags.each_value do |value|
total_count += value.count_all if value.children?
end
return total_count
end | ruby | def count_all
# Iterate over all elements, and repeat recursively for all elements which themselves contain children.
total_count = count
@tags.each_value do |value|
total_count += value.count_all if value.children?
end
return total_count
end | [
"def",
"count_all",
"total_count",
"=",
"count",
"@tags",
".",
"each_value",
"do",
"|",
"value",
"|",
"total_count",
"+=",
"value",
".",
"count_all",
"if",
"value",
".",
"children?",
"end",
"return",
"total_count",
"end"
]
| Gives the total number of elements connected to this parent.
This count includes all the elements contained in any possible child elements.
@return [Integer] The total number of child elements connected to this parent | [
"Gives",
"the",
"total",
"number",
"of",
"elements",
"connected",
"to",
"this",
"parent",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/parent.rb#L109-L116 | train |
dicom/ruby-dicom | lib/dicom/parent.rb | DICOM.Parent.delete | def delete(tag_or_index, options={})
check_key(tag_or_index, :delete)
# We need to delete the specified child element's parent reference in addition to removing it from the tag Hash.
element = self[tag_or_index]
if element
element.parent = nil unless options[:no_follow]
@tags.delete(tag_or_index)
end
end | ruby | def delete(tag_or_index, options={})
check_key(tag_or_index, :delete)
# We need to delete the specified child element's parent reference in addition to removing it from the tag Hash.
element = self[tag_or_index]
if element
element.parent = nil unless options[:no_follow]
@tags.delete(tag_or_index)
end
end | [
"def",
"delete",
"(",
"tag_or_index",
",",
"options",
"=",
"{",
"}",
")",
"check_key",
"(",
"tag_or_index",
",",
":delete",
")",
"element",
"=",
"self",
"[",
"tag_or_index",
"]",
"if",
"element",
"element",
".",
"parent",
"=",
"nil",
"unless",
"options",
"[",
":no_follow",
"]",
"@tags",
".",
"delete",
"(",
"tag_or_index",
")",
"end",
"end"
]
| Deletes the specified element from this parent.
@param [String, Integer] tag_or_index a ruby-dicom tag string or item index
@param [Hash] options the options used for deleting the element
option options [Boolean] :no_follow when true, the method does not update the parent attribute of the child that is deleted
@example Delete an Element from a DObject instance
dcm.delete("0008,0090")
@example Delete Item 1 from a Sequence
dcm["3006,0020"].delete(1) | [
"Deletes",
"the",
"specified",
"element",
"from",
"this",
"parent",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/parent.rb#L128-L136 | train |
dicom/ruby-dicom | lib/dicom/parent.rb | DICOM.Parent.delete_group | def delete_group(group_string)
group_elements = group(group_string)
group_elements.each do |element|
delete(element.tag)
end
end | ruby | def delete_group(group_string)
group_elements = group(group_string)
group_elements.each do |element|
delete(element.tag)
end
end | [
"def",
"delete_group",
"(",
"group_string",
")",
"group_elements",
"=",
"group",
"(",
"group_string",
")",
"group_elements",
".",
"each",
"do",
"|",
"element",
"|",
"delete",
"(",
"element",
".",
"tag",
")",
"end",
"end"
]
| Deletes all elements of the specified group from this parent.
@param [String] group_string a group string (the first 4 characters of a tag string)
@example Delete the File Meta Group of a DICOM object
dcm.delete_group("0002") | [
"Deletes",
"all",
"elements",
"of",
"the",
"specified",
"group",
"from",
"this",
"parent",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/parent.rb#L152-L157 | train |
dicom/ruby-dicom | lib/dicom/parent.rb | DICOM.Parent.encode_children | def encode_children(old_endian)
# Cycle through all levels of children recursively:
children.each do |element|
if element.children?
element.encode_children(old_endian)
elsif element.is_a?(Element)
encode_child(element, old_endian)
end
end
end | ruby | def encode_children(old_endian)
# Cycle through all levels of children recursively:
children.each do |element|
if element.children?
element.encode_children(old_endian)
elsif element.is_a?(Element)
encode_child(element, old_endian)
end
end
end | [
"def",
"encode_children",
"(",
"old_endian",
")",
"children",
".",
"each",
"do",
"|",
"element",
"|",
"if",
"element",
".",
"children?",
"element",
".",
"encode_children",
"(",
"old_endian",
")",
"elsif",
"element",
".",
"is_a?",
"(",
"Element",
")",
"encode_child",
"(",
"element",
",",
"old_endian",
")",
"end",
"end",
"end"
]
| Re-encodes the binary data strings of all child Element instances.
This also includes all the elements contained in any possible child elements.
@note This method is only intended for internal library use, but for technical reasons
(the fact that is called between instances of different classes), can't be made private.
@param [Boolean] old_endian the previous endianness of the elements/DObject instance (used for decoding values from binary) | [
"Re",
"-",
"encodes",
"the",
"binary",
"data",
"strings",
"of",
"all",
"child",
"Element",
"instances",
".",
"This",
"also",
"includes",
"all",
"the",
"elements",
"contained",
"in",
"any",
"possible",
"child",
"elements",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/parent.rb#L241-L250 | train |
dicom/ruby-dicom | lib/dicom/parent.rb | DICOM.Parent.group | def group(group_string)
raise ArgumentError, "Expected String, got #{group_string.class}." unless group_string.is_a?(String)
found = Array.new
children.each do |child|
found << child if child.tag.group == group_string.upcase
end
return found
end | ruby | def group(group_string)
raise ArgumentError, "Expected String, got #{group_string.class}." unless group_string.is_a?(String)
found = Array.new
children.each do |child|
found << child if child.tag.group == group_string.upcase
end
return found
end | [
"def",
"group",
"(",
"group_string",
")",
"raise",
"ArgumentError",
",",
"\"Expected String, got #{group_string.class}.\"",
"unless",
"group_string",
".",
"is_a?",
"(",
"String",
")",
"found",
"=",
"Array",
".",
"new",
"children",
".",
"each",
"do",
"|",
"child",
"|",
"found",
"<<",
"child",
"if",
"child",
".",
"tag",
".",
"group",
"==",
"group_string",
".",
"upcase",
"end",
"return",
"found",
"end"
]
| Returns an array of all child elements that belongs to the specified group.
@param [String] group_string a group string (the first 4 characters of a tag string)
@return [Array<Element, Item, Sequence>] the matching child elements (an empty array if no children matches) | [
"Returns",
"an",
"array",
"of",
"all",
"child",
"elements",
"that",
"belongs",
"to",
"the",
"specified",
"group",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/parent.rb#L272-L279 | train |
dicom/ruby-dicom | lib/dicom/parent.rb | DICOM.Parent.handle_print | def handle_print(index, max_digits, max_name, max_length, max_generations, visualization, options={})
# FIXME: This method is somewhat complex, and some simplification, if possible, wouldn't hurt.
elements = Array.new
s = " "
hook_symbol = "|_"
last_item_symbol = " "
nonlast_item_symbol = "| "
children.each_with_index do |element, i|
n_parents = element.parents.length
# Formatting: Index
i_s = s*(max_digits-(index).to_s.length)
# Formatting: Name (and Tag)
if element.tag == ITEM_TAG
# Add index numbers to the Item names:
name = "#{element.name} (\##{i})"
else
name = element.name
end
n_s = s*(max_name-name.length)
# Formatting: Tag
tag = "#{visualization.join}#{element.tag}"
t_s = s*((max_generations-1)*2+9-tag.length)
# Formatting: Length
l_s = s*(max_length-element.length.to_s.length)
# Formatting Value:
if element.is_a?(Element)
value = element.value.to_s
else
value = ""
end
if options[:value_max]
value = "#{value[0..(options[:value_max]-3)]}.." if value.length > options[:value_max]
end
elements << "#{i_s}#{index} #{tag}#{t_s} #{name}#{n_s} #{element.vr} #{l_s}#{element.length} #{value}"
index += 1
# If we have child elements, print those elements recursively:
if element.children?
if n_parents > 1
child_visualization = Array.new
child_visualization.replace(visualization)
if element == children.first
if children.length == 1
# Last item:
child_visualization.insert(n_parents-2, last_item_symbol)
else
# More items follows:
child_visualization.insert(n_parents-2, nonlast_item_symbol)
end
elsif element == children.last
# Last item:
child_visualization[n_parents-2] = last_item_symbol
child_visualization.insert(-1, hook_symbol)
else
# Neither first nor last (more items follows):
child_visualization.insert(n_parents-2, nonlast_item_symbol)
end
elsif n_parents == 1
child_visualization = Array.new(1, hook_symbol)
else
child_visualization = Array.new
end
new_elements, index = element.handle_print(index, max_digits, max_name, max_length, max_generations, child_visualization, options)
elements << new_elements
end
end
return elements.flatten, index
end | ruby | def handle_print(index, max_digits, max_name, max_length, max_generations, visualization, options={})
# FIXME: This method is somewhat complex, and some simplification, if possible, wouldn't hurt.
elements = Array.new
s = " "
hook_symbol = "|_"
last_item_symbol = " "
nonlast_item_symbol = "| "
children.each_with_index do |element, i|
n_parents = element.parents.length
# Formatting: Index
i_s = s*(max_digits-(index).to_s.length)
# Formatting: Name (and Tag)
if element.tag == ITEM_TAG
# Add index numbers to the Item names:
name = "#{element.name} (\##{i})"
else
name = element.name
end
n_s = s*(max_name-name.length)
# Formatting: Tag
tag = "#{visualization.join}#{element.tag}"
t_s = s*((max_generations-1)*2+9-tag.length)
# Formatting: Length
l_s = s*(max_length-element.length.to_s.length)
# Formatting Value:
if element.is_a?(Element)
value = element.value.to_s
else
value = ""
end
if options[:value_max]
value = "#{value[0..(options[:value_max]-3)]}.." if value.length > options[:value_max]
end
elements << "#{i_s}#{index} #{tag}#{t_s} #{name}#{n_s} #{element.vr} #{l_s}#{element.length} #{value}"
index += 1
# If we have child elements, print those elements recursively:
if element.children?
if n_parents > 1
child_visualization = Array.new
child_visualization.replace(visualization)
if element == children.first
if children.length == 1
# Last item:
child_visualization.insert(n_parents-2, last_item_symbol)
else
# More items follows:
child_visualization.insert(n_parents-2, nonlast_item_symbol)
end
elsif element == children.last
# Last item:
child_visualization[n_parents-2] = last_item_symbol
child_visualization.insert(-1, hook_symbol)
else
# Neither first nor last (more items follows):
child_visualization.insert(n_parents-2, nonlast_item_symbol)
end
elsif n_parents == 1
child_visualization = Array.new(1, hook_symbol)
else
child_visualization = Array.new
end
new_elements, index = element.handle_print(index, max_digits, max_name, max_length, max_generations, child_visualization, options)
elements << new_elements
end
end
return elements.flatten, index
end | [
"def",
"handle_print",
"(",
"index",
",",
"max_digits",
",",
"max_name",
",",
"max_length",
",",
"max_generations",
",",
"visualization",
",",
"options",
"=",
"{",
"}",
")",
"elements",
"=",
"Array",
".",
"new",
"s",
"=",
"\" \"",
"hook_symbol",
"=",
"\"|_\"",
"last_item_symbol",
"=",
"\" \"",
"nonlast_item_symbol",
"=",
"\"| \"",
"children",
".",
"each_with_index",
"do",
"|",
"element",
",",
"i",
"|",
"n_parents",
"=",
"element",
".",
"parents",
".",
"length",
"i_s",
"=",
"s",
"*",
"(",
"max_digits",
"-",
"(",
"index",
")",
".",
"to_s",
".",
"length",
")",
"if",
"element",
".",
"tag",
"==",
"ITEM_TAG",
"name",
"=",
"\"#{element.name} (\\##{i})\"",
"else",
"name",
"=",
"element",
".",
"name",
"end",
"n_s",
"=",
"s",
"*",
"(",
"max_name",
"-",
"name",
".",
"length",
")",
"tag",
"=",
"\"#{visualization.join}#{element.tag}\"",
"t_s",
"=",
"s",
"*",
"(",
"(",
"max_generations",
"-",
"1",
")",
"*",
"2",
"+",
"9",
"-",
"tag",
".",
"length",
")",
"l_s",
"=",
"s",
"*",
"(",
"max_length",
"-",
"element",
".",
"length",
".",
"to_s",
".",
"length",
")",
"if",
"element",
".",
"is_a?",
"(",
"Element",
")",
"value",
"=",
"element",
".",
"value",
".",
"to_s",
"else",
"value",
"=",
"\"\"",
"end",
"if",
"options",
"[",
":value_max",
"]",
"value",
"=",
"\"#{value[0..(options[:value_max]-3)]}..\"",
"if",
"value",
".",
"length",
">",
"options",
"[",
":value_max",
"]",
"end",
"elements",
"<<",
"\"#{i_s}#{index} #{tag}#{t_s} #{name}#{n_s} #{element.vr} #{l_s}#{element.length} #{value}\"",
"index",
"+=",
"1",
"if",
"element",
".",
"children?",
"if",
"n_parents",
">",
"1",
"child_visualization",
"=",
"Array",
".",
"new",
"child_visualization",
".",
"replace",
"(",
"visualization",
")",
"if",
"element",
"==",
"children",
".",
"first",
"if",
"children",
".",
"length",
"==",
"1",
"child_visualization",
".",
"insert",
"(",
"n_parents",
"-",
"2",
",",
"last_item_symbol",
")",
"else",
"child_visualization",
".",
"insert",
"(",
"n_parents",
"-",
"2",
",",
"nonlast_item_symbol",
")",
"end",
"elsif",
"element",
"==",
"children",
".",
"last",
"child_visualization",
"[",
"n_parents",
"-",
"2",
"]",
"=",
"last_item_symbol",
"child_visualization",
".",
"insert",
"(",
"-",
"1",
",",
"hook_symbol",
")",
"else",
"child_visualization",
".",
"insert",
"(",
"n_parents",
"-",
"2",
",",
"nonlast_item_symbol",
")",
"end",
"elsif",
"n_parents",
"==",
"1",
"child_visualization",
"=",
"Array",
".",
"new",
"(",
"1",
",",
"hook_symbol",
")",
"else",
"child_visualization",
"=",
"Array",
".",
"new",
"end",
"new_elements",
",",
"index",
"=",
"element",
".",
"handle_print",
"(",
"index",
",",
"max_digits",
",",
"max_name",
",",
"max_length",
",",
"max_generations",
",",
"child_visualization",
",",
"options",
")",
"elements",
"<<",
"new_elements",
"end",
"end",
"return",
"elements",
".",
"flatten",
",",
"index",
"end"
]
| Gathers the desired information from the selected data elements and
processes this information to make a text output which is nicely formatted.
@note This method is only intended for internal library use, but for technical reasons
(the fact that is called between instances of different classes), can't be made private.
The method is used by the print() method to construct its text output.
@param [Integer] index the index which is given to the first child of this parent
@param [Integer] max_digits the maximum number of digits in the index of an element (in reality the number of digits of the last element)
@param [Integer] max_name the maximum number of characters in the name of any element to be printed
@param [Integer] max_length the maximum number of digits in the length of an element
@param [Integer] max_generations the maximum number of generations of children for this parent
@param [Integer] visualization an array of string symbols which visualizes the tree structure that the children of this particular parent belongs to (for no visualization, an empty array is passed)
@param [Hash] options the options to use when processing the print information
@option options [Integer] :value_max if a value max length is specified, the element values which exceeds this are trimmed
@return [Array] a text array and an index of the last element | [
"Gathers",
"the",
"desired",
"information",
"from",
"the",
"selected",
"data",
"elements",
"and",
"processes",
"this",
"information",
"to",
"make",
"a",
"text",
"output",
"which",
"is",
"nicely",
"formatted",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/parent.rb#L298-L364 | train |
dicom/ruby-dicom | lib/dicom/parent.rb | DICOM.Parent.max_lengths | def max_lengths
max_name = 0
max_length = 0
max_generations = 0
children.each do |element|
if element.children?
max_nc, max_lc, max_gc = element.max_lengths
max_name = max_nc if max_nc > max_name
max_length = max_lc if max_lc > max_length
max_generations = max_gc if max_gc > max_generations
end
n_length = element.name.length
l_length = element.length.to_s.length
generations = element.parents.length
max_name = n_length if n_length > max_name
max_length = l_length if l_length > max_length
max_generations = generations if generations > max_generations
end
return max_name, max_length, max_generations
end | ruby | def max_lengths
max_name = 0
max_length = 0
max_generations = 0
children.each do |element|
if element.children?
max_nc, max_lc, max_gc = element.max_lengths
max_name = max_nc if max_nc > max_name
max_length = max_lc if max_lc > max_length
max_generations = max_gc if max_gc > max_generations
end
n_length = element.name.length
l_length = element.length.to_s.length
generations = element.parents.length
max_name = n_length if n_length > max_name
max_length = l_length if l_length > max_length
max_generations = generations if generations > max_generations
end
return max_name, max_length, max_generations
end | [
"def",
"max_lengths",
"max_name",
"=",
"0",
"max_length",
"=",
"0",
"max_generations",
"=",
"0",
"children",
".",
"each",
"do",
"|",
"element",
"|",
"if",
"element",
".",
"children?",
"max_nc",
",",
"max_lc",
",",
"max_gc",
"=",
"element",
".",
"max_lengths",
"max_name",
"=",
"max_nc",
"if",
"max_nc",
">",
"max_name",
"max_length",
"=",
"max_lc",
"if",
"max_lc",
">",
"max_length",
"max_generations",
"=",
"max_gc",
"if",
"max_gc",
">",
"max_generations",
"end",
"n_length",
"=",
"element",
".",
"name",
".",
"length",
"l_length",
"=",
"element",
".",
"length",
".",
"to_s",
".",
"length",
"generations",
"=",
"element",
".",
"parents",
".",
"length",
"max_name",
"=",
"n_length",
"if",
"n_length",
">",
"max_name",
"max_length",
"=",
"l_length",
"if",
"l_length",
">",
"max_length",
"max_generations",
"=",
"generations",
"if",
"generations",
">",
"max_generations",
"end",
"return",
"max_name",
",",
"max_length",
",",
"max_generations",
"end"
]
| Finds and returns the maximum character lengths of name and length which occurs for any child element,
as well as the maximum number of generations of elements.
@note This method is only intended for internal library use, but for technical reasons
(the fact that is called between instances of different classes), can't be made private.
The method is used by the print() method to achieve a proper format in its output. | [
"Finds",
"and",
"returns",
"the",
"maximum",
"character",
"lengths",
"of",
"name",
"and",
"length",
"which",
"occurs",
"for",
"any",
"child",
"element",
"as",
"well",
"as",
"the",
"maximum",
"number",
"of",
"generations",
"of",
"elements",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/parent.rb#L421-L440 | train |
dicom/ruby-dicom | lib/dicom/parent.rb | DICOM.Parent.method_missing | def method_missing(sym, *args, &block)
s = sym.to_s
action = s[-1]
# Try to match the method against a tag from the dictionary:
tag = LIBRARY.as_tag(s) || LIBRARY.as_tag(s[0..-2])
if tag
if action == '?'
# Query:
return self.exists?(tag)
elsif action == '='
# Assignment:
unless args.length==0 || args[0].nil?
# What kind of element to create?
if tag == 'FFFE,E000'
return self.add_item
elsif LIBRARY.element(tag).vr == 'SQ'
return self.add(Sequence.new(tag))
else
return self.add(Element.new(tag, *args))
end
else
return self.delete(tag)
end
else
# Retrieval:
return self[tag]
end
end
# Forward to Object#method_missing:
super
end | ruby | def method_missing(sym, *args, &block)
s = sym.to_s
action = s[-1]
# Try to match the method against a tag from the dictionary:
tag = LIBRARY.as_tag(s) || LIBRARY.as_tag(s[0..-2])
if tag
if action == '?'
# Query:
return self.exists?(tag)
elsif action == '='
# Assignment:
unless args.length==0 || args[0].nil?
# What kind of element to create?
if tag == 'FFFE,E000'
return self.add_item
elsif LIBRARY.element(tag).vr == 'SQ'
return self.add(Sequence.new(tag))
else
return self.add(Element.new(tag, *args))
end
else
return self.delete(tag)
end
else
# Retrieval:
return self[tag]
end
end
# Forward to Object#method_missing:
super
end | [
"def",
"method_missing",
"(",
"sym",
",",
"*",
"args",
",",
"&",
"block",
")",
"s",
"=",
"sym",
".",
"to_s",
"action",
"=",
"s",
"[",
"-",
"1",
"]",
"tag",
"=",
"LIBRARY",
".",
"as_tag",
"(",
"s",
")",
"||",
"LIBRARY",
".",
"as_tag",
"(",
"s",
"[",
"0",
"..",
"-",
"2",
"]",
")",
"if",
"tag",
"if",
"action",
"==",
"'?'",
"return",
"self",
".",
"exists?",
"(",
"tag",
")",
"elsif",
"action",
"==",
"'='",
"unless",
"args",
".",
"length",
"==",
"0",
"||",
"args",
"[",
"0",
"]",
".",
"nil?",
"if",
"tag",
"==",
"'FFFE,E000'",
"return",
"self",
".",
"add_item",
"elsif",
"LIBRARY",
".",
"element",
"(",
"tag",
")",
".",
"vr",
"==",
"'SQ'",
"return",
"self",
".",
"add",
"(",
"Sequence",
".",
"new",
"(",
"tag",
")",
")",
"else",
"return",
"self",
".",
"add",
"(",
"Element",
".",
"new",
"(",
"tag",
",",
"*",
"args",
")",
")",
"end",
"else",
"return",
"self",
".",
"delete",
"(",
"tag",
")",
"end",
"else",
"return",
"self",
"[",
"tag",
"]",
"end",
"end",
"super",
"end"
]
| Handles missing methods, which in our case is intended to be dynamic
method names matching DICOM elements in the dictionary.
When a dynamic method name is matched against a DICOM element, this method:
* Returns the element if the method name suggests an element retrieval, and the element exists.
* Returns nil if the method name suggests an element retrieval, but the element doesn't exist.
* Returns a boolean, if the method name suggests a query (?), based on whether the matched element exists or not.
* When the method name suggests assignment (=), an element is created with the supplied arguments, or if the argument is nil, the element is deleted.
* When a dynamic method name is not matched against a DICOM element, and the method is not defined by the parent, a NoMethodError is raised.
@param [Symbol] sym a method name | [
"Handles",
"missing",
"methods",
"which",
"in",
"our",
"case",
"is",
"intended",
"to",
"be",
"dynamic",
"method",
"names",
"matching",
"DICOM",
"elements",
"in",
"the",
"dictionary",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/parent.rb#L455-L485 | train |
dicom/ruby-dicom | lib/dicom/parent.rb | DICOM.Parent.print | def print(options={})
# FIXME: Perhaps a :children => false option would be a good idea (to avoid lengthy printouts in cases where this would be desirable)?
# FIXME: Speed. The new print algorithm may seem to be slower than the old one (observed on complex, hiearchical DICOM files). Perhaps it can be optimized?
elements = Array.new
# We first gather some properties that is necessary to produce a nicely formatted printout (max_lengths, count_all),
# then the actual information is gathered (handle_print),
# and lastly, we pass this information on to the methods which print the output (print_file or print_screen).
if count > 0
max_name, max_length, max_generations = max_lengths
max_digits = count_all.to_s.length
visualization = Array.new
elements, index = handle_print(start_index=1, max_digits, max_name, max_length, max_generations, visualization, options)
if options[:file]
print_file(elements, options[:file])
else
print_screen(elements)
end
else
puts "Notice: Object #{self} is empty (contains no data elements)!"
end
return elements
end | ruby | def print(options={})
# FIXME: Perhaps a :children => false option would be a good idea (to avoid lengthy printouts in cases where this would be desirable)?
# FIXME: Speed. The new print algorithm may seem to be slower than the old one (observed on complex, hiearchical DICOM files). Perhaps it can be optimized?
elements = Array.new
# We first gather some properties that is necessary to produce a nicely formatted printout (max_lengths, count_all),
# then the actual information is gathered (handle_print),
# and lastly, we pass this information on to the methods which print the output (print_file or print_screen).
if count > 0
max_name, max_length, max_generations = max_lengths
max_digits = count_all.to_s.length
visualization = Array.new
elements, index = handle_print(start_index=1, max_digits, max_name, max_length, max_generations, visualization, options)
if options[:file]
print_file(elements, options[:file])
else
print_screen(elements)
end
else
puts "Notice: Object #{self} is empty (contains no data elements)!"
end
return elements
end | [
"def",
"print",
"(",
"options",
"=",
"{",
"}",
")",
"elements",
"=",
"Array",
".",
"new",
"if",
"count",
">",
"0",
"max_name",
",",
"max_length",
",",
"max_generations",
"=",
"max_lengths",
"max_digits",
"=",
"count_all",
".",
"to_s",
".",
"length",
"visualization",
"=",
"Array",
".",
"new",
"elements",
",",
"index",
"=",
"handle_print",
"(",
"start_index",
"=",
"1",
",",
"max_digits",
",",
"max_name",
",",
"max_length",
",",
"max_generations",
",",
"visualization",
",",
"options",
")",
"if",
"options",
"[",
":file",
"]",
"print_file",
"(",
"elements",
",",
"options",
"[",
":file",
"]",
")",
"else",
"print_screen",
"(",
"elements",
")",
"end",
"else",
"puts",
"\"Notice: Object #{self} is empty (contains no data elements)!\"",
"end",
"return",
"elements",
"end"
]
| Prints all child elementals of this particular parent.
Information such as tag, parent-child relationship, name, vr, length and value is
gathered for each element and processed to produce a nicely formatted output.
@param [Hash] options the options to use for handling the printout
option options [Integer] :value_max if a value max length is specified, the element values which exceeds this are trimmed
option options [String] :file if a file path is specified, the output is printed to this file instead of being printed to the screen
@return [Array<String>] an array of formatted element string lines
@example Print a DObject instance to screen
dcm.print
@example Print the DObject to the screen, but specify a 25 character value cutoff to produce better-looking results
dcm.print(:value_max => 25)
@example Print to a text file the elements that belong to a specific Sequence
dcm["3006,0020"].print(:file => "dicom.txt") | [
"Prints",
"all",
"child",
"elementals",
"of",
"this",
"particular",
"parent",
".",
"Information",
"such",
"as",
"tag",
"parent",
"-",
"child",
"relationship",
"name",
"vr",
"length",
"and",
"value",
"is",
"gathered",
"for",
"each",
"element",
"and",
"processed",
"to",
"produce",
"a",
"nicely",
"formatted",
"output",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/parent.rb#L502-L523 | train |
dicom/ruby-dicom | lib/dicom/parent.rb | DICOM.Parent.to_hash | def to_hash
as_hash = Hash.new
unless children?
if self.is_a?(DObject)
as_hash = {}
else
as_hash[(self.tag.private?) ? self.tag : self.send(DICOM.key_representation)] = nil
end
else
children.each do |child|
if child.tag.private?
hash_key = child.tag
elsif child.is_a?(Item)
hash_key = "Item #{child.index}"
else
hash_key = child.send(DICOM.key_representation)
end
if child.is_a?(Element)
as_hash[hash_key] = child.to_hash[hash_key]
else
as_hash[hash_key] = child.to_hash
end
end
end
return as_hash
end | ruby | def to_hash
as_hash = Hash.new
unless children?
if self.is_a?(DObject)
as_hash = {}
else
as_hash[(self.tag.private?) ? self.tag : self.send(DICOM.key_representation)] = nil
end
else
children.each do |child|
if child.tag.private?
hash_key = child.tag
elsif child.is_a?(Item)
hash_key = "Item #{child.index}"
else
hash_key = child.send(DICOM.key_representation)
end
if child.is_a?(Element)
as_hash[hash_key] = child.to_hash[hash_key]
else
as_hash[hash_key] = child.to_hash
end
end
end
return as_hash
end | [
"def",
"to_hash",
"as_hash",
"=",
"Hash",
".",
"new",
"unless",
"children?",
"if",
"self",
".",
"is_a?",
"(",
"DObject",
")",
"as_hash",
"=",
"{",
"}",
"else",
"as_hash",
"[",
"(",
"self",
".",
"tag",
".",
"private?",
")",
"?",
"self",
".",
"tag",
":",
"self",
".",
"send",
"(",
"DICOM",
".",
"key_representation",
")",
"]",
"=",
"nil",
"end",
"else",
"children",
".",
"each",
"do",
"|",
"child",
"|",
"if",
"child",
".",
"tag",
".",
"private?",
"hash_key",
"=",
"child",
".",
"tag",
"elsif",
"child",
".",
"is_a?",
"(",
"Item",
")",
"hash_key",
"=",
"\"Item #{child.index}\"",
"else",
"hash_key",
"=",
"child",
".",
"send",
"(",
"DICOM",
".",
"key_representation",
")",
"end",
"if",
"child",
".",
"is_a?",
"(",
"Element",
")",
"as_hash",
"[",
"hash_key",
"]",
"=",
"child",
".",
"to_hash",
"[",
"hash_key",
"]",
"else",
"as_hash",
"[",
"hash_key",
"]",
"=",
"child",
".",
"to_hash",
"end",
"end",
"end",
"return",
"as_hash",
"end"
]
| Builds a nested hash containing all children of this parent.
Keys are determined by the key_representation attribute, and data element values are used as values.
* For private elements, the tag is used for key instead of the key representation, as private tags lacks names.
* For child-less parents, the key_representation attribute is used as value.
@return [Hash] a nested hash containing key & value pairs of all children | [
"Builds",
"a",
"nested",
"hash",
"containing",
"all",
"children",
"of",
"this",
"parent",
"."
]
| 3ffcfe21edc8dcd31298f945781990789fc832ab | https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/parent.rb#L585-L610 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.