repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
libvips/ruby-vips | lib/vips/object.rb | Vips.Object.get_typeof_error | def get_typeof_error name
pspec = get_pspec name
raise Vips::Error unless pspec
pspec[:value][:value_type]
end | ruby | def get_typeof_error name
pspec = get_pspec name
raise Vips::Error unless pspec
pspec[:value][:value_type]
end | [
"def",
"get_typeof_error",
"name",
"pspec",
"=",
"get_pspec",
"name",
"raise",
"Vips",
"::",
"Error",
"unless",
"pspec",
"pspec",
"[",
":value",
"]",
"[",
":value_type",
"]",
"end"
] | return a gtype, raise an error on not found | [
"return",
"a",
"gtype",
"raise",
"an",
"error",
"on",
"not",
"found"
] | 8f14b1afda91e1078d7a5e6afe94098fef2f2da1 | https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/object.rb#L133-L138 | train |
libvips/ruby-vips | lib/vips/gvalue.rb | GObject.GValue.set | def set value
# GLib::logger.debug("GObject::GValue.set") {
# "value = #{value.inspect[0..50]}"
# }
gtype = self[:gtype]
fundamental = ::GObject::g_type_fundamental gtype
case gtype
when GBOOL_TYPE
::GObject::g_value_set_boolean self, (value ? 1 : 0)
when GINT_TYPE
::GObject::g_value_set_int self, value
when GUINT64_TYPE
::GObject::g_value_set_uint64 self, value
when GDOUBLE_TYPE
::GObject::g_value_set_double self, value
when GSTR_TYPE
::GObject::g_value_set_string self, value
when Vips::REFSTR_TYPE
::Vips::vips_value_set_ref_string self, value
when Vips::ARRAY_INT_TYPE
value = [value] unless value.is_a? Array
Vips::vips_value_set_array_int self, nil, value.length
ptr = Vips::vips_value_get_array_int self, nil
ptr.write_array_of_int32 value
when Vips::ARRAY_DOUBLE_TYPE
value = [value] unless value.is_a? Array
# this will allocate an array in the gvalue
Vips::vips_value_set_array_double self, nil, value.length
# pull the array out and fill it
ptr = Vips::vips_value_get_array_double self, nil
ptr.write_array_of_double value
when Vips::ARRAY_IMAGE_TYPE
value = [value] unless value.is_a? Array
Vips::vips_value_set_array_image self, value.length
ptr = Vips::vips_value_get_array_image self, nil
ptr.write_array_of_pointer value
# the gvalue needs a ref on each of the images
value.each {|image| ::GObject::g_object_ref image}
when Vips::BLOB_TYPE
len = value.bytesize
ptr = GLib::g_malloc len
Vips::vips_value_set_blob self, GLib::G_FREE, ptr, len
ptr.write_bytes value
else
case fundamental
when GFLAGS_TYPE
::GObject::g_value_set_flags self, value
when GENUM_TYPE
enum_value = GValue.from_nick(self[:gtype], value)
::GObject::g_value_set_enum self, enum_value
when GOBJECT_TYPE
::GObject::g_value_set_object self, value
else
raise Vips::Error, "unimplemented gtype for set: " +
"#{::GObject::g_type_name gtype} (#{gtype})"
end
end
end | ruby | def set value
# GLib::logger.debug("GObject::GValue.set") {
# "value = #{value.inspect[0..50]}"
# }
gtype = self[:gtype]
fundamental = ::GObject::g_type_fundamental gtype
case gtype
when GBOOL_TYPE
::GObject::g_value_set_boolean self, (value ? 1 : 0)
when GINT_TYPE
::GObject::g_value_set_int self, value
when GUINT64_TYPE
::GObject::g_value_set_uint64 self, value
when GDOUBLE_TYPE
::GObject::g_value_set_double self, value
when GSTR_TYPE
::GObject::g_value_set_string self, value
when Vips::REFSTR_TYPE
::Vips::vips_value_set_ref_string self, value
when Vips::ARRAY_INT_TYPE
value = [value] unless value.is_a? Array
Vips::vips_value_set_array_int self, nil, value.length
ptr = Vips::vips_value_get_array_int self, nil
ptr.write_array_of_int32 value
when Vips::ARRAY_DOUBLE_TYPE
value = [value] unless value.is_a? Array
# this will allocate an array in the gvalue
Vips::vips_value_set_array_double self, nil, value.length
# pull the array out and fill it
ptr = Vips::vips_value_get_array_double self, nil
ptr.write_array_of_double value
when Vips::ARRAY_IMAGE_TYPE
value = [value] unless value.is_a? Array
Vips::vips_value_set_array_image self, value.length
ptr = Vips::vips_value_get_array_image self, nil
ptr.write_array_of_pointer value
# the gvalue needs a ref on each of the images
value.each {|image| ::GObject::g_object_ref image}
when Vips::BLOB_TYPE
len = value.bytesize
ptr = GLib::g_malloc len
Vips::vips_value_set_blob self, GLib::G_FREE, ptr, len
ptr.write_bytes value
else
case fundamental
when GFLAGS_TYPE
::GObject::g_value_set_flags self, value
when GENUM_TYPE
enum_value = GValue.from_nick(self[:gtype], value)
::GObject::g_value_set_enum self, enum_value
when GOBJECT_TYPE
::GObject::g_value_set_object self, value
else
raise Vips::Error, "unimplemented gtype for set: " +
"#{::GObject::g_type_name gtype} (#{gtype})"
end
end
end | [
"def",
"set",
"value",
"# GLib::logger.debug(\"GObject::GValue.set\") {",
"# \"value = #{value.inspect[0..50]}\"",
"# }",
"gtype",
"=",
"self",
"[",
":gtype",
"]",
"fundamental",
"=",
"::",
"GObject",
"::",
"g_type_fundamental",
"gtype",
"case",
"gtype",
"when",
"GBOOL_TYPE",
"::",
"GObject",
"::",
"g_value_set_boolean",
"self",
",",
"(",
"value",
"?",
"1",
":",
"0",
")",
"when",
"GINT_TYPE",
"::",
"GObject",
"::",
"g_value_set_int",
"self",
",",
"value",
"when",
"GUINT64_TYPE",
"::",
"GObject",
"::",
"g_value_set_uint64",
"self",
",",
"value",
"when",
"GDOUBLE_TYPE",
"::",
"GObject",
"::",
"g_value_set_double",
"self",
",",
"value",
"when",
"GSTR_TYPE",
"::",
"GObject",
"::",
"g_value_set_string",
"self",
",",
"value",
"when",
"Vips",
"::",
"REFSTR_TYPE",
"::",
"Vips",
"::",
"vips_value_set_ref_string",
"self",
",",
"value",
"when",
"Vips",
"::",
"ARRAY_INT_TYPE",
"value",
"=",
"[",
"value",
"]",
"unless",
"value",
".",
"is_a?",
"Array",
"Vips",
"::",
"vips_value_set_array_int",
"self",
",",
"nil",
",",
"value",
".",
"length",
"ptr",
"=",
"Vips",
"::",
"vips_value_get_array_int",
"self",
",",
"nil",
"ptr",
".",
"write_array_of_int32",
"value",
"when",
"Vips",
"::",
"ARRAY_DOUBLE_TYPE",
"value",
"=",
"[",
"value",
"]",
"unless",
"value",
".",
"is_a?",
"Array",
"# this will allocate an array in the gvalue",
"Vips",
"::",
"vips_value_set_array_double",
"self",
",",
"nil",
",",
"value",
".",
"length",
"# pull the array out and fill it",
"ptr",
"=",
"Vips",
"::",
"vips_value_get_array_double",
"self",
",",
"nil",
"ptr",
".",
"write_array_of_double",
"value",
"when",
"Vips",
"::",
"ARRAY_IMAGE_TYPE",
"value",
"=",
"[",
"value",
"]",
"unless",
"value",
".",
"is_a?",
"Array",
"Vips",
"::",
"vips_value_set_array_image",
"self",
",",
"value",
".",
"length",
"ptr",
"=",
"Vips",
"::",
"vips_value_get_array_image",
"self",
",",
"nil",
"ptr",
".",
"write_array_of_pointer",
"value",
"# the gvalue needs a ref on each of the images",
"value",
".",
"each",
"{",
"|",
"image",
"|",
"::",
"GObject",
"::",
"g_object_ref",
"image",
"}",
"when",
"Vips",
"::",
"BLOB_TYPE",
"len",
"=",
"value",
".",
"bytesize",
"ptr",
"=",
"GLib",
"::",
"g_malloc",
"len",
"Vips",
"::",
"vips_value_set_blob",
"self",
",",
"GLib",
"::",
"G_FREE",
",",
"ptr",
",",
"len",
"ptr",
".",
"write_bytes",
"value",
"else",
"case",
"fundamental",
"when",
"GFLAGS_TYPE",
"::",
"GObject",
"::",
"g_value_set_flags",
"self",
",",
"value",
"when",
"GENUM_TYPE",
"enum_value",
"=",
"GValue",
".",
"from_nick",
"(",
"self",
"[",
":gtype",
"]",
",",
"value",
")",
"::",
"GObject",
"::",
"g_value_set_enum",
"self",
",",
"enum_value",
"when",
"GOBJECT_TYPE",
"::",
"GObject",
"::",
"g_value_set_object",
"self",
",",
"value",
"else",
"raise",
"Vips",
"::",
"Error",
",",
"\"unimplemented gtype for set: \"",
"+",
"\"#{::GObject::g_type_name gtype} (#{gtype})\"",
"end",
"end",
"end"
] | Set the value of a GValue. The value is converted to the type of the
GValue, if possible.
@param value [Any] The value to set | [
"Set",
"the",
"value",
"of",
"a",
"GValue",
".",
"The",
"value",
"is",
"converted",
"to",
"the",
"type",
"of",
"the",
"GValue",
"if",
"possible",
"."
] | 8f14b1afda91e1078d7a5e6afe94098fef2f2da1 | https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/gvalue.rb#L84-L163 | train |
libvips/ruby-vips | lib/vips/gvalue.rb | GObject.GValue.get | def get
gtype = self[:gtype]
fundamental = ::GObject::g_type_fundamental gtype
result = nil
case gtype
when GBOOL_TYPE
result = ::GObject::g_value_get_boolean(self) != 0 ? true : false
when GINT_TYPE
result = ::GObject::g_value_get_int self
when GUINT64_TYPE
result = ::GObject::g_value_get_uint64 self
when GDOUBLE_TYPE
result = ::GObject::g_value_get_double self
when GSTR_TYPE
result = ::GObject::g_value_get_string self
when Vips::REFSTR_TYPE
len = Vips::SizeStruct.new
result = ::Vips::vips_value_get_ref_string self, len
when Vips::ARRAY_INT_TYPE
len = Vips::IntStruct.new
array = Vips::vips_value_get_array_int self, len
result = array.get_array_of_int32 0, len[:value]
when Vips::ARRAY_DOUBLE_TYPE
len = Vips::IntStruct.new
array = Vips::vips_value_get_array_double self, len
result = array.get_array_of_double 0, len[:value]
when Vips::ARRAY_IMAGE_TYPE
len = Vips::IntStruct.new
array = Vips::vips_value_get_array_image self, len
result = array.get_array_of_pointer 0, len[:value]
result.map! do |pointer|
::GObject::g_object_ref pointer
Vips::Image.new pointer
end
when Vips::BLOB_TYPE
len = Vips::SizeStruct.new
array = Vips::vips_value_get_blob self, len
result = array.get_bytes 0, len[:value]
else
case fundamental
when GFLAGS_TYPE
result = ::GObject::g_value_get_flags self
when GENUM_TYPE
enum_value = ::GObject::g_value_get_enum(self)
result = GValue.to_nick self[:gtype], enum_value
when GOBJECT_TYPE
obj = ::GObject::g_value_get_object self
# g_value_get_object() does not add a ref ... we need to add
# one to match the unref in gobject release
::GObject::g_object_ref obj
result = Vips::Image.new obj
else
raise Vips::Error, "unimplemented gtype for get: " +
"#{::GObject::g_type_name gtype} (#{gtype})"
end
end
# GLib::logger.debug("GObject::GValue.get") {
# "result = #{result.inspect[0..50]}"
# }
return result
end | ruby | def get
gtype = self[:gtype]
fundamental = ::GObject::g_type_fundamental gtype
result = nil
case gtype
when GBOOL_TYPE
result = ::GObject::g_value_get_boolean(self) != 0 ? true : false
when GINT_TYPE
result = ::GObject::g_value_get_int self
when GUINT64_TYPE
result = ::GObject::g_value_get_uint64 self
when GDOUBLE_TYPE
result = ::GObject::g_value_get_double self
when GSTR_TYPE
result = ::GObject::g_value_get_string self
when Vips::REFSTR_TYPE
len = Vips::SizeStruct.new
result = ::Vips::vips_value_get_ref_string self, len
when Vips::ARRAY_INT_TYPE
len = Vips::IntStruct.new
array = Vips::vips_value_get_array_int self, len
result = array.get_array_of_int32 0, len[:value]
when Vips::ARRAY_DOUBLE_TYPE
len = Vips::IntStruct.new
array = Vips::vips_value_get_array_double self, len
result = array.get_array_of_double 0, len[:value]
when Vips::ARRAY_IMAGE_TYPE
len = Vips::IntStruct.new
array = Vips::vips_value_get_array_image self, len
result = array.get_array_of_pointer 0, len[:value]
result.map! do |pointer|
::GObject::g_object_ref pointer
Vips::Image.new pointer
end
when Vips::BLOB_TYPE
len = Vips::SizeStruct.new
array = Vips::vips_value_get_blob self, len
result = array.get_bytes 0, len[:value]
else
case fundamental
when GFLAGS_TYPE
result = ::GObject::g_value_get_flags self
when GENUM_TYPE
enum_value = ::GObject::g_value_get_enum(self)
result = GValue.to_nick self[:gtype], enum_value
when GOBJECT_TYPE
obj = ::GObject::g_value_get_object self
# g_value_get_object() does not add a ref ... we need to add
# one to match the unref in gobject release
::GObject::g_object_ref obj
result = Vips::Image.new obj
else
raise Vips::Error, "unimplemented gtype for get: " +
"#{::GObject::g_type_name gtype} (#{gtype})"
end
end
# GLib::logger.debug("GObject::GValue.get") {
# "result = #{result.inspect[0..50]}"
# }
return result
end | [
"def",
"get",
"gtype",
"=",
"self",
"[",
":gtype",
"]",
"fundamental",
"=",
"::",
"GObject",
"::",
"g_type_fundamental",
"gtype",
"result",
"=",
"nil",
"case",
"gtype",
"when",
"GBOOL_TYPE",
"result",
"=",
"::",
"GObject",
"::",
"g_value_get_boolean",
"(",
"self",
")",
"!=",
"0",
"?",
"true",
":",
"false",
"when",
"GINT_TYPE",
"result",
"=",
"::",
"GObject",
"::",
"g_value_get_int",
"self",
"when",
"GUINT64_TYPE",
"result",
"=",
"::",
"GObject",
"::",
"g_value_get_uint64",
"self",
"when",
"GDOUBLE_TYPE",
"result",
"=",
"::",
"GObject",
"::",
"g_value_get_double",
"self",
"when",
"GSTR_TYPE",
"result",
"=",
"::",
"GObject",
"::",
"g_value_get_string",
"self",
"when",
"Vips",
"::",
"REFSTR_TYPE",
"len",
"=",
"Vips",
"::",
"SizeStruct",
".",
"new",
"result",
"=",
"::",
"Vips",
"::",
"vips_value_get_ref_string",
"self",
",",
"len",
"when",
"Vips",
"::",
"ARRAY_INT_TYPE",
"len",
"=",
"Vips",
"::",
"IntStruct",
".",
"new",
"array",
"=",
"Vips",
"::",
"vips_value_get_array_int",
"self",
",",
"len",
"result",
"=",
"array",
".",
"get_array_of_int32",
"0",
",",
"len",
"[",
":value",
"]",
"when",
"Vips",
"::",
"ARRAY_DOUBLE_TYPE",
"len",
"=",
"Vips",
"::",
"IntStruct",
".",
"new",
"array",
"=",
"Vips",
"::",
"vips_value_get_array_double",
"self",
",",
"len",
"result",
"=",
"array",
".",
"get_array_of_double",
"0",
",",
"len",
"[",
":value",
"]",
"when",
"Vips",
"::",
"ARRAY_IMAGE_TYPE",
"len",
"=",
"Vips",
"::",
"IntStruct",
".",
"new",
"array",
"=",
"Vips",
"::",
"vips_value_get_array_image",
"self",
",",
"len",
"result",
"=",
"array",
".",
"get_array_of_pointer",
"0",
",",
"len",
"[",
":value",
"]",
"result",
".",
"map!",
"do",
"|",
"pointer",
"|",
"::",
"GObject",
"::",
"g_object_ref",
"pointer",
"Vips",
"::",
"Image",
".",
"new",
"pointer",
"end",
"when",
"Vips",
"::",
"BLOB_TYPE",
"len",
"=",
"Vips",
"::",
"SizeStruct",
".",
"new",
"array",
"=",
"Vips",
"::",
"vips_value_get_blob",
"self",
",",
"len",
"result",
"=",
"array",
".",
"get_bytes",
"0",
",",
"len",
"[",
":value",
"]",
"else",
"case",
"fundamental",
"when",
"GFLAGS_TYPE",
"result",
"=",
"::",
"GObject",
"::",
"g_value_get_flags",
"self",
"when",
"GENUM_TYPE",
"enum_value",
"=",
"::",
"GObject",
"::",
"g_value_get_enum",
"(",
"self",
")",
"result",
"=",
"GValue",
".",
"to_nick",
"self",
"[",
":gtype",
"]",
",",
"enum_value",
"when",
"GOBJECT_TYPE",
"obj",
"=",
"::",
"GObject",
"::",
"g_value_get_object",
"self",
"# g_value_get_object() does not add a ref ... we need to add",
"# one to match the unref in gobject release",
"::",
"GObject",
"::",
"g_object_ref",
"obj",
"result",
"=",
"Vips",
"::",
"Image",
".",
"new",
"obj",
"else",
"raise",
"Vips",
"::",
"Error",
",",
"\"unimplemented gtype for get: \"",
"+",
"\"#{::GObject::g_type_name gtype} (#{gtype})\"",
"end",
"end",
"# GLib::logger.debug(\"GObject::GValue.get\") {",
"# \"result = #{result.inspect[0..50]}\"",
"# }",
"return",
"result",
"end"
] | Get the value of a GValue. The value is converted to a Ruby type in
the obvious way.
@return [Any] the value held by the GValue | [
"Get",
"the",
"value",
"of",
"a",
"GValue",
".",
"The",
"value",
"is",
"converted",
"to",
"a",
"Ruby",
"type",
"in",
"the",
"obvious",
"way",
"."
] | 8f14b1afda91e1078d7a5e6afe94098fef2f2da1 | https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/gvalue.rb#L169-L247 | train |
pcreux/csv-importer | lib/csv_importer/runner.rb | CSVImporter.Runner.call | def call
if rows.empty?
report.done!
return report
end
report.in_progress!
persist_rows!
report.done!
report
rescue ImportAborted
report.aborted!
report
end | ruby | def call
if rows.empty?
report.done!
return report
end
report.in_progress!
persist_rows!
report.done!
report
rescue ImportAborted
report.aborted!
report
end | [
"def",
"call",
"if",
"rows",
".",
"empty?",
"report",
".",
"done!",
"return",
"report",
"end",
"report",
".",
"in_progress!",
"persist_rows!",
"report",
".",
"done!",
"report",
"rescue",
"ImportAborted",
"report",
".",
"aborted!",
"report",
"end"
] | Persist the rows' model and return a `Report` | [
"Persist",
"the",
"rows",
"model",
"and",
"return",
"a",
"Report"
] | 942070b4b22eed0b36989b98fe4ebe9104b9f665 | https://github.com/pcreux/csv-importer/blob/942070b4b22eed0b36989b98fe4ebe9104b9f665/lib/csv_importer/runner.rb#L21-L36 | train |
pcreux/csv-importer | lib/csv_importer/csv_reader.rb | CSVImporter.CSVReader.sanitize_cells | def sanitize_cells(rows)
rows.map do |cells|
cells.map do |cell|
cell ? cell.strip : ""
end
end
end | ruby | def sanitize_cells(rows)
rows.map do |cells|
cells.map do |cell|
cell ? cell.strip : ""
end
end
end | [
"def",
"sanitize_cells",
"(",
"rows",
")",
"rows",
".",
"map",
"do",
"|",
"cells",
"|",
"cells",
".",
"map",
"do",
"|",
"cell",
"|",
"cell",
"?",
"cell",
".",
"strip",
":",
"\"\"",
"end",
"end",
"end"
] | Remove trailing white spaces and ensure we always return a string | [
"Remove",
"trailing",
"white",
"spaces",
"and",
"ensure",
"we",
"always",
"return",
"a",
"string"
] | 942070b4b22eed0b36989b98fe4ebe9104b9f665 | https://github.com/pcreux/csv-importer/blob/942070b4b22eed0b36989b98fe4ebe9104b9f665/lib/csv_importer/csv_reader.rb#L60-L66 | train |
pcreux/csv-importer | lib/csv_importer/row.rb | CSVImporter.Row.model | def model
@model ||= begin
model = find_or_build_model
set_attributes(model)
after_build_blocks.each { |block| instance_exec(model, &block) }
model
end
end | ruby | def model
@model ||= begin
model = find_or_build_model
set_attributes(model)
after_build_blocks.each { |block| instance_exec(model, &block) }
model
end
end | [
"def",
"model",
"@model",
"||=",
"begin",
"model",
"=",
"find_or_build_model",
"set_attributes",
"(",
"model",
")",
"after_build_blocks",
".",
"each",
"{",
"|",
"block",
"|",
"instance_exec",
"(",
"model",
",",
"block",
")",
"}",
"model",
"end",
"end"
] | The model to be persisted | [
"The",
"model",
"to",
"be",
"persisted"
] | 942070b4b22eed0b36989b98fe4ebe9104b9f665 | https://github.com/pcreux/csv-importer/blob/942070b4b22eed0b36989b98fe4ebe9104b9f665/lib/csv_importer/row.rb#L18-L27 | train |
pcreux/csv-importer | lib/csv_importer/row.rb | CSVImporter.Row.set_attribute | def set_attribute(model, column, csv_value)
column_definition = column.definition
if column_definition.to && column_definition.to.is_a?(Proc)
to_proc = column_definition.to
case to_proc.arity
when 1 # to: ->(email) { email.downcase }
model.public_send("#{column_definition.name}=", to_proc.call(csv_value))
when 2 # to: ->(published, post) { post.published_at = Time.now if published == "true" }
to_proc.call(csv_value, model)
when 3 # to: ->(field_value, post, column) { post.hash_field[column.name] = field_value }
to_proc.call(csv_value, model, column)
else
raise ArgumentError, "`to` proc can only have 1, 2 or 3 arguments"
end
else
attribute = column_definition.attribute
model.public_send("#{attribute}=", csv_value)
end
model
end | ruby | def set_attribute(model, column, csv_value)
column_definition = column.definition
if column_definition.to && column_definition.to.is_a?(Proc)
to_proc = column_definition.to
case to_proc.arity
when 1 # to: ->(email) { email.downcase }
model.public_send("#{column_definition.name}=", to_proc.call(csv_value))
when 2 # to: ->(published, post) { post.published_at = Time.now if published == "true" }
to_proc.call(csv_value, model)
when 3 # to: ->(field_value, post, column) { post.hash_field[column.name] = field_value }
to_proc.call(csv_value, model, column)
else
raise ArgumentError, "`to` proc can only have 1, 2 or 3 arguments"
end
else
attribute = column_definition.attribute
model.public_send("#{attribute}=", csv_value)
end
model
end | [
"def",
"set_attribute",
"(",
"model",
",",
"column",
",",
"csv_value",
")",
"column_definition",
"=",
"column",
".",
"definition",
"if",
"column_definition",
".",
"to",
"&&",
"column_definition",
".",
"to",
".",
"is_a?",
"(",
"Proc",
")",
"to_proc",
"=",
"column_definition",
".",
"to",
"case",
"to_proc",
".",
"arity",
"when",
"1",
"# to: ->(email) { email.downcase }",
"model",
".",
"public_send",
"(",
"\"#{column_definition.name}=\"",
",",
"to_proc",
".",
"call",
"(",
"csv_value",
")",
")",
"when",
"2",
"# to: ->(published, post) { post.published_at = Time.now if published == \"true\" }",
"to_proc",
".",
"call",
"(",
"csv_value",
",",
"model",
")",
"when",
"3",
"# to: ->(field_value, post, column) { post.hash_field[column.name] = field_value }",
"to_proc",
".",
"call",
"(",
"csv_value",
",",
"model",
",",
"column",
")",
"else",
"raise",
"ArgumentError",
",",
"\"`to` proc can only have 1, 2 or 3 arguments\"",
"end",
"else",
"attribute",
"=",
"column_definition",
".",
"attribute",
"model",
".",
"public_send",
"(",
"\"#{attribute}=\"",
",",
"csv_value",
")",
"end",
"model",
"end"
] | Set the attribute using the column_definition and the csv_value | [
"Set",
"the",
"attribute",
"using",
"the",
"column_definition",
"and",
"the",
"csv_value"
] | 942070b4b22eed0b36989b98fe4ebe9104b9f665 | https://github.com/pcreux/csv-importer/blob/942070b4b22eed0b36989b98fe4ebe9104b9f665/lib/csv_importer/row.rb#L53-L74 | train |
pcreux/csv-importer | lib/csv_importer/row.rb | CSVImporter.Row.errors | def errors
Hash[
model.errors.map do |attribute, errors|
if column_name = header.column_name_for_model_attribute(attribute)
[column_name, errors]
else
[attribute, errors]
end
end
]
end | ruby | def errors
Hash[
model.errors.map do |attribute, errors|
if column_name = header.column_name_for_model_attribute(attribute)
[column_name, errors]
else
[attribute, errors]
end
end
]
end | [
"def",
"errors",
"Hash",
"[",
"model",
".",
"errors",
".",
"map",
"do",
"|",
"attribute",
",",
"errors",
"|",
"if",
"column_name",
"=",
"header",
".",
"column_name_for_model_attribute",
"(",
"attribute",
")",
"[",
"column_name",
",",
"errors",
"]",
"else",
"[",
"attribute",
",",
"errors",
"]",
"end",
"end",
"]",
"end"
] | Error from the model mapped back to the CSV header if we can | [
"Error",
"from",
"the",
"model",
"mapped",
"back",
"to",
"the",
"CSV",
"header",
"if",
"we",
"can"
] | 942070b4b22eed0b36989b98fe4ebe9104b9f665 | https://github.com/pcreux/csv-importer/blob/942070b4b22eed0b36989b98fe4ebe9104b9f665/lib/csv_importer/row.rb#L77-L87 | train |
pcreux/csv-importer | lib/csv_importer/column_definition.rb | CSVImporter.ColumnDefinition.match? | def match?(column_name, search_query=(as || name))
return false if column_name.nil?
downcased_column_name = column_name.downcase
underscored_column_name = downcased_column_name.gsub(/\s+/, '_')
case search_query
when Symbol
underscored_column_name == search_query.to_s
when String
downcased_column_name == search_query.downcase
when Regexp
column_name =~ search_query
when Array
search_query.any? { |query| match?(column_name, query) }
else
raise Error, "Invalid `as`. Should be a Symbol, String, Regexp or Array - was #{as.inspect}"
end
end | ruby | def match?(column_name, search_query=(as || name))
return false if column_name.nil?
downcased_column_name = column_name.downcase
underscored_column_name = downcased_column_name.gsub(/\s+/, '_')
case search_query
when Symbol
underscored_column_name == search_query.to_s
when String
downcased_column_name == search_query.downcase
when Regexp
column_name =~ search_query
when Array
search_query.any? { |query| match?(column_name, query) }
else
raise Error, "Invalid `as`. Should be a Symbol, String, Regexp or Array - was #{as.inspect}"
end
end | [
"def",
"match?",
"(",
"column_name",
",",
"search_query",
"=",
"(",
"as",
"||",
"name",
")",
")",
"return",
"false",
"if",
"column_name",
".",
"nil?",
"downcased_column_name",
"=",
"column_name",
".",
"downcase",
"underscored_column_name",
"=",
"downcased_column_name",
".",
"gsub",
"(",
"/",
"\\s",
"/",
",",
"'_'",
")",
"case",
"search_query",
"when",
"Symbol",
"underscored_column_name",
"==",
"search_query",
".",
"to_s",
"when",
"String",
"downcased_column_name",
"==",
"search_query",
".",
"downcase",
"when",
"Regexp",
"column_name",
"=~",
"search_query",
"when",
"Array",
"search_query",
".",
"any?",
"{",
"|",
"query",
"|",
"match?",
"(",
"column_name",
",",
"query",
")",
"}",
"else",
"raise",
"Error",
",",
"\"Invalid `as`. Should be a Symbol, String, Regexp or Array - was #{as.inspect}\"",
"end",
"end"
] | Return true if column definition matches the column name passed in. | [
"Return",
"true",
"if",
"column",
"definition",
"matches",
"the",
"column",
"name",
"passed",
"in",
"."
] | 942070b4b22eed0b36989b98fe4ebe9104b9f665 | https://github.com/pcreux/csv-importer/blob/942070b4b22eed0b36989b98fe4ebe9104b9f665/lib/csv_importer/column_definition.rb#L44-L62 | train |
piotrmurach/tty | lib/tty/templater.rb | TTY.Templater.generate | def generate(template_options, color_option)
templates.each do |src, dst|
source = @source_path.join(src)
destination = @target_path.join(dst).to_s
next unless ::File.exist?(source)
within_root_path do
TTY::File.copy_file(source, destination,
{ context: template_options }.merge(color_option))
end
end
end | ruby | def generate(template_options, color_option)
templates.each do |src, dst|
source = @source_path.join(src)
destination = @target_path.join(dst).to_s
next unless ::File.exist?(source)
within_root_path do
TTY::File.copy_file(source, destination,
{ context: template_options }.merge(color_option))
end
end
end | [
"def",
"generate",
"(",
"template_options",
",",
"color_option",
")",
"templates",
".",
"each",
"do",
"|",
"src",
",",
"dst",
"|",
"source",
"=",
"@source_path",
".",
"join",
"(",
"src",
")",
"destination",
"=",
"@target_path",
".",
"join",
"(",
"dst",
")",
".",
"to_s",
"next",
"unless",
"::",
"File",
".",
"exist?",
"(",
"source",
")",
"within_root_path",
"do",
"TTY",
"::",
"File",
".",
"copy_file",
"(",
"source",
",",
"destination",
",",
"{",
"context",
":",
"template_options",
"}",
".",
"merge",
"(",
"color_option",
")",
")",
"end",
"end",
"end"
] | Process templates by injecting vars and moving to location
@api private | [
"Process",
"templates",
"by",
"injecting",
"vars",
"and",
"moving",
"to",
"location"
] | 872fa26d321d95b48807569f25cb1633f6fecd17 | https://github.com/piotrmurach/tty/blob/872fa26d321d95b48807569f25cb1633f6fecd17/lib/tty/templater.rb#L41-L51 | train |
piotrmurach/tty | lib/tty/plugins.rb | TTY.Plugins.load_from | def load_from(gemspec_path, pattern)
Gem.refresh
spec = Gem::Specification.load(gemspec_path)
dependencies = spec.runtime_dependencies.concat(spec.development_dependencies)
dependencies.each do |gem|
gem_name = gem.name[pattern]
next if gem_name.to_s.empty?
register(gem_name, Plugin.new(gem_name, gem))
end
self
end | ruby | def load_from(gemspec_path, pattern)
Gem.refresh
spec = Gem::Specification.load(gemspec_path)
dependencies = spec.runtime_dependencies.concat(spec.development_dependencies)
dependencies.each do |gem|
gem_name = gem.name[pattern]
next if gem_name.to_s.empty?
register(gem_name, Plugin.new(gem_name, gem))
end
self
end | [
"def",
"load_from",
"(",
"gemspec_path",
",",
"pattern",
")",
"Gem",
".",
"refresh",
"spec",
"=",
"Gem",
"::",
"Specification",
".",
"load",
"(",
"gemspec_path",
")",
"dependencies",
"=",
"spec",
".",
"runtime_dependencies",
".",
"concat",
"(",
"spec",
".",
"development_dependencies",
")",
"dependencies",
".",
"each",
"do",
"|",
"gem",
"|",
"gem_name",
"=",
"gem",
".",
"name",
"[",
"pattern",
"]",
"next",
"if",
"gem_name",
".",
"to_s",
".",
"empty?",
"register",
"(",
"gem_name",
",",
"Plugin",
".",
"new",
"(",
"gem_name",
",",
"gem",
")",
")",
"end",
"self",
"end"
] | Loads gemspec from a file and registers gems matching pattern.
@param [String|Pathname] gemspec_path
the path to gemspec
@param [Regex] pattern
the pattern to match gems by
@example
plugins.load_from('foo.gemspec', /tty-(.*)/)
@api public | [
"Loads",
"gemspec",
"from",
"a",
"file",
"and",
"registers",
"gems",
"matching",
"pattern",
"."
] | 872fa26d321d95b48807569f25cb1633f6fecd17 | https://github.com/piotrmurach/tty/blob/872fa26d321d95b48807569f25cb1633f6fecd17/lib/tty/plugins.rb#L55-L65 | train |
piotrmurach/tty | lib/tty/plugins.rb | TTY.Plugins.names | def names
plugins.reduce({}) do |hash, plugin|
hash[plugin.name] = plugin
hash
end
end | ruby | def names
plugins.reduce({}) do |hash, plugin|
hash[plugin.name] = plugin
hash
end
end | [
"def",
"names",
"plugins",
".",
"reduce",
"(",
"{",
"}",
")",
"do",
"|",
"hash",
",",
"plugin",
"|",
"hash",
"[",
"plugin",
".",
"name",
"]",
"=",
"plugin",
"hash",
"end",
"end"
] | Return a list of all plugin names as strings
@api public | [
"Return",
"a",
"list",
"of",
"all",
"plugin",
"names",
"as",
"strings"
] | 872fa26d321d95b48807569f25cb1633f6fecd17 | https://github.com/piotrmurach/tty/blob/872fa26d321d95b48807569f25cb1633f6fecd17/lib/tty/plugins.rb#L80-L85 | train |
piotrmurach/tty | lib/tty/path_helpers.rb | TTY.PathHelpers.relative_path_from | def relative_path_from(root_path, path)
project_path = Pathname.new(path)
return project_path if project_path.relative?
project_path.relative_path_from(root_path)
end | ruby | def relative_path_from(root_path, path)
project_path = Pathname.new(path)
return project_path if project_path.relative?
project_path.relative_path_from(root_path)
end | [
"def",
"relative_path_from",
"(",
"root_path",
",",
"path",
")",
"project_path",
"=",
"Pathname",
".",
"new",
"(",
"path",
")",
"return",
"project_path",
"if",
"project_path",
".",
"relative?",
"project_path",
".",
"relative_path_from",
"(",
"root_path",
")",
"end"
] | Extract a relative path for the app
@api private | [
"Extract",
"a",
"relative",
"path",
"for",
"the",
"app"
] | 872fa26d321d95b48807569f25cb1633f6fecd17 | https://github.com/piotrmurach/tty/blob/872fa26d321d95b48807569f25cb1633f6fecd17/lib/tty/path_helpers.rb#L31-L35 | train |
heroku/databasedotcom | lib/databasedotcom/client.rb | Databasedotcom.Client.authenticate | def authenticate(options = nil)
if user_and_pass?(options)
req = https_request(self.host)
user = self.username || options[:username]
pass = self.password || options[:password]
path = encode_path_with_params('/services/oauth2/token', :grant_type => 'password', :client_id => self.client_id, :client_secret => self.client_secret, :username => user, :password => pass)
log_request("https://#{self.host}/#{path}")
result = req.post(path, "")
log_response(result)
raise SalesForceError.new(result) unless result.is_a?(Net::HTTPOK)
self.username = user
self.password = pass
parse_auth_response(result.body)
elsif options.is_a?(Hash)
if options.has_key?("provider")
parse_user_id_and_org_id_from_identity_url(options["uid"])
self.instance_url = options["credentials"]["instance_url"]
self.oauth_token = options["credentials"]["token"]
self.refresh_token = options["credentials"]["refresh_token"]
else
raise ArgumentError unless options.has_key?(:token) && options.has_key?(:instance_url)
self.instance_url = options[:instance_url]
self.oauth_token = options[:token]
self.refresh_token = options[:refresh_token]
end
end
self.version = "22.0" unless self.version
self.oauth_token
end | ruby | def authenticate(options = nil)
if user_and_pass?(options)
req = https_request(self.host)
user = self.username || options[:username]
pass = self.password || options[:password]
path = encode_path_with_params('/services/oauth2/token', :grant_type => 'password', :client_id => self.client_id, :client_secret => self.client_secret, :username => user, :password => pass)
log_request("https://#{self.host}/#{path}")
result = req.post(path, "")
log_response(result)
raise SalesForceError.new(result) unless result.is_a?(Net::HTTPOK)
self.username = user
self.password = pass
parse_auth_response(result.body)
elsif options.is_a?(Hash)
if options.has_key?("provider")
parse_user_id_and_org_id_from_identity_url(options["uid"])
self.instance_url = options["credentials"]["instance_url"]
self.oauth_token = options["credentials"]["token"]
self.refresh_token = options["credentials"]["refresh_token"]
else
raise ArgumentError unless options.has_key?(:token) && options.has_key?(:instance_url)
self.instance_url = options[:instance_url]
self.oauth_token = options[:token]
self.refresh_token = options[:refresh_token]
end
end
self.version = "22.0" unless self.version
self.oauth_token
end | [
"def",
"authenticate",
"(",
"options",
"=",
"nil",
")",
"if",
"user_and_pass?",
"(",
"options",
")",
"req",
"=",
"https_request",
"(",
"self",
".",
"host",
")",
"user",
"=",
"self",
".",
"username",
"||",
"options",
"[",
":username",
"]",
"pass",
"=",
"self",
".",
"password",
"||",
"options",
"[",
":password",
"]",
"path",
"=",
"encode_path_with_params",
"(",
"'/services/oauth2/token'",
",",
":grant_type",
"=>",
"'password'",
",",
":client_id",
"=>",
"self",
".",
"client_id",
",",
":client_secret",
"=>",
"self",
".",
"client_secret",
",",
":username",
"=>",
"user",
",",
":password",
"=>",
"pass",
")",
"log_request",
"(",
"\"https://#{self.host}/#{path}\"",
")",
"result",
"=",
"req",
".",
"post",
"(",
"path",
",",
"\"\"",
")",
"log_response",
"(",
"result",
")",
"raise",
"SalesForceError",
".",
"new",
"(",
"result",
")",
"unless",
"result",
".",
"is_a?",
"(",
"Net",
"::",
"HTTPOK",
")",
"self",
".",
"username",
"=",
"user",
"self",
".",
"password",
"=",
"pass",
"parse_auth_response",
"(",
"result",
".",
"body",
")",
"elsif",
"options",
".",
"is_a?",
"(",
"Hash",
")",
"if",
"options",
".",
"has_key?",
"(",
"\"provider\"",
")",
"parse_user_id_and_org_id_from_identity_url",
"(",
"options",
"[",
"\"uid\"",
"]",
")",
"self",
".",
"instance_url",
"=",
"options",
"[",
"\"credentials\"",
"]",
"[",
"\"instance_url\"",
"]",
"self",
".",
"oauth_token",
"=",
"options",
"[",
"\"credentials\"",
"]",
"[",
"\"token\"",
"]",
"self",
".",
"refresh_token",
"=",
"options",
"[",
"\"credentials\"",
"]",
"[",
"\"refresh_token\"",
"]",
"else",
"raise",
"ArgumentError",
"unless",
"options",
".",
"has_key?",
"(",
":token",
")",
"&&",
"options",
".",
"has_key?",
"(",
":instance_url",
")",
"self",
".",
"instance_url",
"=",
"options",
"[",
":instance_url",
"]",
"self",
".",
"oauth_token",
"=",
"options",
"[",
":token",
"]",
"self",
".",
"refresh_token",
"=",
"options",
"[",
":refresh_token",
"]",
"end",
"end",
"self",
".",
"version",
"=",
"\"22.0\"",
"unless",
"self",
".",
"version",
"self",
".",
"oauth_token",
"end"
] | Returns a new client object. _options_ can be one of the following
* A String containing the name of a YAML file formatted like:
---
client_id: <your_salesforce_client_id>
client_secret: <your_salesforce_client_secret>
host: login.salesforce.com
debugging: true
version: 23.0
sobject_module: My::Module
ca_file: some/ca/file.cert
verify_mode: OpenSSL::SSL::VERIFY_PEER
* A Hash containing the following keys:
client_id
client_secret
host
debugging
version
sobject_module
ca_file
verify_mode
If the environment variables DATABASEDOTCOM_CLIENT_ID, DATABASEDOTCOM_CLIENT_SECRET, DATABASEDOTCOM_HOST,
DATABASEDOTCOM_DEBUGGING, DATABASEDOTCOM_VERSION, DATABASEDOTCOM_SOBJECT_MODULE, DATABASEDOTCOM_CA_FILE, and/or
DATABASEDOTCOM_VERIFY_MODE are present, they override any other values provided
Authenticate to the Force.com API. _options_ is a Hash, interpreted as follows:
* If _options_ contains the keys <tt>:username</tt> and <tt>:password</tt>, those credentials are used to authenticate. In this case, the value of <tt>:password</tt> may need to include a concatenated security token, if required by your Salesforce org
* If _options_ contains the key <tt>:provider</tt>, it is assumed to be the hash returned by Omniauth from a successful web-based OAuth2 authentication
* If _options_ contains the keys <tt>:token</tt> and <tt>:instance_url</tt>, those are assumed to be a valid OAuth2 token and instance URL for a Salesforce account, obtained from an external source. _options_ may also optionally contain the key <tt>:refresh_token</tt>
Raises SalesForceError if an error occurs | [
"Returns",
"a",
"new",
"client",
"object",
".",
"_options_",
"can",
"be",
"one",
"of",
"the",
"following"
] | a9173ff9c47bf2321a6959c9616d00cb6d8e93be | https://github.com/heroku/databasedotcom/blob/a9173ff9c47bf2321a6959c9616d00cb6d8e93be/lib/databasedotcom/client.rb#L103-L133 | train |
heroku/databasedotcom | lib/databasedotcom/client.rb | Databasedotcom.Client.list_sobjects | def list_sobjects
result = http_get("/services/data/v#{self.version}/sobjects")
if result.is_a?(Net::HTTPOK)
JSON.parse(result.body)["sobjects"].collect { |sobject| sobject["name"] }
elsif result.is_a?(Net::HTTPBadRequest)
raise SalesForceError.new(result)
end
end | ruby | def list_sobjects
result = http_get("/services/data/v#{self.version}/sobjects")
if result.is_a?(Net::HTTPOK)
JSON.parse(result.body)["sobjects"].collect { |sobject| sobject["name"] }
elsif result.is_a?(Net::HTTPBadRequest)
raise SalesForceError.new(result)
end
end | [
"def",
"list_sobjects",
"result",
"=",
"http_get",
"(",
"\"/services/data/v#{self.version}/sobjects\"",
")",
"if",
"result",
".",
"is_a?",
"(",
"Net",
"::",
"HTTPOK",
")",
"JSON",
".",
"parse",
"(",
"result",
".",
"body",
")",
"[",
"\"sobjects\"",
"]",
".",
"collect",
"{",
"|",
"sobject",
"|",
"sobject",
"[",
"\"name\"",
"]",
"}",
"elsif",
"result",
".",
"is_a?",
"(",
"Net",
"::",
"HTTPBadRequest",
")",
"raise",
"SalesForceError",
".",
"new",
"(",
"result",
")",
"end",
"end"
] | Returns an Array of Strings listing the class names for every type of _Sobject_ in the database. Raises SalesForceError if an error occurs. | [
"Returns",
"an",
"Array",
"of",
"Strings",
"listing",
"the",
"class",
"names",
"for",
"every",
"type",
"of",
"_Sobject_",
"in",
"the",
"database",
".",
"Raises",
"SalesForceError",
"if",
"an",
"error",
"occurs",
"."
] | a9173ff9c47bf2321a6959c9616d00cb6d8e93be | https://github.com/heroku/databasedotcom/blob/a9173ff9c47bf2321a6959c9616d00cb6d8e93be/lib/databasedotcom/client.rb#L141-L148 | train |
heroku/databasedotcom | lib/databasedotcom/client.rb | Databasedotcom.Client.trending_topics | def trending_topics
result = http_get("/services/data/v#{self.version}/chatter/topics/trending")
result = JSON.parse(result.body)
result["topics"].collect { |topic| topic["name"] }
end | ruby | def trending_topics
result = http_get("/services/data/v#{self.version}/chatter/topics/trending")
result = JSON.parse(result.body)
result["topics"].collect { |topic| topic["name"] }
end | [
"def",
"trending_topics",
"result",
"=",
"http_get",
"(",
"\"/services/data/v#{self.version}/chatter/topics/trending\"",
")",
"result",
"=",
"JSON",
".",
"parse",
"(",
"result",
".",
"body",
")",
"result",
"[",
"\"topics\"",
"]",
".",
"collect",
"{",
"|",
"topic",
"|",
"topic",
"[",
"\"name\"",
"]",
"}",
"end"
] | Returns an array of trending topic names. | [
"Returns",
"an",
"array",
"of",
"trending",
"topic",
"names",
"."
] | a9173ff9c47bf2321a6959c9616d00cb6d8e93be | https://github.com/heroku/databasedotcom/blob/a9173ff9c47bf2321a6959c9616d00cb6d8e93be/lib/databasedotcom/client.rb#L278-L282 | train |
heroku/databasedotcom | lib/databasedotcom/client.rb | Databasedotcom.Client.record_from_hash | def record_from_hash(data)
attributes = data.delete('attributes')
new_record = find_or_materialize(attributes["type"]).new
data.each do |name, value|
field = new_record.description['fields'].find do |field|
key_from_label(field["label"]) == name || field["name"] == name || field["relationshipName"] == name
end
# Field not found
if field == nil
break
end
# If reference/lookup field data was fetched, recursively build the child record and apply
if value.is_a?(Hash) and field['type'] == 'reference' and field["relationshipName"]
relation = record_from_hash( value )
set_value( new_record, field["relationshipName"], relation, 'reference' )
# Apply the raw value for all other field types
else
set_value(new_record, field["name"], value, field["type"]) if field
end
end
new_record
end | ruby | def record_from_hash(data)
attributes = data.delete('attributes')
new_record = find_or_materialize(attributes["type"]).new
data.each do |name, value|
field = new_record.description['fields'].find do |field|
key_from_label(field["label"]) == name || field["name"] == name || field["relationshipName"] == name
end
# Field not found
if field == nil
break
end
# If reference/lookup field data was fetched, recursively build the child record and apply
if value.is_a?(Hash) and field['type'] == 'reference' and field["relationshipName"]
relation = record_from_hash( value )
set_value( new_record, field["relationshipName"], relation, 'reference' )
# Apply the raw value for all other field types
else
set_value(new_record, field["name"], value, field["type"]) if field
end
end
new_record
end | [
"def",
"record_from_hash",
"(",
"data",
")",
"attributes",
"=",
"data",
".",
"delete",
"(",
"'attributes'",
")",
"new_record",
"=",
"find_or_materialize",
"(",
"attributes",
"[",
"\"type\"",
"]",
")",
".",
"new",
"data",
".",
"each",
"do",
"|",
"name",
",",
"value",
"|",
"field",
"=",
"new_record",
".",
"description",
"[",
"'fields'",
"]",
".",
"find",
"do",
"|",
"field",
"|",
"key_from_label",
"(",
"field",
"[",
"\"label\"",
"]",
")",
"==",
"name",
"||",
"field",
"[",
"\"name\"",
"]",
"==",
"name",
"||",
"field",
"[",
"\"relationshipName\"",
"]",
"==",
"name",
"end",
"# Field not found",
"if",
"field",
"==",
"nil",
"break",
"end",
"# If reference/lookup field data was fetched, recursively build the child record and apply",
"if",
"value",
".",
"is_a?",
"(",
"Hash",
")",
"and",
"field",
"[",
"'type'",
"]",
"==",
"'reference'",
"and",
"field",
"[",
"\"relationshipName\"",
"]",
"relation",
"=",
"record_from_hash",
"(",
"value",
")",
"set_value",
"(",
"new_record",
",",
"field",
"[",
"\"relationshipName\"",
"]",
",",
"relation",
",",
"'reference'",
")",
"# Apply the raw value for all other field types",
"else",
"set_value",
"(",
"new_record",
",",
"field",
"[",
"\"name\"",
"]",
",",
"value",
",",
"field",
"[",
"\"type\"",
"]",
")",
"if",
"field",
"end",
"end",
"new_record",
"end"
] | Converts a Hash of object data into a concrete SObject | [
"Converts",
"a",
"Hash",
"of",
"object",
"data",
"into",
"a",
"concrete",
"SObject"
] | a9173ff9c47bf2321a6959c9616d00cb6d8e93be | https://github.com/heroku/databasedotcom/blob/a9173ff9c47bf2321a6959c9616d00cb6d8e93be/lib/databasedotcom/client.rb#L437-L461 | train |
DamirSvrtan/fasterer | lib/fasterer/scanners/method_call_scanner.rb | Fasterer.MethodCallScanner.check_symbol_to_proc | def check_symbol_to_proc
return unless method_call.block_argument_names.count == 1
return if method_call.block_body.nil?
return unless method_call.block_body.sexp_type == :call
return if method_call.arguments.count > 0
body_method_call = MethodCall.new(method_call.block_body)
return unless body_method_call.arguments.count.zero?
return if body_method_call.has_block?
return unless body_method_call.receiver.name == method_call.block_argument_names.first
add_offense(:block_vs_symbol_to_proc)
end | ruby | def check_symbol_to_proc
return unless method_call.block_argument_names.count == 1
return if method_call.block_body.nil?
return unless method_call.block_body.sexp_type == :call
return if method_call.arguments.count > 0
body_method_call = MethodCall.new(method_call.block_body)
return unless body_method_call.arguments.count.zero?
return if body_method_call.has_block?
return unless body_method_call.receiver.name == method_call.block_argument_names.first
add_offense(:block_vs_symbol_to_proc)
end | [
"def",
"check_symbol_to_proc",
"return",
"unless",
"method_call",
".",
"block_argument_names",
".",
"count",
"==",
"1",
"return",
"if",
"method_call",
".",
"block_body",
".",
"nil?",
"return",
"unless",
"method_call",
".",
"block_body",
".",
"sexp_type",
"==",
":call",
"return",
"if",
"method_call",
".",
"arguments",
".",
"count",
">",
"0",
"body_method_call",
"=",
"MethodCall",
".",
"new",
"(",
"method_call",
".",
"block_body",
")",
"return",
"unless",
"body_method_call",
".",
"arguments",
".",
"count",
".",
"zero?",
"return",
"if",
"body_method_call",
".",
"has_block?",
"return",
"unless",
"body_method_call",
".",
"receiver",
".",
"name",
"==",
"method_call",
".",
"block_argument_names",
".",
"first",
"add_offense",
"(",
":block_vs_symbol_to_proc",
")",
"end"
] | Need to refactor, fukken complicated conditions. | [
"Need",
"to",
"refactor",
"fukken",
"complicated",
"conditions",
"."
] | f451a740879efa3c82c0604e3cc80b651f3461ab | https://github.com/DamirSvrtan/fasterer/blob/f451a740879efa3c82c0604e3cc80b651f3461ab/lib/fasterer/scanners/method_call_scanner.rb#L123-L136 | train |
jmettraux/rufus-scheduler | lib/rufus/scheduler.rb | Rufus.Scheduler.scheduled? | def scheduled?(job_or_job_id)
job, _ = fetch(job_or_job_id)
!! (job && job.unscheduled_at.nil? && job.next_time != nil)
end | ruby | def scheduled?(job_or_job_id)
job, _ = fetch(job_or_job_id)
!! (job && job.unscheduled_at.nil? && job.next_time != nil)
end | [
"def",
"scheduled?",
"(",
"job_or_job_id",
")",
"job",
",",
"_",
"=",
"fetch",
"(",
"job_or_job_id",
")",
"!",
"!",
"(",
"job",
"&&",
"job",
".",
"unscheduled_at",
".",
"nil?",
"&&",
"job",
".",
"next_time",
"!=",
"nil",
")",
"end"
] | Returns true if this job is currently scheduled.
Takes extra care to answer true if the job is a repeat job
currently firing. | [
"Returns",
"true",
"if",
"this",
"job",
"is",
"currently",
"scheduled",
"."
] | db3b559fbd988ef44126ea59508e0c62bfc45540 | https://github.com/jmettraux/rufus-scheduler/blob/db3b559fbd988ef44126ea59508e0c62bfc45540/lib/rufus/scheduler.rb#L374-L379 | train |
toptal/crystalball | lib/crystalball/extensions/git/lib.rb | Git.Lib.merge_base | def merge_base(*args)
opts = args.last.is_a?(Hash) ? args.pop : {}
arg_opts = opts.map { |k, v| "--#{k}" if v }.compact + args
command('merge-base', arg_opts)
end | ruby | def merge_base(*args)
opts = args.last.is_a?(Hash) ? args.pop : {}
arg_opts = opts.map { |k, v| "--#{k}" if v }.compact + args
command('merge-base', arg_opts)
end | [
"def",
"merge_base",
"(",
"*",
"args",
")",
"opts",
"=",
"args",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"args",
".",
"pop",
":",
"{",
"}",
"arg_opts",
"=",
"opts",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"\"--#{k}\"",
"if",
"v",
"}",
".",
"compact",
"+",
"args",
"command",
"(",
"'merge-base'",
",",
"arg_opts",
")",
"end"
] | `git merge-base ...`. Returns common ancestor for all passed commits
@param [Array<Object>] args - list of commits to process. Last argument can be options for merge-base command
@return [String] | [
"git",
"merge",
"-",
"base",
"...",
".",
"Returns",
"common",
"ancestor",
"for",
"all",
"passed",
"commits"
] | 9cb62597425e0d0d3e8b428c7d08d3940a43fdea | https://github.com/toptal/crystalball/blob/9cb62597425e0d0d3e8b428c7d08d3940a43fdea/lib/crystalball/extensions/git/lib.rb#L10-L16 | train |
toptal/crystalball | lib/crystalball/map_generator.rb | Crystalball.MapGenerator.start! | def start!
self.map = nil
map_storage.clear!
map_storage.dump(map.metadata.to_h)
strategies.reverse.each(&:after_start)
self.started = true
end | ruby | def start!
self.map = nil
map_storage.clear!
map_storage.dump(map.metadata.to_h)
strategies.reverse.each(&:after_start)
self.started = true
end | [
"def",
"start!",
"self",
".",
"map",
"=",
"nil",
"map_storage",
".",
"clear!",
"map_storage",
".",
"dump",
"(",
"map",
".",
"metadata",
".",
"to_h",
")",
"strategies",
".",
"reverse",
".",
"each",
"(",
":after_start",
")",
"self",
".",
"started",
"=",
"true",
"end"
] | Registers strategies and prepares metadata for execution map | [
"Registers",
"strategies",
"and",
"prepares",
"metadata",
"for",
"execution",
"map"
] | 9cb62597425e0d0d3e8b428c7d08d3940a43fdea | https://github.com/toptal/crystalball/blob/9cb62597425e0d0d3e8b428c7d08d3940a43fdea/lib/crystalball/map_generator.rb#L35-L42 | train |
toptal/crystalball | lib/crystalball/map_generator.rb | Crystalball.MapGenerator.refresh_for_case | def refresh_for_case(example)
map << strategies.run(ExampleGroupMap.new(example), example) { example.run }
check_dump_threshold
end | ruby | def refresh_for_case(example)
map << strategies.run(ExampleGroupMap.new(example), example) { example.run }
check_dump_threshold
end | [
"def",
"refresh_for_case",
"(",
"example",
")",
"map",
"<<",
"strategies",
".",
"run",
"(",
"ExampleGroupMap",
".",
"new",
"(",
"example",
")",
",",
"example",
")",
"{",
"example",
".",
"run",
"}",
"check_dump_threshold",
"end"
] | Runs example and collects execution map for it | [
"Runs",
"example",
"and",
"collects",
"execution",
"map",
"for",
"it"
] | 9cb62597425e0d0d3e8b428c7d08d3940a43fdea | https://github.com/toptal/crystalball/blob/9cb62597425e0d0d3e8b428c7d08d3940a43fdea/lib/crystalball/map_generator.rb#L45-L48 | train |
toptal/crystalball | lib/crystalball/map_generator.rb | Crystalball.MapGenerator.finalize! | def finalize!
return unless started
strategies.each(&:before_finalize)
return unless map.size.positive?
example_groups = (configuration.compact_map? ? MapCompactor.compact_map!(map) : map).example_groups
map_storage.dump(example_groups)
end | ruby | def finalize!
return unless started
strategies.each(&:before_finalize)
return unless map.size.positive?
example_groups = (configuration.compact_map? ? MapCompactor.compact_map!(map) : map).example_groups
map_storage.dump(example_groups)
end | [
"def",
"finalize!",
"return",
"unless",
"started",
"strategies",
".",
"each",
"(",
":before_finalize",
")",
"return",
"unless",
"map",
".",
"size",
".",
"positive?",
"example_groups",
"=",
"(",
"configuration",
".",
"compact_map?",
"?",
"MapCompactor",
".",
"compact_map!",
"(",
"map",
")",
":",
"map",
")",
".",
"example_groups",
"map_storage",
".",
"dump",
"(",
"example_groups",
")",
"end"
] | Finalizes strategies and saves map | [
"Finalizes",
"strategies",
"and",
"saves",
"map"
] | 9cb62597425e0d0d3e8b428c7d08d3940a43fdea | https://github.com/toptal/crystalball/blob/9cb62597425e0d0d3e8b428c7d08d3940a43fdea/lib/crystalball/map_generator.rb#L51-L60 | train |
gdelugre/origami | lib/origami/page.rb | Origami.ResourcesHolder.add_resource | def add_resource(type, rsrc, name = nil)
if name.nil?
rsrc_name = self.resources(type).key(rsrc)
return rsrc_name if rsrc_name
end
name ||= new_id(type)
target = self.is_a?(Resources) ? self : (self.Resources ||= Resources.new)
rsrc_dict = (target[type] and target[type].solve) || (target[type] = Dictionary.new)
rsrc_dict[name.to_sym] = rsrc
name
end | ruby | def add_resource(type, rsrc, name = nil)
if name.nil?
rsrc_name = self.resources(type).key(rsrc)
return rsrc_name if rsrc_name
end
name ||= new_id(type)
target = self.is_a?(Resources) ? self : (self.Resources ||= Resources.new)
rsrc_dict = (target[type] and target[type].solve) || (target[type] = Dictionary.new)
rsrc_dict[name.to_sym] = rsrc
name
end | [
"def",
"add_resource",
"(",
"type",
",",
"rsrc",
",",
"name",
"=",
"nil",
")",
"if",
"name",
".",
"nil?",
"rsrc_name",
"=",
"self",
".",
"resources",
"(",
"type",
")",
".",
"key",
"(",
"rsrc",
")",
"return",
"rsrc_name",
"if",
"rsrc_name",
"end",
"name",
"||=",
"new_id",
"(",
"type",
")",
"target",
"=",
"self",
".",
"is_a?",
"(",
"Resources",
")",
"?",
"self",
":",
"(",
"self",
".",
"Resources",
"||=",
"Resources",
".",
"new",
")",
"rsrc_dict",
"=",
"(",
"target",
"[",
"type",
"]",
"and",
"target",
"[",
"type",
"]",
".",
"solve",
")",
"||",
"(",
"target",
"[",
"type",
"]",
"=",
"Dictionary",
".",
"new",
")",
"rsrc_dict",
"[",
"name",
".",
"to_sym",
"]",
"=",
"rsrc",
"name",
"end"
] | Adds a resource of the specified _type_ in the current object.
If _name_ is not specified, a new name will be automatically generated. | [
"Adds",
"a",
"resource",
"of",
"the",
"specified",
"_type_",
"in",
"the",
"current",
"object",
".",
"If",
"_name_",
"is",
"not",
"specified",
"a",
"new",
"name",
"will",
"be",
"automatically",
"generated",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/page.rb#L148-L161 | train |
gdelugre/origami | lib/origami/page.rb | Origami.ResourcesHolder.each_resource | def each_resource(type)
target = self.is_a?(Resources) ? self : (self.Resources ||= Resources.new)
rsrc = (target[type] and target[type].solve)
return enum_for(__method__, type) { rsrc.is_a?(Dictionary) ? rsrc.length : 0 } unless block_given?
return unless rsrc.is_a?(Dictionary)
rsrc.each_pair do |name, obj|
yield(name.value, obj.solve)
end
end | ruby | def each_resource(type)
target = self.is_a?(Resources) ? self : (self.Resources ||= Resources.new)
rsrc = (target[type] and target[type].solve)
return enum_for(__method__, type) { rsrc.is_a?(Dictionary) ? rsrc.length : 0 } unless block_given?
return unless rsrc.is_a?(Dictionary)
rsrc.each_pair do |name, obj|
yield(name.value, obj.solve)
end
end | [
"def",
"each_resource",
"(",
"type",
")",
"target",
"=",
"self",
".",
"is_a?",
"(",
"Resources",
")",
"?",
"self",
":",
"(",
"self",
".",
"Resources",
"||=",
"Resources",
".",
"new",
")",
"rsrc",
"=",
"(",
"target",
"[",
"type",
"]",
"and",
"target",
"[",
"type",
"]",
".",
"solve",
")",
"return",
"enum_for",
"(",
"__method__",
",",
"type",
")",
"{",
"rsrc",
".",
"is_a?",
"(",
"Dictionary",
")",
"?",
"rsrc",
".",
"length",
":",
"0",
"}",
"unless",
"block_given?",
"return",
"unless",
"rsrc",
".",
"is_a?",
"(",
"Dictionary",
")",
"rsrc",
".",
"each_pair",
"do",
"|",
"name",
",",
"obj",
"|",
"yield",
"(",
"name",
".",
"value",
",",
"obj",
".",
"solve",
")",
"end",
"end"
] | Iterates over the resources by _type_. | [
"Iterates",
"over",
"the",
"resources",
"by",
"_type_",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/page.rb#L166-L177 | train |
gdelugre/origami | lib/origami/page.rb | Origami.ResourcesHolder.resources | def resources(type = nil)
if type.nil?
self.extgstates
.merge self.colorspaces
.merge self.patterns
.merge self.shadings
.merge self.xobjects
.merge self.fonts
.merge self.properties
else
self.each_resource(type).to_h
end
end | ruby | def resources(type = nil)
if type.nil?
self.extgstates
.merge self.colorspaces
.merge self.patterns
.merge self.shadings
.merge self.xobjects
.merge self.fonts
.merge self.properties
else
self.each_resource(type).to_h
end
end | [
"def",
"resources",
"(",
"type",
"=",
"nil",
")",
"if",
"type",
".",
"nil?",
"self",
".",
"extgstates",
".",
"merge",
"self",
".",
"colorspaces",
".",
"merge",
"self",
".",
"patterns",
".",
"merge",
"self",
".",
"shadings",
".",
"merge",
"self",
".",
"xobjects",
".",
"merge",
"self",
".",
"fonts",
".",
"merge",
"self",
".",
"properties",
"else",
"self",
".",
"each_resource",
"(",
"type",
")",
".",
"to_h",
"end",
"end"
] | Returns a Hash of all resources in the object or only the specified _type_. | [
"Returns",
"a",
"Hash",
"of",
"all",
"resources",
"in",
"the",
"object",
"or",
"only",
"the",
"specified",
"_type_",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/page.rb#L198-L210 | train |
gdelugre/origami | lib/origami/page.rb | Origami.PageTreeNode.each_page | def each_page(browsed_nodes: [], &block)
return enum_for(__method__) { self.Count.to_i } unless block_given?
if browsed_nodes.any?{|node| node.equal?(self)}
raise InvalidPageTreeError, "Cyclic tree graph detected"
end
unless self.Kids.is_a?(Array)
raise InvalidPageTreeError, "Kids must be an Array"
end
browsed_nodes.push(self)
unless self.Count.nil?
[ self.Count.value, self.Kids.length ].min.times do |n|
node = self.Kids[n].solve
case node
when PageTreeNode then node.each_page(browsed_nodes: browsed_nodes, &block)
when Page then yield(node)
else
raise InvalidPageTreeError, "not a Page or PageTreeNode"
end
end
end
self
end | ruby | def each_page(browsed_nodes: [], &block)
return enum_for(__method__) { self.Count.to_i } unless block_given?
if browsed_nodes.any?{|node| node.equal?(self)}
raise InvalidPageTreeError, "Cyclic tree graph detected"
end
unless self.Kids.is_a?(Array)
raise InvalidPageTreeError, "Kids must be an Array"
end
browsed_nodes.push(self)
unless self.Count.nil?
[ self.Count.value, self.Kids.length ].min.times do |n|
node = self.Kids[n].solve
case node
when PageTreeNode then node.each_page(browsed_nodes: browsed_nodes, &block)
when Page then yield(node)
else
raise InvalidPageTreeError, "not a Page or PageTreeNode"
end
end
end
self
end | [
"def",
"each_page",
"(",
"browsed_nodes",
":",
"[",
"]",
",",
"&",
"block",
")",
"return",
"enum_for",
"(",
"__method__",
")",
"{",
"self",
".",
"Count",
".",
"to_i",
"}",
"unless",
"block_given?",
"if",
"browsed_nodes",
".",
"any?",
"{",
"|",
"node",
"|",
"node",
".",
"equal?",
"(",
"self",
")",
"}",
"raise",
"InvalidPageTreeError",
",",
"\"Cyclic tree graph detected\"",
"end",
"unless",
"self",
".",
"Kids",
".",
"is_a?",
"(",
"Array",
")",
"raise",
"InvalidPageTreeError",
",",
"\"Kids must be an Array\"",
"end",
"browsed_nodes",
".",
"push",
"(",
"self",
")",
"unless",
"self",
".",
"Count",
".",
"nil?",
"[",
"self",
".",
"Count",
".",
"value",
",",
"self",
".",
"Kids",
".",
"length",
"]",
".",
"min",
".",
"times",
"do",
"|",
"n",
"|",
"node",
"=",
"self",
".",
"Kids",
"[",
"n",
"]",
".",
"solve",
"case",
"node",
"when",
"PageTreeNode",
"then",
"node",
".",
"each_page",
"(",
"browsed_nodes",
":",
"browsed_nodes",
",",
"block",
")",
"when",
"Page",
"then",
"yield",
"(",
"node",
")",
"else",
"raise",
"InvalidPageTreeError",
",",
"\"not a Page or PageTreeNode\"",
"end",
"end",
"end",
"self",
"end"
] | Iterate through each page of that node. | [
"Iterate",
"through",
"each",
"page",
"of",
"that",
"node",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/page.rb#L345-L372 | train |
gdelugre/origami | lib/origami/page.rb | Origami.PageTreeNode.get_page | def get_page(n)
raise IndexError, "Page numbers are referenced starting from 1" if n < 1
raise IndexError, "Page not found" if n > self.Count.to_i
self.each_page.lazy.drop(n - 1).first or raise IndexError, "Page not found"
end | ruby | def get_page(n)
raise IndexError, "Page numbers are referenced starting from 1" if n < 1
raise IndexError, "Page not found" if n > self.Count.to_i
self.each_page.lazy.drop(n - 1).first or raise IndexError, "Page not found"
end | [
"def",
"get_page",
"(",
"n",
")",
"raise",
"IndexError",
",",
"\"Page numbers are referenced starting from 1\"",
"if",
"n",
"<",
"1",
"raise",
"IndexError",
",",
"\"Page not found\"",
"if",
"n",
">",
"self",
".",
"Count",
".",
"to_i",
"self",
".",
"each_page",
".",
"lazy",
".",
"drop",
"(",
"n",
"-",
"1",
")",
".",
"first",
"or",
"raise",
"IndexError",
",",
"\"Page not found\"",
"end"
] | Get the n-th Page object in this node, starting from 1. | [
"Get",
"the",
"n",
"-",
"th",
"Page",
"object",
"in",
"this",
"node",
"starting",
"from",
"1",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/page.rb#L377-L382 | train |
gdelugre/origami | lib/origami/page.rb | Origami.Page.each_content_stream | def each_content_stream
contents = self.Contents
return enum_for(__method__) do
case contents
when Array then contents.length
when Stream then 1
else
0
end
end unless block_given?
case contents
when Stream then yield(contents)
when Array then contents.each { |stm| yield(stm.solve) }
end
end | ruby | def each_content_stream
contents = self.Contents
return enum_for(__method__) do
case contents
when Array then contents.length
when Stream then 1
else
0
end
end unless block_given?
case contents
when Stream then yield(contents)
when Array then contents.each { |stm| yield(stm.solve) }
end
end | [
"def",
"each_content_stream",
"contents",
"=",
"self",
".",
"Contents",
"return",
"enum_for",
"(",
"__method__",
")",
"do",
"case",
"contents",
"when",
"Array",
"then",
"contents",
".",
"length",
"when",
"Stream",
"then",
"1",
"else",
"0",
"end",
"end",
"unless",
"block_given?",
"case",
"contents",
"when",
"Stream",
"then",
"yield",
"(",
"contents",
")",
"when",
"Array",
"then",
"contents",
".",
"each",
"{",
"|",
"stm",
"|",
"yield",
"(",
"stm",
".",
"solve",
")",
"}",
"end",
"end"
] | Iterates over all the ContentStreams of the Page. | [
"Iterates",
"over",
"all",
"the",
"ContentStreams",
"of",
"the",
"Page",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/page.rb#L560-L576 | train |
gdelugre/origami | lib/origami/page.rb | Origami.Page.add_annotation | def add_annotation(*annotations)
self.Annots ||= []
annotations.each do |annot|
annot.solve[:P] = self if self.indirect?
self.Annots << annot
end
end | ruby | def add_annotation(*annotations)
self.Annots ||= []
annotations.each do |annot|
annot.solve[:P] = self if self.indirect?
self.Annots << annot
end
end | [
"def",
"add_annotation",
"(",
"*",
"annotations",
")",
"self",
".",
"Annots",
"||=",
"[",
"]",
"annotations",
".",
"each",
"do",
"|",
"annot",
"|",
"annot",
".",
"solve",
"[",
":P",
"]",
"=",
"self",
"if",
"self",
".",
"indirect?",
"self",
".",
"Annots",
"<<",
"annot",
"end",
"end"
] | Add an Annotation to the Page. | [
"Add",
"an",
"Annotation",
"to",
"the",
"Page",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/page.rb#L588-L595 | train |
gdelugre/origami | lib/origami/page.rb | Origami.Page.each_annotation | def each_annotation
annots = self.Annots
return enum_for(__method__) { annots.is_a?(Array) ? annots.length : 0 } unless block_given?
return unless annots.is_a?(Array)
annots.each do |annot|
yield(annot.solve)
end
end | ruby | def each_annotation
annots = self.Annots
return enum_for(__method__) { annots.is_a?(Array) ? annots.length : 0 } unless block_given?
return unless annots.is_a?(Array)
annots.each do |annot|
yield(annot.solve)
end
end | [
"def",
"each_annotation",
"annots",
"=",
"self",
".",
"Annots",
"return",
"enum_for",
"(",
"__method__",
")",
"{",
"annots",
".",
"is_a?",
"(",
"Array",
")",
"?",
"annots",
".",
"length",
":",
"0",
"}",
"unless",
"block_given?",
"return",
"unless",
"annots",
".",
"is_a?",
"(",
"Array",
")",
"annots",
".",
"each",
"do",
"|",
"annot",
"|",
"yield",
"(",
"annot",
".",
"solve",
")",
"end",
"end"
] | Iterate through each Annotation of the Page. | [
"Iterate",
"through",
"each",
"Annotation",
"of",
"the",
"Page",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/page.rb#L600-L609 | train |
gdelugre/origami | lib/origami/page.rb | Origami.Page.add_flash_application | def add_flash_application(swfspec, params = {})
options =
{
windowed: false,
transparent: false,
navigation_pane: false,
toolbar: false,
pass_context_click: false,
activation: Annotation::RichMedia::Activation::PAGE_OPEN,
deactivation: Annotation::RichMedia::Deactivation::PAGE_CLOSE,
flash_vars: nil
}
options.update(params)
annot = create_richmedia(:Flash, swfspec, options)
add_annotation(annot)
annot
end | ruby | def add_flash_application(swfspec, params = {})
options =
{
windowed: false,
transparent: false,
navigation_pane: false,
toolbar: false,
pass_context_click: false,
activation: Annotation::RichMedia::Activation::PAGE_OPEN,
deactivation: Annotation::RichMedia::Deactivation::PAGE_CLOSE,
flash_vars: nil
}
options.update(params)
annot = create_richmedia(:Flash, swfspec, options)
add_annotation(annot)
annot
end | [
"def",
"add_flash_application",
"(",
"swfspec",
",",
"params",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"windowed",
":",
"false",
",",
"transparent",
":",
"false",
",",
"navigation_pane",
":",
"false",
",",
"toolbar",
":",
"false",
",",
"pass_context_click",
":",
"false",
",",
"activation",
":",
"Annotation",
"::",
"RichMedia",
"::",
"Activation",
"::",
"PAGE_OPEN",
",",
"deactivation",
":",
"Annotation",
"::",
"RichMedia",
"::",
"Deactivation",
"::",
"PAGE_CLOSE",
",",
"flash_vars",
":",
"nil",
"}",
"options",
".",
"update",
"(",
"params",
")",
"annot",
"=",
"create_richmedia",
"(",
":Flash",
",",
"swfspec",
",",
"options",
")",
"add_annotation",
"(",
"annot",
")",
"annot",
"end"
] | Embed a SWF Flash application in the page. | [
"Embed",
"a",
"SWF",
"Flash",
"application",
"in",
"the",
"page",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/page.rb#L621-L639 | train |
gdelugre/origami | lib/origami/metadata.rb | Origami.PDF.metadata | def metadata
metadata_stm = self.Catalog.Metadata
if metadata_stm.is_a?(Stream)
doc = REXML::Document.new(metadata_stm.data)
info = {}
doc.elements.each('*/*/rdf:Description') do |description|
description.attributes.each_attribute do |attr|
case attr.prefix
when 'pdf','xap'
info[attr.name] = attr.value
end
end
description.elements.each('*') do |element|
value = (element.elements['.//rdf:li'] || element).text
info[element.name] = value.to_s
end
end
info
end
end | ruby | def metadata
metadata_stm = self.Catalog.Metadata
if metadata_stm.is_a?(Stream)
doc = REXML::Document.new(metadata_stm.data)
info = {}
doc.elements.each('*/*/rdf:Description') do |description|
description.attributes.each_attribute do |attr|
case attr.prefix
when 'pdf','xap'
info[attr.name] = attr.value
end
end
description.elements.each('*') do |element|
value = (element.elements['.//rdf:li'] || element).text
info[element.name] = value.to_s
end
end
info
end
end | [
"def",
"metadata",
"metadata_stm",
"=",
"self",
".",
"Catalog",
".",
"Metadata",
"if",
"metadata_stm",
".",
"is_a?",
"(",
"Stream",
")",
"doc",
"=",
"REXML",
"::",
"Document",
".",
"new",
"(",
"metadata_stm",
".",
"data",
")",
"info",
"=",
"{",
"}",
"doc",
".",
"elements",
".",
"each",
"(",
"'*/*/rdf:Description'",
")",
"do",
"|",
"description",
"|",
"description",
".",
"attributes",
".",
"each_attribute",
"do",
"|",
"attr",
"|",
"case",
"attr",
".",
"prefix",
"when",
"'pdf'",
",",
"'xap'",
"info",
"[",
"attr",
".",
"name",
"]",
"=",
"attr",
".",
"value",
"end",
"end",
"description",
".",
"elements",
".",
"each",
"(",
"'*'",
")",
"do",
"|",
"element",
"|",
"value",
"=",
"(",
"element",
".",
"elements",
"[",
"'.//rdf:li'",
"]",
"||",
"element",
")",
".",
"text",
"info",
"[",
"element",
".",
"name",
"]",
"=",
"value",
".",
"to_s",
"end",
"end",
"info",
"end",
"end"
] | Returns a Hash of the information found in the metadata stream | [
"Returns",
"a",
"Hash",
"of",
"the",
"information",
"found",
"in",
"the",
"metadata",
"stream"
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/metadata.rb#L59-L83 | train |
gdelugre/origami | lib/origami/metadata.rb | Origami.PDF.create_metadata | def create_metadata(info = {})
skeleton = <<-XMP
<?packet begin="\xef\xbb\xbf" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about="" xmlns:pdf="http://ns.adobe.com/pdf/1.3/">
</rdf:Description>
</rdf:RDF>
</x:xmpmeta>
<?xpacket end="w"?>
XMP
xml =
if self.Catalog.Metadata.is_a?(Stream)
self.Catalog.Metadata.data
else
skeleton
end
doc = REXML::Document.new(xml)
desc = doc.elements['*/*/rdf:Description']
info.each do |name, value|
elt = REXML::Element.new "pdf:#{name}"
elt.text = value
desc.elements << elt
end
xml = ""; doc.write(xml, 4)
if self.Catalog.Metadata.is_a?(Stream)
self.Catalog.Metadata.data = xml
else
self.Catalog.Metadata = Stream.new(xml)
end
self.Catalog.Metadata
end | ruby | def create_metadata(info = {})
skeleton = <<-XMP
<?packet begin="\xef\xbb\xbf" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about="" xmlns:pdf="http://ns.adobe.com/pdf/1.3/">
</rdf:Description>
</rdf:RDF>
</x:xmpmeta>
<?xpacket end="w"?>
XMP
xml =
if self.Catalog.Metadata.is_a?(Stream)
self.Catalog.Metadata.data
else
skeleton
end
doc = REXML::Document.new(xml)
desc = doc.elements['*/*/rdf:Description']
info.each do |name, value|
elt = REXML::Element.new "pdf:#{name}"
elt.text = value
desc.elements << elt
end
xml = ""; doc.write(xml, 4)
if self.Catalog.Metadata.is_a?(Stream)
self.Catalog.Metadata.data = xml
else
self.Catalog.Metadata = Stream.new(xml)
end
self.Catalog.Metadata
end | [
"def",
"create_metadata",
"(",
"info",
"=",
"{",
"}",
")",
"skeleton",
"=",
"<<-XMP",
"\\xef",
"\\xbb",
"\\xbf",
"XMP",
"xml",
"=",
"if",
"self",
".",
"Catalog",
".",
"Metadata",
".",
"is_a?",
"(",
"Stream",
")",
"self",
".",
"Catalog",
".",
"Metadata",
".",
"data",
"else",
"skeleton",
"end",
"doc",
"=",
"REXML",
"::",
"Document",
".",
"new",
"(",
"xml",
")",
"desc",
"=",
"doc",
".",
"elements",
"[",
"'*/*/rdf:Description'",
"]",
"info",
".",
"each",
"do",
"|",
"name",
",",
"value",
"|",
"elt",
"=",
"REXML",
"::",
"Element",
".",
"new",
"\"pdf:#{name}\"",
"elt",
".",
"text",
"=",
"value",
"desc",
".",
"elements",
"<<",
"elt",
"end",
"xml",
"=",
"\"\"",
";",
"doc",
".",
"write",
"(",
"xml",
",",
"4",
")",
"if",
"self",
".",
"Catalog",
".",
"Metadata",
".",
"is_a?",
"(",
"Stream",
")",
"self",
".",
"Catalog",
".",
"Metadata",
".",
"data",
"=",
"xml",
"else",
"self",
".",
"Catalog",
".",
"Metadata",
"=",
"Stream",
".",
"new",
"(",
"xml",
")",
"end",
"self",
".",
"Catalog",
".",
"Metadata",
"end"
] | Modifies or creates a metadata stream. | [
"Modifies",
"or",
"creates",
"a",
"metadata",
"stream",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/metadata.rb#L88-L126 | train |
gdelugre/origami | lib/origami/trailer.rb | Origami.PDF.trailer | def trailer
#
# First look for a standard trailer dictionary
#
if @revisions.last.trailer.dictionary?
trl = @revisions.last.trailer
#
# Otherwise look for a xref stream.
#
else
trl = @revisions.last.xrefstm
end
raise InvalidPDFError, "No trailer found" if trl.nil?
trl
end | ruby | def trailer
#
# First look for a standard trailer dictionary
#
if @revisions.last.trailer.dictionary?
trl = @revisions.last.trailer
#
# Otherwise look for a xref stream.
#
else
trl = @revisions.last.xrefstm
end
raise InvalidPDFError, "No trailer found" if trl.nil?
trl
end | [
"def",
"trailer",
"#",
"# First look for a standard trailer dictionary",
"#",
"if",
"@revisions",
".",
"last",
".",
"trailer",
".",
"dictionary?",
"trl",
"=",
"@revisions",
".",
"last",
".",
"trailer",
"#",
"# Otherwise look for a xref stream.",
"#",
"else",
"trl",
"=",
"@revisions",
".",
"last",
".",
"xrefstm",
"end",
"raise",
"InvalidPDFError",
",",
"\"No trailer found\"",
"if",
"trl",
".",
"nil?",
"trl",
"end"
] | Returns the current trailer.
This might be either a Trailer or XRefStream. | [
"Returns",
"the",
"current",
"trailer",
".",
"This",
"might",
"be",
"either",
"a",
"Trailer",
"or",
"XRefStream",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/trailer.rb#L29-L46 | train |
gdelugre/origami | lib/origami/extensions/ppklite.rb | Origami.PPKLite.add_certificate | def add_certificate(certfile, attributes, viewable: false, editable: false)
if certfile.is_a?(OpenSSL::X509::Certificate)
x509 = certfile
else
x509 = OpenSSL::X509::Certificate.new(certfile)
end
address_book = get_address_book
cert = Certificate.new
cert.Cert = x509.to_der
cert.ID = address_book.NextID
address_book.NextID += 1
cert.Trust = attributes
cert.Viewable = viewable
cert.Editable = editable
address_book.Entries.push(self << cert)
end | ruby | def add_certificate(certfile, attributes, viewable: false, editable: false)
if certfile.is_a?(OpenSSL::X509::Certificate)
x509 = certfile
else
x509 = OpenSSL::X509::Certificate.new(certfile)
end
address_book = get_address_book
cert = Certificate.new
cert.Cert = x509.to_der
cert.ID = address_book.NextID
address_book.NextID += 1
cert.Trust = attributes
cert.Viewable = viewable
cert.Editable = editable
address_book.Entries.push(self << cert)
end | [
"def",
"add_certificate",
"(",
"certfile",
",",
"attributes",
",",
"viewable",
":",
"false",
",",
"editable",
":",
"false",
")",
"if",
"certfile",
".",
"is_a?",
"(",
"OpenSSL",
"::",
"X509",
"::",
"Certificate",
")",
"x509",
"=",
"certfile",
"else",
"x509",
"=",
"OpenSSL",
"::",
"X509",
"::",
"Certificate",
".",
"new",
"(",
"certfile",
")",
"end",
"address_book",
"=",
"get_address_book",
"cert",
"=",
"Certificate",
".",
"new",
"cert",
".",
"Cert",
"=",
"x509",
".",
"to_der",
"cert",
".",
"ID",
"=",
"address_book",
".",
"NextID",
"address_book",
".",
"NextID",
"+=",
"1",
"cert",
".",
"Trust",
"=",
"attributes",
"cert",
".",
"Viewable",
"=",
"viewable",
"cert",
".",
"Editable",
"=",
"editable",
"address_book",
".",
"Entries",
".",
"push",
"(",
"self",
"<<",
"cert",
")",
"end"
] | Add a certificate into the address book | [
"Add",
"a",
"certificate",
"into",
"the",
"address",
"book"
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/extensions/ppklite.rb#L346-L365 | train |
gdelugre/origami | lib/origami/stream.rb | Origami.Stream.each_filter | def each_filter
filters = self.Filter
return enum_for(__method__) do
case filters
when NilClass then 0
when Array then filters.length
else
1
end
end unless block_given?
return if filters.nil?
if filters.is_a?(Array)
filters.each do |filter| yield(filter) end
else
yield(filters)
end
self
end | ruby | def each_filter
filters = self.Filter
return enum_for(__method__) do
case filters
when NilClass then 0
when Array then filters.length
else
1
end
end unless block_given?
return if filters.nil?
if filters.is_a?(Array)
filters.each do |filter| yield(filter) end
else
yield(filters)
end
self
end | [
"def",
"each_filter",
"filters",
"=",
"self",
".",
"Filter",
"return",
"enum_for",
"(",
"__method__",
")",
"do",
"case",
"filters",
"when",
"NilClass",
"then",
"0",
"when",
"Array",
"then",
"filters",
".",
"length",
"else",
"1",
"end",
"end",
"unless",
"block_given?",
"return",
"if",
"filters",
".",
"nil?",
"if",
"filters",
".",
"is_a?",
"(",
"Array",
")",
"filters",
".",
"each",
"do",
"|",
"filter",
"|",
"yield",
"(",
"filter",
")",
"end",
"else",
"yield",
"(",
"filters",
")",
"end",
"self",
"end"
] | Iterates over each Filter in the Stream. | [
"Iterates",
"over",
"each",
"Filter",
"in",
"the",
"Stream",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/stream.rb#L166-L187 | train |
gdelugre/origami | lib/origami/stream.rb | Origami.Stream.set_predictor | def set_predictor(predictor, colors: 1, bitspercomponent: 8, columns: 1)
filters = self.filters
layer = filters.index(:FlateDecode) or filters.index(:LZWDecode)
if layer.nil?
raise InvalidStreamObjectError, 'Predictor functions can only be used with Flate or LZW filters'
end
params = Filter::LZW::DecodeParms.new
params[:Predictor] = predictor
params[:Colors] = colors if colors != 1
params[:BitsPerComponent] = bitspercomponent if bitspercomponent != 8
params[:Columns] = columns if columns != 1
set_decode_params(layer, params)
self
end | ruby | def set_predictor(predictor, colors: 1, bitspercomponent: 8, columns: 1)
filters = self.filters
layer = filters.index(:FlateDecode) or filters.index(:LZWDecode)
if layer.nil?
raise InvalidStreamObjectError, 'Predictor functions can only be used with Flate or LZW filters'
end
params = Filter::LZW::DecodeParms.new
params[:Predictor] = predictor
params[:Colors] = colors if colors != 1
params[:BitsPerComponent] = bitspercomponent if bitspercomponent != 8
params[:Columns] = columns if columns != 1
set_decode_params(layer, params)
self
end | [
"def",
"set_predictor",
"(",
"predictor",
",",
"colors",
":",
"1",
",",
"bitspercomponent",
":",
"8",
",",
"columns",
":",
"1",
")",
"filters",
"=",
"self",
".",
"filters",
"layer",
"=",
"filters",
".",
"index",
"(",
":FlateDecode",
")",
"or",
"filters",
".",
"index",
"(",
":LZWDecode",
")",
"if",
"layer",
".",
"nil?",
"raise",
"InvalidStreamObjectError",
",",
"'Predictor functions can only be used with Flate or LZW filters'",
"end",
"params",
"=",
"Filter",
"::",
"LZW",
"::",
"DecodeParms",
".",
"new",
"params",
"[",
":Predictor",
"]",
"=",
"predictor",
"params",
"[",
":Colors",
"]",
"=",
"colors",
"if",
"colors",
"!=",
"1",
"params",
"[",
":BitsPerComponent",
"]",
"=",
"bitspercomponent",
"if",
"bitspercomponent",
"!=",
"8",
"params",
"[",
":Columns",
"]",
"=",
"columns",
"if",
"columns",
"!=",
"1",
"set_decode_params",
"(",
"layer",
",",
"params",
")",
"self",
"end"
] | Set predictor type for the current Stream.
Applies only for LZW and FlateDecode filters. | [
"Set",
"predictor",
"type",
"for",
"the",
"current",
"Stream",
".",
"Applies",
"only",
"for",
"LZW",
"and",
"FlateDecode",
"filters",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/stream.rb#L200-L217 | train |
gdelugre/origami | lib/origami/stream.rb | Origami.Stream.decode! | def decode!
self.decrypt! if self.is_a?(Encryption::EncryptedStream)
return if decoded?
filters = self.filters
dparams = decode_params
@data = @encoded_data.dup
@data.freeze
filters.each_with_index do |filter, layer|
params = dparams[layer].is_a?(Dictionary) ? dparams[layer] : {}
# Handle Crypt filters.
if filter == :Crypt
raise Filter::Error, "Crypt filter must be the first filter" unless layer.zero?
# Skip the Crypt filter.
next
end
begin
@data = decode_data(@data, filter, params)
rescue Filter::Error => error
@data = error.decoded_data
raise
end
end
self
end | ruby | def decode!
self.decrypt! if self.is_a?(Encryption::EncryptedStream)
return if decoded?
filters = self.filters
dparams = decode_params
@data = @encoded_data.dup
@data.freeze
filters.each_with_index do |filter, layer|
params = dparams[layer].is_a?(Dictionary) ? dparams[layer] : {}
# Handle Crypt filters.
if filter == :Crypt
raise Filter::Error, "Crypt filter must be the first filter" unless layer.zero?
# Skip the Crypt filter.
next
end
begin
@data = decode_data(@data, filter, params)
rescue Filter::Error => error
@data = error.decoded_data
raise
end
end
self
end | [
"def",
"decode!",
"self",
".",
"decrypt!",
"if",
"self",
".",
"is_a?",
"(",
"Encryption",
"::",
"EncryptedStream",
")",
"return",
"if",
"decoded?",
"filters",
"=",
"self",
".",
"filters",
"dparams",
"=",
"decode_params",
"@data",
"=",
"@encoded_data",
".",
"dup",
"@data",
".",
"freeze",
"filters",
".",
"each_with_index",
"do",
"|",
"filter",
",",
"layer",
"|",
"params",
"=",
"dparams",
"[",
"layer",
"]",
".",
"is_a?",
"(",
"Dictionary",
")",
"?",
"dparams",
"[",
"layer",
"]",
":",
"{",
"}",
"# Handle Crypt filters.",
"if",
"filter",
"==",
":Crypt",
"raise",
"Filter",
"::",
"Error",
",",
"\"Crypt filter must be the first filter\"",
"unless",
"layer",
".",
"zero?",
"# Skip the Crypt filter.",
"next",
"end",
"begin",
"@data",
"=",
"decode_data",
"(",
"@data",
",",
"filter",
",",
"params",
")",
"rescue",
"Filter",
"::",
"Error",
"=>",
"error",
"@data",
"=",
"error",
".",
"decoded_data",
"raise",
"end",
"end",
"self",
"end"
] | Uncompress the stream data. | [
"Uncompress",
"the",
"stream",
"data",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/stream.rb#L274-L304 | train |
gdelugre/origami | lib/origami/stream.rb | Origami.Stream.encode! | def encode!
return if encoded?
filters = self.filters
dparams = decode_params
@encoded_data = @data.dup
(filters.length - 1).downto(0) do |layer|
params = dparams[layer].is_a?(Dictionary) ? dparams[layer] : {}
filter = filters[layer]
# Handle Crypt filters.
if filter == :Crypt
raise Filter::Error, "Crypt filter must be the first filter" unless layer.zero?
# Skip the Crypt filter.
next
end
@encoded_data = encode_data(@encoded_data, filter, params)
end
self.Length = @encoded_data.length
self
end | ruby | def encode!
return if encoded?
filters = self.filters
dparams = decode_params
@encoded_data = @data.dup
(filters.length - 1).downto(0) do |layer|
params = dparams[layer].is_a?(Dictionary) ? dparams[layer] : {}
filter = filters[layer]
# Handle Crypt filters.
if filter == :Crypt
raise Filter::Error, "Crypt filter must be the first filter" unless layer.zero?
# Skip the Crypt filter.
next
end
@encoded_data = encode_data(@encoded_data, filter, params)
end
self.Length = @encoded_data.length
self
end | [
"def",
"encode!",
"return",
"if",
"encoded?",
"filters",
"=",
"self",
".",
"filters",
"dparams",
"=",
"decode_params",
"@encoded_data",
"=",
"@data",
".",
"dup",
"(",
"filters",
".",
"length",
"-",
"1",
")",
".",
"downto",
"(",
"0",
")",
"do",
"|",
"layer",
"|",
"params",
"=",
"dparams",
"[",
"layer",
"]",
".",
"is_a?",
"(",
"Dictionary",
")",
"?",
"dparams",
"[",
"layer",
"]",
":",
"{",
"}",
"filter",
"=",
"filters",
"[",
"layer",
"]",
"# Handle Crypt filters.",
"if",
"filter",
"==",
":Crypt",
"raise",
"Filter",
"::",
"Error",
",",
"\"Crypt filter must be the first filter\"",
"unless",
"layer",
".",
"zero?",
"# Skip the Crypt filter.",
"next",
"end",
"@encoded_data",
"=",
"encode_data",
"(",
"@encoded_data",
",",
"filter",
",",
"params",
")",
"end",
"self",
".",
"Length",
"=",
"@encoded_data",
".",
"length",
"self",
"end"
] | Compress the stream data. | [
"Compress",
"the",
"stream",
"data",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/stream.rb#L309-L334 | train |
gdelugre/origami | lib/origami/stream.rb | Origami.ObjectStream.import_object_from_document | def import_object_from_document(object)
obj_doc = object.document
# Remove the previous instance if the object is indirect to avoid duplicates.
if obj_doc.equal?(@document)
@document.delete_object(object.reference) if object.indirect?
# Otherwise, create a exported version of the object.
else
object = object.export
end
object
end | ruby | def import_object_from_document(object)
obj_doc = object.document
# Remove the previous instance if the object is indirect to avoid duplicates.
if obj_doc.equal?(@document)
@document.delete_object(object.reference) if object.indirect?
# Otherwise, create a exported version of the object.
else
object = object.export
end
object
end | [
"def",
"import_object_from_document",
"(",
"object",
")",
"obj_doc",
"=",
"object",
".",
"document",
"# Remove the previous instance if the object is indirect to avoid duplicates.",
"if",
"obj_doc",
".",
"equal?",
"(",
"@document",
")",
"@document",
".",
"delete_object",
"(",
"object",
".",
"reference",
")",
"if",
"object",
".",
"indirect?",
"# Otherwise, create a exported version of the object.",
"else",
"object",
"=",
"object",
".",
"export",
"end",
"object",
"end"
] | Preprocess the object in case it already belongs to a document.
If the document is the same as the current object stream, remove the duplicate object from our document.
If the object comes from another document, use the export method to create a version without references. | [
"Preprocess",
"the",
"object",
"in",
"case",
"it",
"already",
"belongs",
"to",
"a",
"document",
".",
"If",
"the",
"document",
"is",
"the",
"same",
"as",
"the",
"current",
"object",
"stream",
"remove",
"the",
"duplicate",
"object",
"from",
"our",
"document",
".",
"If",
"the",
"object",
"comes",
"from",
"another",
"document",
"use",
"the",
"export",
"method",
"to",
"create",
"a",
"version",
"without",
"references",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/stream.rb#L638-L651 | train |
gdelugre/origami | lib/origami/string.rb | Origami.String.to_utf8 | def to_utf8
detect_encoding
utf16 = self.encoding.to_utf16be(self.value)
utf16.slice!(0, Encoding::UTF16BE::BOM.size)
utf16.encode("utf-8", "utf-16be")
end | ruby | def to_utf8
detect_encoding
utf16 = self.encoding.to_utf16be(self.value)
utf16.slice!(0, Encoding::UTF16BE::BOM.size)
utf16.encode("utf-8", "utf-16be")
end | [
"def",
"to_utf8",
"detect_encoding",
"utf16",
"=",
"self",
".",
"encoding",
".",
"to_utf16be",
"(",
"self",
".",
"value",
")",
"utf16",
".",
"slice!",
"(",
"0",
",",
"Encoding",
"::",
"UTF16BE",
"::",
"BOM",
".",
"size",
")",
"utf16",
".",
"encode",
"(",
"\"utf-8\"",
",",
"\"utf-16be\"",
")",
"end"
] | Convert String object to an UTF8 encoded Ruby string. | [
"Convert",
"String",
"object",
"to",
"an",
"UTF8",
"encoded",
"Ruby",
"string",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/string.rb#L121-L128 | train |
gdelugre/origami | lib/origami/graphics/xobject.rb | Origami.ContentStream.draw_polygon | def draw_polygon(coords = [], attr = {})
load!
stroke_color = attr.fetch(:stroke_color, DEFAULT_STROKE_COLOR)
fill_color = attr.fetch(:fill_color, DEFAULT_FILL_COLOR)
line_cap = attr.fetch(:line_cap, DEFAULT_LINECAP)
line_join = attr.fetch(:line_join, DEFAULT_LINEJOIN)
line_width = attr.fetch(:line_width, DEFAULT_LINEWIDTH)
dash_pattern = attr.fetch(:dash, DEFAULT_DASHPATTERN)
stroke = attr[:stroke].nil? ? true : attr[:stroke]
fill = attr[:fill].nil? ? false : attr[:fill]
stroke = true if fill == false and stroke == false
set_fill_color(fill_color) if fill
set_stroke_color(stroke_color) if stroke
set_line_width(line_width)
set_line_cap(line_cap)
set_line_join(line_join)
set_dash_pattern(dash_pattern)
if @canvas.gs.text_state.is_in_text_object?
@instructions << PDF::Instruction.new('ET').render(@canvas)
end
unless coords.size < 1
x,y = coords.slice!(0)
@instructions << PDF::Instruction.new('m',x,y).render(@canvas)
coords.each do |px,py|
@instructions << PDF::Instruction.new('l',px,py).render(@canvas)
end
@instructions << (i =
if stroke and not fill
PDF::Instruction.new('s')
elsif fill and not stroke
PDF::Instruction.new('f')
elsif fill and stroke
PDF::Instruction.new('b')
end
)
i.render(@canvas)
end
self
end | ruby | def draw_polygon(coords = [], attr = {})
load!
stroke_color = attr.fetch(:stroke_color, DEFAULT_STROKE_COLOR)
fill_color = attr.fetch(:fill_color, DEFAULT_FILL_COLOR)
line_cap = attr.fetch(:line_cap, DEFAULT_LINECAP)
line_join = attr.fetch(:line_join, DEFAULT_LINEJOIN)
line_width = attr.fetch(:line_width, DEFAULT_LINEWIDTH)
dash_pattern = attr.fetch(:dash, DEFAULT_DASHPATTERN)
stroke = attr[:stroke].nil? ? true : attr[:stroke]
fill = attr[:fill].nil? ? false : attr[:fill]
stroke = true if fill == false and stroke == false
set_fill_color(fill_color) if fill
set_stroke_color(stroke_color) if stroke
set_line_width(line_width)
set_line_cap(line_cap)
set_line_join(line_join)
set_dash_pattern(dash_pattern)
if @canvas.gs.text_state.is_in_text_object?
@instructions << PDF::Instruction.new('ET').render(@canvas)
end
unless coords.size < 1
x,y = coords.slice!(0)
@instructions << PDF::Instruction.new('m',x,y).render(@canvas)
coords.each do |px,py|
@instructions << PDF::Instruction.new('l',px,py).render(@canvas)
end
@instructions << (i =
if stroke and not fill
PDF::Instruction.new('s')
elsif fill and not stroke
PDF::Instruction.new('f')
elsif fill and stroke
PDF::Instruction.new('b')
end
)
i.render(@canvas)
end
self
end | [
"def",
"draw_polygon",
"(",
"coords",
"=",
"[",
"]",
",",
"attr",
"=",
"{",
"}",
")",
"load!",
"stroke_color",
"=",
"attr",
".",
"fetch",
"(",
":stroke_color",
",",
"DEFAULT_STROKE_COLOR",
")",
"fill_color",
"=",
"attr",
".",
"fetch",
"(",
":fill_color",
",",
"DEFAULT_FILL_COLOR",
")",
"line_cap",
"=",
"attr",
".",
"fetch",
"(",
":line_cap",
",",
"DEFAULT_LINECAP",
")",
"line_join",
"=",
"attr",
".",
"fetch",
"(",
":line_join",
",",
"DEFAULT_LINEJOIN",
")",
"line_width",
"=",
"attr",
".",
"fetch",
"(",
":line_width",
",",
"DEFAULT_LINEWIDTH",
")",
"dash_pattern",
"=",
"attr",
".",
"fetch",
"(",
":dash",
",",
"DEFAULT_DASHPATTERN",
")",
"stroke",
"=",
"attr",
"[",
":stroke",
"]",
".",
"nil?",
"?",
"true",
":",
"attr",
"[",
":stroke",
"]",
"fill",
"=",
"attr",
"[",
":fill",
"]",
".",
"nil?",
"?",
"false",
":",
"attr",
"[",
":fill",
"]",
"stroke",
"=",
"true",
"if",
"fill",
"==",
"false",
"and",
"stroke",
"==",
"false",
"set_fill_color",
"(",
"fill_color",
")",
"if",
"fill",
"set_stroke_color",
"(",
"stroke_color",
")",
"if",
"stroke",
"set_line_width",
"(",
"line_width",
")",
"set_line_cap",
"(",
"line_cap",
")",
"set_line_join",
"(",
"line_join",
")",
"set_dash_pattern",
"(",
"dash_pattern",
")",
"if",
"@canvas",
".",
"gs",
".",
"text_state",
".",
"is_in_text_object?",
"@instructions",
"<<",
"PDF",
"::",
"Instruction",
".",
"new",
"(",
"'ET'",
")",
".",
"render",
"(",
"@canvas",
")",
"end",
"unless",
"coords",
".",
"size",
"<",
"1",
"x",
",",
"y",
"=",
"coords",
".",
"slice!",
"(",
"0",
")",
"@instructions",
"<<",
"PDF",
"::",
"Instruction",
".",
"new",
"(",
"'m'",
",",
"x",
",",
"y",
")",
".",
"render",
"(",
"@canvas",
")",
"coords",
".",
"each",
"do",
"|",
"px",
",",
"py",
"|",
"@instructions",
"<<",
"PDF",
"::",
"Instruction",
".",
"new",
"(",
"'l'",
",",
"px",
",",
"py",
")",
".",
"render",
"(",
"@canvas",
")",
"end",
"@instructions",
"<<",
"(",
"i",
"=",
"if",
"stroke",
"and",
"not",
"fill",
"PDF",
"::",
"Instruction",
".",
"new",
"(",
"'s'",
")",
"elsif",
"fill",
"and",
"not",
"stroke",
"PDF",
"::",
"Instruction",
".",
"new",
"(",
"'f'",
")",
"elsif",
"fill",
"and",
"stroke",
"PDF",
"::",
"Instruction",
".",
"new",
"(",
"'b'",
")",
"end",
")",
"i",
".",
"render",
"(",
"@canvas",
")",
"end",
"self",
"end"
] | Draw a polygon from a array of coordinates. | [
"Draw",
"a",
"polygon",
"from",
"a",
"array",
"of",
"coordinates",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/graphics/xobject.rb#L96-L144 | train |
gdelugre/origami | lib/origami/object.rb | Origami.StandardObject.version_required | def version_required #:nodoc:
max = [ "1.0", 0 ]
self.each_key do |field|
attributes = self.class.fields[field.value]
if attributes.nil?
STDERR.puts "Warning: object #{self.class} has undocumented field #{field.value}"
next
end
version = attributes[:Version] || '1.0'
level = attributes[:ExtensionLevel] || 0
current = [ version, level ]
max = [ max, current, self[field.value].version_required ].max
end
max
end | ruby | def version_required #:nodoc:
max = [ "1.0", 0 ]
self.each_key do |field|
attributes = self.class.fields[field.value]
if attributes.nil?
STDERR.puts "Warning: object #{self.class} has undocumented field #{field.value}"
next
end
version = attributes[:Version] || '1.0'
level = attributes[:ExtensionLevel] || 0
current = [ version, level ]
max = [ max, current, self[field.value].version_required ].max
end
max
end | [
"def",
"version_required",
"#:nodoc:",
"max",
"=",
"[",
"\"1.0\"",
",",
"0",
"]",
"self",
".",
"each_key",
"do",
"|",
"field",
"|",
"attributes",
"=",
"self",
".",
"class",
".",
"fields",
"[",
"field",
".",
"value",
"]",
"if",
"attributes",
".",
"nil?",
"STDERR",
".",
"puts",
"\"Warning: object #{self.class} has undocumented field #{field.value}\"",
"next",
"end",
"version",
"=",
"attributes",
"[",
":Version",
"]",
"||",
"'1.0'",
"level",
"=",
"attributes",
"[",
":ExtensionLevel",
"]",
"||",
"0",
"current",
"=",
"[",
"version",
",",
"level",
"]",
"max",
"=",
"[",
"max",
",",
"current",
",",
"self",
"[",
"field",
".",
"value",
"]",
".",
"version_required",
"]",
".",
"max",
"end",
"max",
"end"
] | Returns the version and level required by the current Object. | [
"Returns",
"the",
"version",
"and",
"level",
"required",
"by",
"the",
"current",
"Object",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/object.rb#L263-L281 | train |
gdelugre/origami | lib/origami/object.rb | Origami.Object.set_indirect | def set_indirect(bool)
unless bool == true or bool == false
raise TypeError, "The argument must be boolean"
end
if bool == false
@no = @generation = 0
@document = nil
@file_offset = nil
end
@indirect = bool
self
end | ruby | def set_indirect(bool)
unless bool == true or bool == false
raise TypeError, "The argument must be boolean"
end
if bool == false
@no = @generation = 0
@document = nil
@file_offset = nil
end
@indirect = bool
self
end | [
"def",
"set_indirect",
"(",
"bool",
")",
"unless",
"bool",
"==",
"true",
"or",
"bool",
"==",
"false",
"raise",
"TypeError",
",",
"\"The argument must be boolean\"",
"end",
"if",
"bool",
"==",
"false",
"@no",
"=",
"@generation",
"=",
"0",
"@document",
"=",
"nil",
"@file_offset",
"=",
"nil",
"end",
"@indirect",
"=",
"bool",
"self",
"end"
] | Creates a new PDF Object.
Sets whether the object is indirect or not.
Indirect objects are allocated numbers at build time. | [
"Creates",
"a",
"new",
"PDF",
"Object",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/object.rb#L409-L422 | train |
gdelugre/origami | lib/origami/object.rb | Origami.Object.copy | def copy
saved_doc = @document
saved_parent = @parent
@document = @parent = nil # do not process parent object and document in the copy
# Perform the recursive copy (quite dirty).
copyobj = Marshal.load(Marshal.dump(self))
# restore saved values
@document = saved_doc
@parent = saved_parent
copyobj.set_document(saved_doc) if copyobj.indirect?
copyobj.parent = parent
copyobj
end | ruby | def copy
saved_doc = @document
saved_parent = @parent
@document = @parent = nil # do not process parent object and document in the copy
# Perform the recursive copy (quite dirty).
copyobj = Marshal.load(Marshal.dump(self))
# restore saved values
@document = saved_doc
@parent = saved_parent
copyobj.set_document(saved_doc) if copyobj.indirect?
copyobj.parent = parent
copyobj
end | [
"def",
"copy",
"saved_doc",
"=",
"@document",
"saved_parent",
"=",
"@parent",
"@document",
"=",
"@parent",
"=",
"nil",
"# do not process parent object and document in the copy",
"# Perform the recursive copy (quite dirty).",
"copyobj",
"=",
"Marshal",
".",
"load",
"(",
"Marshal",
".",
"dump",
"(",
"self",
")",
")",
"# restore saved values",
"@document",
"=",
"saved_doc",
"@parent",
"=",
"saved_parent",
"copyobj",
".",
"set_document",
"(",
"saved_doc",
")",
"if",
"copyobj",
".",
"indirect?",
"copyobj",
".",
"parent",
"=",
"parent",
"copyobj",
"end"
] | Deep copy of an object. | [
"Deep",
"copy",
"of",
"an",
"object",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/object.rb#L457-L474 | train |
gdelugre/origami | lib/origami/object.rb | Origami.Object.cast_to | def cast_to(type, parser = nil)
assert_cast_type(type)
cast = type.new(self.copy, parser)
cast.file_offset = @file_offset
transfer_attributes(cast)
end | ruby | def cast_to(type, parser = nil)
assert_cast_type(type)
cast = type.new(self.copy, parser)
cast.file_offset = @file_offset
transfer_attributes(cast)
end | [
"def",
"cast_to",
"(",
"type",
",",
"parser",
"=",
"nil",
")",
"assert_cast_type",
"(",
"type",
")",
"cast",
"=",
"type",
".",
"new",
"(",
"self",
".",
"copy",
",",
"parser",
")",
"cast",
".",
"file_offset",
"=",
"@file_offset",
"transfer_attributes",
"(",
"cast",
")",
"end"
] | Casts an object to a new type. | [
"Casts",
"an",
"object",
"to",
"a",
"new",
"type",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/object.rb#L479-L486 | train |
gdelugre/origami | lib/origami/object.rb | Origami.Object.reference | def reference
raise InvalidObjectError, "Cannot reference a direct object" unless self.indirect?
ref = Reference.new(@no, @generation)
ref.parent = self
ref
end | ruby | def reference
raise InvalidObjectError, "Cannot reference a direct object" unless self.indirect?
ref = Reference.new(@no, @generation)
ref.parent = self
ref
end | [
"def",
"reference",
"raise",
"InvalidObjectError",
",",
"\"Cannot reference a direct object\"",
"unless",
"self",
".",
"indirect?",
"ref",
"=",
"Reference",
".",
"new",
"(",
"@no",
",",
"@generation",
")",
"ref",
".",
"parent",
"=",
"self",
"ref",
"end"
] | Returns an indirect reference to this object. | [
"Returns",
"an",
"indirect",
"reference",
"to",
"this",
"object",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/object.rb#L491-L498 | train |
gdelugre/origami | lib/origami/object.rb | Origami.Object.xrefs | def xrefs
raise InvalidObjectError, "Cannot find xrefs to a direct object" unless self.indirect?
raise InvalidObjectError, "Not attached to any document" if self.document.nil?
@document.each_object(compressed: true)
.flat_map { |object|
case object
when Stream
object.dictionary.xref_cache[self.reference]
when ObjectCache
object.xref_cache[self.reference]
end
}
.compact!
end | ruby | def xrefs
raise InvalidObjectError, "Cannot find xrefs to a direct object" unless self.indirect?
raise InvalidObjectError, "Not attached to any document" if self.document.nil?
@document.each_object(compressed: true)
.flat_map { |object|
case object
when Stream
object.dictionary.xref_cache[self.reference]
when ObjectCache
object.xref_cache[self.reference]
end
}
.compact!
end | [
"def",
"xrefs",
"raise",
"InvalidObjectError",
",",
"\"Cannot find xrefs to a direct object\"",
"unless",
"self",
".",
"indirect?",
"raise",
"InvalidObjectError",
",",
"\"Not attached to any document\"",
"if",
"self",
".",
"document",
".",
"nil?",
"@document",
".",
"each_object",
"(",
"compressed",
":",
"true",
")",
".",
"flat_map",
"{",
"|",
"object",
"|",
"case",
"object",
"when",
"Stream",
"object",
".",
"dictionary",
".",
"xref_cache",
"[",
"self",
".",
"reference",
"]",
"when",
"ObjectCache",
"object",
".",
"xref_cache",
"[",
"self",
".",
"reference",
"]",
"end",
"}",
".",
"compact!",
"end"
] | Returns an array of references pointing to the current object. | [
"Returns",
"an",
"array",
"of",
"references",
"pointing",
"to",
"the",
"current",
"object",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/object.rb#L503-L517 | train |
gdelugre/origami | lib/origami/object.rb | Origami.Object.export | def export
exported_obj = self.logicalize
exported_obj.no = exported_obj.generation = 0
exported_obj.set_document(nil) if exported_obj.indirect?
exported_obj.parent = nil
exported_obj.xref_cache.clear
exported_obj
end | ruby | def export
exported_obj = self.logicalize
exported_obj.no = exported_obj.generation = 0
exported_obj.set_document(nil) if exported_obj.indirect?
exported_obj.parent = nil
exported_obj.xref_cache.clear
exported_obj
end | [
"def",
"export",
"exported_obj",
"=",
"self",
".",
"logicalize",
"exported_obj",
".",
"no",
"=",
"exported_obj",
".",
"generation",
"=",
"0",
"exported_obj",
".",
"set_document",
"(",
"nil",
")",
"if",
"exported_obj",
".",
"indirect?",
"exported_obj",
".",
"parent",
"=",
"nil",
"exported_obj",
".",
"xref_cache",
".",
"clear",
"exported_obj",
"end"
] | Creates an exportable version of current object.
The exportable version is a copy of _self_ with solved references, no owning PDF and no parent.
References to Catalog or PageTreeNode objects have been destroyed.
When exported, an object can be moved into another document without hassle. | [
"Creates",
"an",
"exportable",
"version",
"of",
"current",
"object",
".",
"The",
"exportable",
"version",
"is",
"a",
"copy",
"of",
"_self_",
"with",
"solved",
"references",
"no",
"owning",
"PDF",
"and",
"no",
"parent",
".",
"References",
"to",
"Catalog",
"or",
"PageTreeNode",
"objects",
"have",
"been",
"destroyed",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/object.rb#L526-L534 | train |
gdelugre/origami | lib/origami/object.rb | Origami.Object.type | def type
name = (self.class.name or self.class.superclass.name or self.native_type.name)
name.split("::").last.to_sym
end | ruby | def type
name = (self.class.name or self.class.superclass.name or self.native_type.name)
name.split("::").last.to_sym
end | [
"def",
"type",
"name",
"=",
"(",
"self",
".",
"class",
".",
"name",
"or",
"self",
".",
"class",
".",
"superclass",
".",
"name",
"or",
"self",
".",
"native_type",
".",
"name",
")",
"name",
".",
"split",
"(",
"\"::\"",
")",
".",
"last",
".",
"to_sym",
"end"
] | Returns the symbol type of this Object. | [
"Returns",
"the",
"symbol",
"type",
"of",
"this",
"Object",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/object.rb#L681-L685 | train |
gdelugre/origami | lib/origami/object.rb | Origami.Object.transfer_attributes | def transfer_attributes(target)
target.no, target.generation = @no, @generation
target.parent = @parent
if self.indirect?
target.set_indirect(true)
target.set_document(@document)
end
target
end | ruby | def transfer_attributes(target)
target.no, target.generation = @no, @generation
target.parent = @parent
if self.indirect?
target.set_indirect(true)
target.set_document(@document)
end
target
end | [
"def",
"transfer_attributes",
"(",
"target",
")",
"target",
".",
"no",
",",
"target",
".",
"generation",
"=",
"@no",
",",
"@generation",
"target",
".",
"parent",
"=",
"@parent",
"if",
"self",
".",
"indirect?",
"target",
".",
"set_indirect",
"(",
"true",
")",
"target",
".",
"set_document",
"(",
"@document",
")",
"end",
"target",
"end"
] | Copy the attributes of the current object to another object.
Copied attributes do not include the file offset. | [
"Copy",
"the",
"attributes",
"of",
"the",
"current",
"object",
"to",
"another",
"object",
".",
"Copied",
"attributes",
"do",
"not",
"include",
"the",
"file",
"offset",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/object.rb#L716-L725 | train |
gdelugre/origami | lib/origami/object.rb | Origami.Object.resolve_all_references | def resolve_all_references(obj, browsed: [], cache: {})
return obj if browsed.include?(obj)
browsed.push(obj)
if obj.is_a?(ObjectStream)
obj.each do |subobj|
resolve_all_references(subobj, browsed: browsed, cache: cache)
end
end
if obj.is_a?(Stream)
resolve_all_references(obj.dictionary, browsed: browsed, cache: cache)
end
if obj.is_a?(CompoundObject)
obj.update_values! do |subobj|
if subobj.is_a?(Reference)
subobj = (cache[subobj] ||= subobj.solve.copy)
subobj.no = subobj.generation = 0
subobj.parent = obj
end
resolve_all_references(subobj, browsed: browsed, cache: cache)
end
end
obj
end | ruby | def resolve_all_references(obj, browsed: [], cache: {})
return obj if browsed.include?(obj)
browsed.push(obj)
if obj.is_a?(ObjectStream)
obj.each do |subobj|
resolve_all_references(subobj, browsed: browsed, cache: cache)
end
end
if obj.is_a?(Stream)
resolve_all_references(obj.dictionary, browsed: browsed, cache: cache)
end
if obj.is_a?(CompoundObject)
obj.update_values! do |subobj|
if subobj.is_a?(Reference)
subobj = (cache[subobj] ||= subobj.solve.copy)
subobj.no = subobj.generation = 0
subobj.parent = obj
end
resolve_all_references(subobj, browsed: browsed, cache: cache)
end
end
obj
end | [
"def",
"resolve_all_references",
"(",
"obj",
",",
"browsed",
":",
"[",
"]",
",",
"cache",
":",
"{",
"}",
")",
"return",
"obj",
"if",
"browsed",
".",
"include?",
"(",
"obj",
")",
"browsed",
".",
"push",
"(",
"obj",
")",
"if",
"obj",
".",
"is_a?",
"(",
"ObjectStream",
")",
"obj",
".",
"each",
"do",
"|",
"subobj",
"|",
"resolve_all_references",
"(",
"subobj",
",",
"browsed",
":",
"browsed",
",",
"cache",
":",
"cache",
")",
"end",
"end",
"if",
"obj",
".",
"is_a?",
"(",
"Stream",
")",
"resolve_all_references",
"(",
"obj",
".",
"dictionary",
",",
"browsed",
":",
"browsed",
",",
"cache",
":",
"cache",
")",
"end",
"if",
"obj",
".",
"is_a?",
"(",
"CompoundObject",
")",
"obj",
".",
"update_values!",
"do",
"|",
"subobj",
"|",
"if",
"subobj",
".",
"is_a?",
"(",
"Reference",
")",
"subobj",
"=",
"(",
"cache",
"[",
"subobj",
"]",
"||=",
"subobj",
".",
"solve",
".",
"copy",
")",
"subobj",
".",
"no",
"=",
"subobj",
".",
"generation",
"=",
"0",
"subobj",
".",
"parent",
"=",
"obj",
"end",
"resolve_all_references",
"(",
"subobj",
",",
"browsed",
":",
"browsed",
",",
"cache",
":",
"cache",
")",
"end",
"end",
"obj",
"end"
] | Replace all references of an object by their actual object value. | [
"Replace",
"all",
"references",
"of",
"an",
"object",
"by",
"their",
"actual",
"object",
"value",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/object.rb#L730-L757 | train |
gdelugre/origami | lib/origami/parser.rb | Origami.Parser.try_object_promotion | def try_object_promotion(obj)
return obj unless Origami::OPTIONS[:enable_type_propagation] and @deferred_casts.key?(obj.reference)
types = @deferred_casts[obj.reference]
types = [ types ] unless types.is_a?(::Array)
# Promote object if a compatible type is found.
cast_type = types.find {|type| type < obj.class }
if cast_type
obj = obj.cast_to(cast_type, self)
else
obj
end
end | ruby | def try_object_promotion(obj)
return obj unless Origami::OPTIONS[:enable_type_propagation] and @deferred_casts.key?(obj.reference)
types = @deferred_casts[obj.reference]
types = [ types ] unless types.is_a?(::Array)
# Promote object if a compatible type is found.
cast_type = types.find {|type| type < obj.class }
if cast_type
obj = obj.cast_to(cast_type, self)
else
obj
end
end | [
"def",
"try_object_promotion",
"(",
"obj",
")",
"return",
"obj",
"unless",
"Origami",
"::",
"OPTIONS",
"[",
":enable_type_propagation",
"]",
"and",
"@deferred_casts",
".",
"key?",
"(",
"obj",
".",
"reference",
")",
"types",
"=",
"@deferred_casts",
"[",
"obj",
".",
"reference",
"]",
"types",
"=",
"[",
"types",
"]",
"unless",
"types",
".",
"is_a?",
"(",
"::",
"Array",
")",
"# Promote object if a compatible type is found.",
"cast_type",
"=",
"types",
".",
"find",
"{",
"|",
"type",
"|",
"type",
"<",
"obj",
".",
"class",
"}",
"if",
"cast_type",
"obj",
"=",
"obj",
".",
"cast_to",
"(",
"cast_type",
",",
"self",
")",
"else",
"obj",
"end",
"end"
] | Attempt to promote an object using the deferred casts. | [
"Attempt",
"to",
"promote",
"an",
"object",
"using",
"the",
"deferred",
"casts",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/parser.rb#L226-L239 | train |
gdelugre/origami | lib/origami/signature.rb | Origami.PDF.signed? | def signed?
begin
self.Catalog.AcroForm.is_a?(Dictionary) and
self.Catalog.AcroForm.SigFlags.is_a?(Integer) and
(self.Catalog.AcroForm.SigFlags & InteractiveForm::SigFlags::SIGNATURES_EXIST != 0)
rescue InvalidReferenceError
false
end
end | ruby | def signed?
begin
self.Catalog.AcroForm.is_a?(Dictionary) and
self.Catalog.AcroForm.SigFlags.is_a?(Integer) and
(self.Catalog.AcroForm.SigFlags & InteractiveForm::SigFlags::SIGNATURES_EXIST != 0)
rescue InvalidReferenceError
false
end
end | [
"def",
"signed?",
"begin",
"self",
".",
"Catalog",
".",
"AcroForm",
".",
"is_a?",
"(",
"Dictionary",
")",
"and",
"self",
".",
"Catalog",
".",
"AcroForm",
".",
"SigFlags",
".",
"is_a?",
"(",
"Integer",
")",
"and",
"(",
"self",
".",
"Catalog",
".",
"AcroForm",
".",
"SigFlags",
"&",
"InteractiveForm",
"::",
"SigFlags",
"::",
"SIGNATURES_EXIST",
"!=",
"0",
")",
"rescue",
"InvalidReferenceError",
"false",
"end",
"end"
] | Returns whether the document contains a digital signature. | [
"Returns",
"whether",
"the",
"document",
"contains",
"a",
"digital",
"signature",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/signature.rb#L194-L202 | train |
gdelugre/origami | lib/origami/signature.rb | Origami.PDF.extract_signed_data | def extract_signed_data(digsig)
# Computes the boundaries of the Contents field.
start_sig = digsig[:Contents].file_offset
stream = StringScanner.new(self.original_data)
stream.pos = digsig[:Contents].file_offset
Object.typeof(stream).parse(stream)
end_sig = stream.pos
stream.terminate
r1, r2 = digsig.ranges
if r1.begin != 0 or
r2.end != self.original_data.size or
r1.end != start_sig or
r2.begin != end_sig
raise SignatureError, "Invalid signature byte range"
end
self.original_data[r1] + self.original_data[r2]
end | ruby | def extract_signed_data(digsig)
# Computes the boundaries of the Contents field.
start_sig = digsig[:Contents].file_offset
stream = StringScanner.new(self.original_data)
stream.pos = digsig[:Contents].file_offset
Object.typeof(stream).parse(stream)
end_sig = stream.pos
stream.terminate
r1, r2 = digsig.ranges
if r1.begin != 0 or
r2.end != self.original_data.size or
r1.end != start_sig or
r2.begin != end_sig
raise SignatureError, "Invalid signature byte range"
end
self.original_data[r1] + self.original_data[r2]
end | [
"def",
"extract_signed_data",
"(",
"digsig",
")",
"# Computes the boundaries of the Contents field.",
"start_sig",
"=",
"digsig",
"[",
":Contents",
"]",
".",
"file_offset",
"stream",
"=",
"StringScanner",
".",
"new",
"(",
"self",
".",
"original_data",
")",
"stream",
".",
"pos",
"=",
"digsig",
"[",
":Contents",
"]",
".",
"file_offset",
"Object",
".",
"typeof",
"(",
"stream",
")",
".",
"parse",
"(",
"stream",
")",
"end_sig",
"=",
"stream",
".",
"pos",
"stream",
".",
"terminate",
"r1",
",",
"r2",
"=",
"digsig",
".",
"ranges",
"if",
"r1",
".",
"begin",
"!=",
"0",
"or",
"r2",
".",
"end",
"!=",
"self",
".",
"original_data",
".",
"size",
"or",
"r1",
".",
"end",
"!=",
"start_sig",
"or",
"r2",
".",
"begin",
"!=",
"end_sig",
"raise",
"SignatureError",
",",
"\"Invalid signature byte range\"",
"end",
"self",
".",
"original_data",
"[",
"r1",
"]",
"+",
"self",
".",
"original_data",
"[",
"r2",
"]",
"end"
] | Verifies the ByteRange field of a digital signature and returned the signed data. | [
"Verifies",
"the",
"ByteRange",
"field",
"of",
"a",
"digital",
"signature",
"and",
"returned",
"the",
"signed",
"data",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/signature.rb#L314-L334 | train |
gdelugre/origami | lib/origami/compound.rb | Origami.CompoundObject.update_values | def update_values(&b)
return enum_for(__method__) unless block_given?
return self.class.new self.transform_values(&b) if self.respond_to?(:transform_values)
return self.class.new self.map(&b) if self.respond_to?(:map)
raise NotImplementedError, "This object does not implement this method"
end | ruby | def update_values(&b)
return enum_for(__method__) unless block_given?
return self.class.new self.transform_values(&b) if self.respond_to?(:transform_values)
return self.class.new self.map(&b) if self.respond_to?(:map)
raise NotImplementedError, "This object does not implement this method"
end | [
"def",
"update_values",
"(",
"&",
"b",
")",
"return",
"enum_for",
"(",
"__method__",
")",
"unless",
"block_given?",
"return",
"self",
".",
"class",
".",
"new",
"self",
".",
"transform_values",
"(",
"b",
")",
"if",
"self",
".",
"respond_to?",
"(",
":transform_values",
")",
"return",
"self",
".",
"class",
".",
"new",
"self",
".",
"map",
"(",
"b",
")",
"if",
"self",
".",
"respond_to?",
"(",
":map",
")",
"raise",
"NotImplementedError",
",",
"\"This object does not implement this method\"",
"end"
] | Returns a new compound object with updated values based on the provided block. | [
"Returns",
"a",
"new",
"compound",
"object",
"with",
"updated",
"values",
"based",
"on",
"the",
"provided",
"block",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/compound.rb#L127-L133 | train |
gdelugre/origami | lib/origami/compound.rb | Origami.CompoundObject.update_values! | def update_values!(&b)
return enum_for(__method__) unless block_given?
return self.transform_values!(&b) if self.respond_to?(:transform_values!)
return self.map!(&b) if self.respond_to?(:map!)
raise NotImplementedError, "This object does not implement this method"
end | ruby | def update_values!(&b)
return enum_for(__method__) unless block_given?
return self.transform_values!(&b) if self.respond_to?(:transform_values!)
return self.map!(&b) if self.respond_to?(:map!)
raise NotImplementedError, "This object does not implement this method"
end | [
"def",
"update_values!",
"(",
"&",
"b",
")",
"return",
"enum_for",
"(",
"__method__",
")",
"unless",
"block_given?",
"return",
"self",
".",
"transform_values!",
"(",
"b",
")",
"if",
"self",
".",
"respond_to?",
"(",
":transform_values!",
")",
"return",
"self",
".",
"map!",
"(",
"b",
")",
"if",
"self",
".",
"respond_to?",
"(",
":map!",
")",
"raise",
"NotImplementedError",
",",
"\"This object does not implement this method\"",
"end"
] | Modifies the compound object's values based on the provided block. | [
"Modifies",
"the",
"compound",
"object",
"s",
"values",
"based",
"on",
"the",
"provided",
"block",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/compound.rb#L138-L144 | train |
gdelugre/origami | lib/origami/linearization.rb | Origami.PDF.linearized? | def linearized?
begin
first_obj = @revisions.first.objects.min_by{|obj| obj.file_offset}
rescue
return false
end
@revisions.size > 1 and first_obj.is_a?(Dictionary) and first_obj.has_key? :Linearized
end | ruby | def linearized?
begin
first_obj = @revisions.first.objects.min_by{|obj| obj.file_offset}
rescue
return false
end
@revisions.size > 1 and first_obj.is_a?(Dictionary) and first_obj.has_key? :Linearized
end | [
"def",
"linearized?",
"begin",
"first_obj",
"=",
"@revisions",
".",
"first",
".",
"objects",
".",
"min_by",
"{",
"|",
"obj",
"|",
"obj",
".",
"file_offset",
"}",
"rescue",
"return",
"false",
"end",
"@revisions",
".",
"size",
">",
"1",
"and",
"first_obj",
".",
"is_a?",
"(",
"Dictionary",
")",
"and",
"first_obj",
".",
"has_key?",
":Linearized",
"end"
] | Returns whether the current document is linearized. | [
"Returns",
"whether",
"the",
"current",
"document",
"is",
"linearized",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/linearization.rb#L31-L39 | train |
gdelugre/origami | lib/origami/linearization.rb | Origami.PDF.delinearize! | def delinearize!
raise LinearizationError, 'Not a linearized document' unless self.linearized?
#
# Saves the first trailer.
#
prev_trailer = @revisions.first.trailer
linear_dict = @revisions.first.objects.min_by{|obj| obj.file_offset}
#
# Removes hint streams used by linearization.
#
delete_hint_streams(linear_dict)
#
# Update the trailer.
#
last_trailer = (@revisions.last.trailer ||= Trailer.new)
last_trailer.dictionary ||= Dictionary.new
if prev_trailer.dictionary?
last_trailer.dictionary =
last_trailer.dictionary.merge(prev_trailer.dictionary)
else
xrefstm = @revisions.last.xrefstm
raise LinearizationError,
'Cannot find trailer info while delinearizing document' unless xrefstm.is_a?(XRefStream)
last_trailer.dictionary[:Root] = xrefstm[:Root]
last_trailer.dictionary[:Encrypt] = xrefstm[:Encrypt]
last_trailer.dictionary[:Info] = xrefstm[:Info]
last_trailer.dictionary[:ID] = xrefstm[:ID]
end
#
# Remove all xrefs.
# Fix: Should be merged instead.
#
remove_xrefs
#
# Remove the linearization revision.
#
@revisions.first.body.delete(linear_dict.reference)
@revisions.last.body.merge! @revisions.first.body
remove_revision(0)
self
end | ruby | def delinearize!
raise LinearizationError, 'Not a linearized document' unless self.linearized?
#
# Saves the first trailer.
#
prev_trailer = @revisions.first.trailer
linear_dict = @revisions.first.objects.min_by{|obj| obj.file_offset}
#
# Removes hint streams used by linearization.
#
delete_hint_streams(linear_dict)
#
# Update the trailer.
#
last_trailer = (@revisions.last.trailer ||= Trailer.new)
last_trailer.dictionary ||= Dictionary.new
if prev_trailer.dictionary?
last_trailer.dictionary =
last_trailer.dictionary.merge(prev_trailer.dictionary)
else
xrefstm = @revisions.last.xrefstm
raise LinearizationError,
'Cannot find trailer info while delinearizing document' unless xrefstm.is_a?(XRefStream)
last_trailer.dictionary[:Root] = xrefstm[:Root]
last_trailer.dictionary[:Encrypt] = xrefstm[:Encrypt]
last_trailer.dictionary[:Info] = xrefstm[:Info]
last_trailer.dictionary[:ID] = xrefstm[:ID]
end
#
# Remove all xrefs.
# Fix: Should be merged instead.
#
remove_xrefs
#
# Remove the linearization revision.
#
@revisions.first.body.delete(linear_dict.reference)
@revisions.last.body.merge! @revisions.first.body
remove_revision(0)
self
end | [
"def",
"delinearize!",
"raise",
"LinearizationError",
",",
"'Not a linearized document'",
"unless",
"self",
".",
"linearized?",
"#",
"# Saves the first trailer.",
"#",
"prev_trailer",
"=",
"@revisions",
".",
"first",
".",
"trailer",
"linear_dict",
"=",
"@revisions",
".",
"first",
".",
"objects",
".",
"min_by",
"{",
"|",
"obj",
"|",
"obj",
".",
"file_offset",
"}",
"#",
"# Removes hint streams used by linearization.",
"#",
"delete_hint_streams",
"(",
"linear_dict",
")",
"#",
"# Update the trailer.",
"#",
"last_trailer",
"=",
"(",
"@revisions",
".",
"last",
".",
"trailer",
"||=",
"Trailer",
".",
"new",
")",
"last_trailer",
".",
"dictionary",
"||=",
"Dictionary",
".",
"new",
"if",
"prev_trailer",
".",
"dictionary?",
"last_trailer",
".",
"dictionary",
"=",
"last_trailer",
".",
"dictionary",
".",
"merge",
"(",
"prev_trailer",
".",
"dictionary",
")",
"else",
"xrefstm",
"=",
"@revisions",
".",
"last",
".",
"xrefstm",
"raise",
"LinearizationError",
",",
"'Cannot find trailer info while delinearizing document'",
"unless",
"xrefstm",
".",
"is_a?",
"(",
"XRefStream",
")",
"last_trailer",
".",
"dictionary",
"[",
":Root",
"]",
"=",
"xrefstm",
"[",
":Root",
"]",
"last_trailer",
".",
"dictionary",
"[",
":Encrypt",
"]",
"=",
"xrefstm",
"[",
":Encrypt",
"]",
"last_trailer",
".",
"dictionary",
"[",
":Info",
"]",
"=",
"xrefstm",
"[",
":Info",
"]",
"last_trailer",
".",
"dictionary",
"[",
":ID",
"]",
"=",
"xrefstm",
"[",
":ID",
"]",
"end",
"#",
"# Remove all xrefs.",
"# Fix: Should be merged instead.",
"#",
"remove_xrefs",
"#",
"# Remove the linearization revision.",
"#",
"@revisions",
".",
"first",
".",
"body",
".",
"delete",
"(",
"linear_dict",
".",
"reference",
")",
"@revisions",
".",
"last",
".",
"body",
".",
"merge!",
"@revisions",
".",
"first",
".",
"body",
"remove_revision",
"(",
"0",
")",
"self",
"end"
] | Tries to delinearize the document if it has been linearized.
This operation is xrefs destructive, should be fixed in the future to merge tables. | [
"Tries",
"to",
"delinearize",
"the",
"document",
"if",
"it",
"has",
"been",
"linearized",
".",
"This",
"operation",
"is",
"xrefs",
"destructive",
"should",
"be",
"fixed",
"in",
"the",
"future",
"to",
"merge",
"tables",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/linearization.rb#L45-L95 | train |
gdelugre/origami | lib/origami/linearization.rb | Origami.PDF.delete_hint_streams | def delete_hint_streams(linearization_dict)
hints = linearization_dict[:H]
return unless hints.is_a?(Array)
hints.each_slice(2) do |offset, _length|
next unless offset.is_a?(Integer)
stream = get_object_by_offset(offset)
delete_object(stream.reference) if stream.is_a?(Stream)
end
end | ruby | def delete_hint_streams(linearization_dict)
hints = linearization_dict[:H]
return unless hints.is_a?(Array)
hints.each_slice(2) do |offset, _length|
next unless offset.is_a?(Integer)
stream = get_object_by_offset(offset)
delete_object(stream.reference) if stream.is_a?(Stream)
end
end | [
"def",
"delete_hint_streams",
"(",
"linearization_dict",
")",
"hints",
"=",
"linearization_dict",
"[",
":H",
"]",
"return",
"unless",
"hints",
".",
"is_a?",
"(",
"Array",
")",
"hints",
".",
"each_slice",
"(",
"2",
")",
"do",
"|",
"offset",
",",
"_length",
"|",
"next",
"unless",
"offset",
".",
"is_a?",
"(",
"Integer",
")",
"stream",
"=",
"get_object_by_offset",
"(",
"offset",
")",
"delete_object",
"(",
"stream",
".",
"reference",
")",
"if",
"stream",
".",
"is_a?",
"(",
"Stream",
")",
"end",
"end"
] | Strip the document from Hint streams given a linearization dictionary. | [
"Strip",
"the",
"document",
"from",
"Hint",
"streams",
"given",
"a",
"linearization",
"dictionary",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/linearization.rb#L102-L112 | train |
gdelugre/origami | lib/origami/reference.rb | Origami.Reference.follow | def follow
doc = self.document
if doc.nil?
raise InvalidReferenceError, "Not attached to any document"
end
target = doc.get_object(self)
if target.nil? and not Origami::OPTIONS[:ignore_bad_references]
raise InvalidReferenceError, "Cannot resolve reference : #{self}"
end
target or Null.new
end | ruby | def follow
doc = self.document
if doc.nil?
raise InvalidReferenceError, "Not attached to any document"
end
target = doc.get_object(self)
if target.nil? and not Origami::OPTIONS[:ignore_bad_references]
raise InvalidReferenceError, "Cannot resolve reference : #{self}"
end
target or Null.new
end | [
"def",
"follow",
"doc",
"=",
"self",
".",
"document",
"if",
"doc",
".",
"nil?",
"raise",
"InvalidReferenceError",
",",
"\"Not attached to any document\"",
"end",
"target",
"=",
"doc",
".",
"get_object",
"(",
"self",
")",
"if",
"target",
".",
"nil?",
"and",
"not",
"Origami",
"::",
"OPTIONS",
"[",
":ignore_bad_references",
"]",
"raise",
"InvalidReferenceError",
",",
"\"Cannot resolve reference : #{self}\"",
"end",
"target",
"or",
"Null",
".",
"new",
"end"
] | Returns the object pointed to by the reference.
The reference must be part of a document.
Raises an InvalidReferenceError if the object cannot be found. | [
"Returns",
"the",
"object",
"pointed",
"to",
"by",
"the",
"reference",
".",
"The",
"reference",
"must",
"be",
"part",
"of",
"a",
"document",
".",
"Raises",
"an",
"InvalidReferenceError",
"if",
"the",
"object",
"cannot",
"be",
"found",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/reference.rb#L68-L82 | train |
gdelugre/origami | lib/origami/acroform.rb | Origami.PDF.create_form | def create_form(*fields)
acroform = self.Catalog.AcroForm ||= InteractiveForm.new.set_indirect(true)
self.add_fields(*fields)
acroform
end | ruby | def create_form(*fields)
acroform = self.Catalog.AcroForm ||= InteractiveForm.new.set_indirect(true)
self.add_fields(*fields)
acroform
end | [
"def",
"create_form",
"(",
"*",
"fields",
")",
"acroform",
"=",
"self",
".",
"Catalog",
".",
"AcroForm",
"||=",
"InteractiveForm",
".",
"new",
".",
"set_indirect",
"(",
"true",
")",
"self",
".",
"add_fields",
"(",
"fields",
")",
"acroform",
"end"
] | Creates a new AcroForm with specified fields. | [
"Creates",
"a",
"new",
"AcroForm",
"with",
"specified",
"fields",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/acroform.rb#L35-L40 | train |
gdelugre/origami | lib/origami/acroform.rb | Origami.PDF.each_field | def each_field
return enum_for(__method__) do
if self.form? and self.Catalog.AcroForm.Fields.is_a?(Array)
self.Catalog.AcroForm.Fields.length
else
0
end
end unless block_given?
if self.form? and self.Catalog.AcroForm.Fields.is_a?(Array)
self.Catalog.AcroForm.Fields.each do |field|
yield(field.solve)
end
end
end | ruby | def each_field
return enum_for(__method__) do
if self.form? and self.Catalog.AcroForm.Fields.is_a?(Array)
self.Catalog.AcroForm.Fields.length
else
0
end
end unless block_given?
if self.form? and self.Catalog.AcroForm.Fields.is_a?(Array)
self.Catalog.AcroForm.Fields.each do |field|
yield(field.solve)
end
end
end | [
"def",
"each_field",
"return",
"enum_for",
"(",
"__method__",
")",
"do",
"if",
"self",
".",
"form?",
"and",
"self",
".",
"Catalog",
".",
"AcroForm",
".",
"Fields",
".",
"is_a?",
"(",
"Array",
")",
"self",
".",
"Catalog",
".",
"AcroForm",
".",
"Fields",
".",
"length",
"else",
"0",
"end",
"end",
"unless",
"block_given?",
"if",
"self",
".",
"form?",
"and",
"self",
".",
"Catalog",
".",
"AcroForm",
".",
"Fields",
".",
"is_a?",
"(",
"Array",
")",
"self",
".",
"Catalog",
".",
"AcroForm",
".",
"Fields",
".",
"each",
"do",
"|",
"field",
"|",
"yield",
"(",
"field",
".",
"solve",
")",
"end",
"end",
"end"
] | Iterates over each Acroform Field. | [
"Iterates",
"over",
"each",
"Acroform",
"Field",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/acroform.rb#L68-L82 | train |
gdelugre/origami | lib/origami/encryption.rb | Origami.PDF.create_security_handler | def create_security_handler(version, revision, params)
# Ensure the document has an ID.
doc_id = (trailer_key(:ID) || generate_id).first
# Create the standard encryption dictionary.
handler = Encryption::Standard::Dictionary.new
handler.Filter = :Standard
handler.V = version
handler.R = revision
handler.Length = params[:key_size]
handler.P = -1 # params[:Permissions]
# Build the crypt filter dictionary.
if revision >= 4
handler.EncryptMetadata = params[:encrypt_metadata]
handler.CF = Dictionary.new
crypt_filter = Encryption::CryptFilterDictionary.new
crypt_filter.AuthEvent = :DocOpen
if revision == 4
crypt_filter.CFM = :AESV2
else
crypt_filter.CFM = :AESV3
end
crypt_filter.Length = params[:key_size] >> 3
handler.CF[:StdCF] = crypt_filter
handler.StmF = handler.StrF = :StdCF
end
user_passwd, owner_passwd = params[:user_passwd], params[:owner_passwd]
# Setup keys.
handler.set_passwords(owner_passwd, user_passwd, doc_id)
encryption_key = handler.compute_user_encryption_key(user_passwd, doc_id)
# Install the encryption dictionary to the document.
self.trailer.Encrypt = self << handler
[ handler, encryption_key ]
end | ruby | def create_security_handler(version, revision, params)
# Ensure the document has an ID.
doc_id = (trailer_key(:ID) || generate_id).first
# Create the standard encryption dictionary.
handler = Encryption::Standard::Dictionary.new
handler.Filter = :Standard
handler.V = version
handler.R = revision
handler.Length = params[:key_size]
handler.P = -1 # params[:Permissions]
# Build the crypt filter dictionary.
if revision >= 4
handler.EncryptMetadata = params[:encrypt_metadata]
handler.CF = Dictionary.new
crypt_filter = Encryption::CryptFilterDictionary.new
crypt_filter.AuthEvent = :DocOpen
if revision == 4
crypt_filter.CFM = :AESV2
else
crypt_filter.CFM = :AESV3
end
crypt_filter.Length = params[:key_size] >> 3
handler.CF[:StdCF] = crypt_filter
handler.StmF = handler.StrF = :StdCF
end
user_passwd, owner_passwd = params[:user_passwd], params[:owner_passwd]
# Setup keys.
handler.set_passwords(owner_passwd, user_passwd, doc_id)
encryption_key = handler.compute_user_encryption_key(user_passwd, doc_id)
# Install the encryption dictionary to the document.
self.trailer.Encrypt = self << handler
[ handler, encryption_key ]
end | [
"def",
"create_security_handler",
"(",
"version",
",",
"revision",
",",
"params",
")",
"# Ensure the document has an ID.",
"doc_id",
"=",
"(",
"trailer_key",
"(",
":ID",
")",
"||",
"generate_id",
")",
".",
"first",
"# Create the standard encryption dictionary.",
"handler",
"=",
"Encryption",
"::",
"Standard",
"::",
"Dictionary",
".",
"new",
"handler",
".",
"Filter",
"=",
":Standard",
"handler",
".",
"V",
"=",
"version",
"handler",
".",
"R",
"=",
"revision",
"handler",
".",
"Length",
"=",
"params",
"[",
":key_size",
"]",
"handler",
".",
"P",
"=",
"-",
"1",
"# params[:Permissions]",
"# Build the crypt filter dictionary.",
"if",
"revision",
">=",
"4",
"handler",
".",
"EncryptMetadata",
"=",
"params",
"[",
":encrypt_metadata",
"]",
"handler",
".",
"CF",
"=",
"Dictionary",
".",
"new",
"crypt_filter",
"=",
"Encryption",
"::",
"CryptFilterDictionary",
".",
"new",
"crypt_filter",
".",
"AuthEvent",
"=",
":DocOpen",
"if",
"revision",
"==",
"4",
"crypt_filter",
".",
"CFM",
"=",
":AESV2",
"else",
"crypt_filter",
".",
"CFM",
"=",
":AESV3",
"end",
"crypt_filter",
".",
"Length",
"=",
"params",
"[",
":key_size",
"]",
">>",
"3",
"handler",
".",
"CF",
"[",
":StdCF",
"]",
"=",
"crypt_filter",
"handler",
".",
"StmF",
"=",
"handler",
".",
"StrF",
"=",
":StdCF",
"end",
"user_passwd",
",",
"owner_passwd",
"=",
"params",
"[",
":user_passwd",
"]",
",",
"params",
"[",
":owner_passwd",
"]",
"# Setup keys.",
"handler",
".",
"set_passwords",
"(",
"owner_passwd",
",",
"user_passwd",
",",
"doc_id",
")",
"encryption_key",
"=",
"handler",
".",
"compute_user_encryption_key",
"(",
"user_passwd",
",",
"doc_id",
")",
"# Install the encryption dictionary to the document.",
"self",
".",
"trailer",
".",
"Encrypt",
"=",
"self",
"<<",
"handler",
"[",
"handler",
",",
"encryption_key",
"]",
"end"
] | Installs the standard security dictionary, marking the document as being encrypted.
Returns the handler and the encryption key used for protecting contents. | [
"Installs",
"the",
"standard",
"security",
"dictionary",
"marking",
"the",
"document",
"as",
"being",
"encrypted",
".",
"Returns",
"the",
"handler",
"and",
"the",
"encryption",
"key",
"used",
"for",
"protecting",
"contents",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/encryption.rb#L123-L165 | train |
gdelugre/origami | lib/origami/pdf.rb | Origami.PDF.<< | def <<(object)
owner = object.document
#
# Does object belongs to another PDF ?
#
if owner and not owner.equal?(self)
import object
else
add_to_revision(object, @revisions.last)
end
end | ruby | def <<(object)
owner = object.document
#
# Does object belongs to another PDF ?
#
if owner and not owner.equal?(self)
import object
else
add_to_revision(object, @revisions.last)
end
end | [
"def",
"<<",
"(",
"object",
")",
"owner",
"=",
"object",
".",
"document",
"#",
"# Does object belongs to another PDF ?",
"#",
"if",
"owner",
"and",
"not",
"owner",
".",
"equal?",
"(",
"self",
")",
"import",
"object",
"else",
"add_to_revision",
"(",
"object",
",",
"@revisions",
".",
"last",
")",
"end",
"end"
] | Adds a new object to the PDF file.
If this object has no version number, then a new one will be automatically
computed and assignated to him.
It returns a Reference to this Object.
_object_:: The object to add. | [
"Adds",
"a",
"new",
"object",
"to",
"the",
"PDF",
"file",
".",
"If",
"this",
"object",
"has",
"no",
"version",
"number",
"then",
"a",
"new",
"one",
"will",
"be",
"automatically",
"computed",
"and",
"assignated",
"to",
"him",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L317-L328 | train |
gdelugre/origami | lib/origami/pdf.rb | Origami.PDF.add_to_revision | def add_to_revision(object, revision)
object.set_indirect(true)
object.set_document(self)
object.no, object.generation = allocate_new_object_number if object.no == 0
revision.body[object.reference] = object
object.reference
end | ruby | def add_to_revision(object, revision)
object.set_indirect(true)
object.set_document(self)
object.no, object.generation = allocate_new_object_number if object.no == 0
revision.body[object.reference] = object
object.reference
end | [
"def",
"add_to_revision",
"(",
"object",
",",
"revision",
")",
"object",
".",
"set_indirect",
"(",
"true",
")",
"object",
".",
"set_document",
"(",
"self",
")",
"object",
".",
"no",
",",
"object",
".",
"generation",
"=",
"allocate_new_object_number",
"if",
"object",
".",
"no",
"==",
"0",
"revision",
".",
"body",
"[",
"object",
".",
"reference",
"]",
"=",
"object",
"object",
".",
"reference",
"end"
] | Adds a new object to a specific revision.
If this object has no version number, then a new one will be automatically
computed and assignated to him.
It returns a Reference to this Object.
_object_:: The object to add.
_revision_:: The revision to add the object to. | [
"Adds",
"a",
"new",
"object",
"to",
"a",
"specific",
"revision",
".",
"If",
"this",
"object",
"has",
"no",
"version",
"number",
"then",
"a",
"new",
"one",
"will",
"be",
"automatically",
"computed",
"and",
"assignated",
"to",
"him",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L350-L359 | train |
gdelugre/origami | lib/origami/pdf.rb | Origami.PDF.add_new_revision | def add_new_revision
root = @revisions.last.trailer[:Root] unless @revisions.empty?
@revisions << Revision.new(self)
@revisions.last.trailer = Trailer.new
@revisions.last.trailer.Root = root
self
end | ruby | def add_new_revision
root = @revisions.last.trailer[:Root] unless @revisions.empty?
@revisions << Revision.new(self)
@revisions.last.trailer = Trailer.new
@revisions.last.trailer.Root = root
self
end | [
"def",
"add_new_revision",
"root",
"=",
"@revisions",
".",
"last",
".",
"trailer",
"[",
":Root",
"]",
"unless",
"@revisions",
".",
"empty?",
"@revisions",
"<<",
"Revision",
".",
"new",
"(",
"self",
")",
"@revisions",
".",
"last",
".",
"trailer",
"=",
"Trailer",
".",
"new",
"@revisions",
".",
"last",
".",
"trailer",
".",
"Root",
"=",
"root",
"self",
"end"
] | Ends the current Revision, and starts a new one. | [
"Ends",
"the",
"current",
"Revision",
"and",
"starts",
"a",
"new",
"one",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L364-L372 | train |
gdelugre/origami | lib/origami/pdf.rb | Origami.PDF.delete_object | def delete_object(no, generation = 0)
case no
when Reference
target = no
when ::Integer
target = Reference.new(no, generation)
else
raise TypeError, "Invalid parameter type : #{no.class}"
end
@revisions.each do |rev|
rev.body.delete(target)
end
end | ruby | def delete_object(no, generation = 0)
case no
when Reference
target = no
when ::Integer
target = Reference.new(no, generation)
else
raise TypeError, "Invalid parameter type : #{no.class}"
end
@revisions.each do |rev|
rev.body.delete(target)
end
end | [
"def",
"delete_object",
"(",
"no",
",",
"generation",
"=",
"0",
")",
"case",
"no",
"when",
"Reference",
"target",
"=",
"no",
"when",
"::",
"Integer",
"target",
"=",
"Reference",
".",
"new",
"(",
"no",
",",
"generation",
")",
"else",
"raise",
"TypeError",
",",
"\"Invalid parameter type : #{no.class}\"",
"end",
"@revisions",
".",
"each",
"do",
"|",
"rev",
"|",
"rev",
".",
"body",
".",
"delete",
"(",
"target",
")",
"end",
"end"
] | Remove an object. | [
"Remove",
"an",
"object",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L401-L414 | train |
gdelugre/origami | lib/origami/pdf.rb | Origami.PDF.cast_object | def cast_object(reference, type) #:nodoc:
@revisions.each do |rev|
if rev.body.include?(reference)
object = rev.body[reference]
return object if object.is_a?(type)
if type < rev.body[reference].class
rev.body[reference] = object.cast_to(type, @parser)
return rev.body[reference]
end
end
end
nil
end | ruby | def cast_object(reference, type) #:nodoc:
@revisions.each do |rev|
if rev.body.include?(reference)
object = rev.body[reference]
return object if object.is_a?(type)
if type < rev.body[reference].class
rev.body[reference] = object.cast_to(type, @parser)
return rev.body[reference]
end
end
end
nil
end | [
"def",
"cast_object",
"(",
"reference",
",",
"type",
")",
"#:nodoc:",
"@revisions",
".",
"each",
"do",
"|",
"rev",
"|",
"if",
"rev",
".",
"body",
".",
"include?",
"(",
"reference",
")",
"object",
"=",
"rev",
".",
"body",
"[",
"reference",
"]",
"return",
"object",
"if",
"object",
".",
"is_a?",
"(",
"type",
")",
"if",
"type",
"<",
"rev",
".",
"body",
"[",
"reference",
"]",
".",
"class",
"rev",
".",
"body",
"[",
"reference",
"]",
"=",
"object",
".",
"cast_to",
"(",
"type",
",",
"@parser",
")",
"return",
"rev",
".",
"body",
"[",
"reference",
"]",
"end",
"end",
"end",
"nil",
"end"
] | Casts a PDF object into another object type.
The target type must be a subtype of the original type. | [
"Casts",
"a",
"PDF",
"object",
"into",
"another",
"object",
"type",
".",
"The",
"target",
"type",
"must",
"be",
"a",
"subtype",
"of",
"the",
"original",
"type",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L499-L514 | train |
gdelugre/origami | lib/origami/pdf.rb | Origami.PDF.search_object | def search_object(object, pattern, streams: true, object_streams: true)
result = []
case object
when Stream
result.concat object.dictionary.strings_cache.select{|str| str.match(pattern) }
result.concat object.dictionary.names_cache.select{|name| name.value.match(pattern) }
begin
result.push object if streams and object.data.match(pattern)
rescue Filter::Error
return result # Skip object if a decoding error occured.
end
return result unless object.is_a?(ObjectStream) and object_streams
object.each do |child|
result.concat search_object(child, pattern,
streams: streams, object_streams: object_streams)
end
when Name, String
result.push object if object.value.match(pattern)
when ObjectCache
result.concat object.strings_cache.select{|str| str.match(pattern) }
result.concat object.names_cache.select{|name| name.value.match(pattern) }
end
result
end | ruby | def search_object(object, pattern, streams: true, object_streams: true)
result = []
case object
when Stream
result.concat object.dictionary.strings_cache.select{|str| str.match(pattern) }
result.concat object.dictionary.names_cache.select{|name| name.value.match(pattern) }
begin
result.push object if streams and object.data.match(pattern)
rescue Filter::Error
return result # Skip object if a decoding error occured.
end
return result unless object.is_a?(ObjectStream) and object_streams
object.each do |child|
result.concat search_object(child, pattern,
streams: streams, object_streams: object_streams)
end
when Name, String
result.push object if object.value.match(pattern)
when ObjectCache
result.concat object.strings_cache.select{|str| str.match(pattern) }
result.concat object.names_cache.select{|name| name.value.match(pattern) }
end
result
end | [
"def",
"search_object",
"(",
"object",
",",
"pattern",
",",
"streams",
":",
"true",
",",
"object_streams",
":",
"true",
")",
"result",
"=",
"[",
"]",
"case",
"object",
"when",
"Stream",
"result",
".",
"concat",
"object",
".",
"dictionary",
".",
"strings_cache",
".",
"select",
"{",
"|",
"str",
"|",
"str",
".",
"match",
"(",
"pattern",
")",
"}",
"result",
".",
"concat",
"object",
".",
"dictionary",
".",
"names_cache",
".",
"select",
"{",
"|",
"name",
"|",
"name",
".",
"value",
".",
"match",
"(",
"pattern",
")",
"}",
"begin",
"result",
".",
"push",
"object",
"if",
"streams",
"and",
"object",
".",
"data",
".",
"match",
"(",
"pattern",
")",
"rescue",
"Filter",
"::",
"Error",
"return",
"result",
"# Skip object if a decoding error occured.",
"end",
"return",
"result",
"unless",
"object",
".",
"is_a?",
"(",
"ObjectStream",
")",
"and",
"object_streams",
"object",
".",
"each",
"do",
"|",
"child",
"|",
"result",
".",
"concat",
"search_object",
"(",
"child",
",",
"pattern",
",",
"streams",
":",
"streams",
",",
"object_streams",
":",
"object_streams",
")",
"end",
"when",
"Name",
",",
"String",
"result",
".",
"push",
"object",
"if",
"object",
".",
"value",
".",
"match",
"(",
"pattern",
")",
"when",
"ObjectCache",
"result",
".",
"concat",
"object",
".",
"strings_cache",
".",
"select",
"{",
"|",
"str",
"|",
"str",
".",
"match",
"(",
"pattern",
")",
"}",
"result",
".",
"concat",
"object",
".",
"names_cache",
".",
"select",
"{",
"|",
"name",
"|",
"name",
".",
"value",
".",
"match",
"(",
"pattern",
")",
"}",
"end",
"result",
"end"
] | Searches through an object, possibly going into object streams.
Returns an array of matching strings, names and streams. | [
"Searches",
"through",
"an",
"object",
"possibly",
"going",
"into",
"object",
"streams",
".",
"Returns",
"an",
"array",
"of",
"matching",
"strings",
"names",
"and",
"streams",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L576-L606 | train |
gdelugre/origami | lib/origami/pdf.rb | Origami.PDF.load_object_at_offset | def load_object_at_offset(revision, offset)
return nil if loaded? or @parser.nil?
pos = @parser.pos
begin
object = @parser.parse_object(offset)
return nil if object.nil?
if self.is_a?(Encryption::EncryptedDocument)
make_encrypted_object(object)
end
add_to_revision(object, revision)
ensure
@parser.pos = pos
end
object
end | ruby | def load_object_at_offset(revision, offset)
return nil if loaded? or @parser.nil?
pos = @parser.pos
begin
object = @parser.parse_object(offset)
return nil if object.nil?
if self.is_a?(Encryption::EncryptedDocument)
make_encrypted_object(object)
end
add_to_revision(object, revision)
ensure
@parser.pos = pos
end
object
end | [
"def",
"load_object_at_offset",
"(",
"revision",
",",
"offset",
")",
"return",
"nil",
"if",
"loaded?",
"or",
"@parser",
".",
"nil?",
"pos",
"=",
"@parser",
".",
"pos",
"begin",
"object",
"=",
"@parser",
".",
"parse_object",
"(",
"offset",
")",
"return",
"nil",
"if",
"object",
".",
"nil?",
"if",
"self",
".",
"is_a?",
"(",
"Encryption",
"::",
"EncryptedDocument",
")",
"make_encrypted_object",
"(",
"object",
")",
"end",
"add_to_revision",
"(",
"object",
",",
"revision",
")",
"ensure",
"@parser",
".",
"pos",
"=",
"pos",
"end",
"object",
"end"
] | Load an object from its given file offset.
The document must have an associated Parser. | [
"Load",
"an",
"object",
"from",
"its",
"given",
"file",
"offset",
".",
"The",
"document",
"must",
"have",
"an",
"associated",
"Parser",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L612-L630 | train |
gdelugre/origami | lib/origami/pdf.rb | Origami.PDF.make_encrypted_object | def make_encrypted_object(object)
case object
when String
object.extend(Encryption::EncryptedString)
when Stream
object.extend(Encryption::EncryptedStream)
when ObjectCache
object.strings_cache.each do |string|
string.extend(Encryption::EncryptedString)
end
end
end | ruby | def make_encrypted_object(object)
case object
when String
object.extend(Encryption::EncryptedString)
when Stream
object.extend(Encryption::EncryptedStream)
when ObjectCache
object.strings_cache.each do |string|
string.extend(Encryption::EncryptedString)
end
end
end | [
"def",
"make_encrypted_object",
"(",
"object",
")",
"case",
"object",
"when",
"String",
"object",
".",
"extend",
"(",
"Encryption",
"::",
"EncryptedString",
")",
"when",
"Stream",
"object",
".",
"extend",
"(",
"Encryption",
"::",
"EncryptedStream",
")",
"when",
"ObjectCache",
"object",
".",
"strings_cache",
".",
"each",
"do",
"|",
"string",
"|",
"string",
".",
"extend",
"(",
"Encryption",
"::",
"EncryptedString",
")",
"end",
"end",
"end"
] | Method called on encrypted objects loaded into the document. | [
"Method",
"called",
"on",
"encrypted",
"objects",
"loaded",
"into",
"the",
"document",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L635-L646 | train |
gdelugre/origami | lib/origami/pdf.rb | Origami.PDF.load_all_objects | def load_all_objects
return if loaded? or @parser.nil?
@revisions.each do |revision|
if revision.xreftable?
xrefs = revision.xreftable
elsif revision.xrefstm?
xrefs = revision.xrefstm
else
next
end
xrefs.each_with_number do |xref, no|
self.get_object(no) unless xref.free?
end
end
loaded!
end | ruby | def load_all_objects
return if loaded? or @parser.nil?
@revisions.each do |revision|
if revision.xreftable?
xrefs = revision.xreftable
elsif revision.xrefstm?
xrefs = revision.xrefstm
else
next
end
xrefs.each_with_number do |xref, no|
self.get_object(no) unless xref.free?
end
end
loaded!
end | [
"def",
"load_all_objects",
"return",
"if",
"loaded?",
"or",
"@parser",
".",
"nil?",
"@revisions",
".",
"each",
"do",
"|",
"revision",
"|",
"if",
"revision",
".",
"xreftable?",
"xrefs",
"=",
"revision",
".",
"xreftable",
"elsif",
"revision",
".",
"xrefstm?",
"xrefs",
"=",
"revision",
".",
"xrefstm",
"else",
"next",
"end",
"xrefs",
".",
"each_with_number",
"do",
"|",
"xref",
",",
"no",
"|",
"self",
".",
"get_object",
"(",
"no",
")",
"unless",
"xref",
".",
"free?",
"end",
"end",
"loaded!",
"end"
] | Force the loading of all objects in the document. | [
"Force",
"the",
"loading",
"of",
"all",
"objects",
"in",
"the",
"document",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L651-L669 | train |
gdelugre/origami | lib/origami/pdf.rb | Origami.PDF.physicalize | def physicalize(options = {})
@revisions.each do |revision|
# Do not use each_object here as build_object may modify the iterator.
revision.objects.each do |obj|
build_object(obj, revision, options)
end
end
self
end | ruby | def physicalize(options = {})
@revisions.each do |revision|
# Do not use each_object here as build_object may modify the iterator.
revision.objects.each do |obj|
build_object(obj, revision, options)
end
end
self
end | [
"def",
"physicalize",
"(",
"options",
"=",
"{",
"}",
")",
"@revisions",
".",
"each",
"do",
"|",
"revision",
"|",
"# Do not use each_object here as build_object may modify the iterator.",
"revision",
".",
"objects",
".",
"each",
"do",
"|",
"obj",
"|",
"build_object",
"(",
"obj",
",",
"revision",
",",
"options",
")",
"end",
"end",
"self",
"end"
] | Converts a logical PDF view into a physical view ready for writing. | [
"Converts",
"a",
"logical",
"PDF",
"view",
"into",
"a",
"physical",
"view",
"ready",
"for",
"writing",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L731-L741 | train |
gdelugre/origami | lib/origami/pdf.rb | Origami.PDF.init | def init
catalog = (self.Catalog = (trailer_key(:Root) || Catalog.new))
@revisions.last.trailer.Root = catalog.reference
loaded!
self
end | ruby | def init
catalog = (self.Catalog = (trailer_key(:Root) || Catalog.new))
@revisions.last.trailer.Root = catalog.reference
loaded!
self
end | [
"def",
"init",
"catalog",
"=",
"(",
"self",
".",
"Catalog",
"=",
"(",
"trailer_key",
"(",
":Root",
")",
"||",
"Catalog",
".",
"new",
")",
")",
"@revisions",
".",
"last",
".",
"trailer",
".",
"Root",
"=",
"catalog",
".",
"reference",
"loaded!",
"self",
"end"
] | Instanciates basic structures required for a valid PDF file. | [
"Instanciates",
"basic",
"structures",
"required",
"for",
"a",
"valid",
"PDF",
"file",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L988-L995 | train |
gdelugre/origami | lib/origami/pdf.rb | Origami.PDF.build_xrefs | def build_xrefs(objects) #:nodoc:
lastno = 0
brange = 0
xrefs = [ XRef.new(0, XRef::FIRSTFREE, XRef::FREE) ]
xrefsection = XRef::Section.new
objects.sort_by {|object| object.reference}
.each do |object|
if (object.no - lastno).abs > 1
xrefsection << XRef::Subsection.new(brange, xrefs)
brange = object.no
xrefs.clear
end
xrefs << XRef.new(get_object_offset(object.no, object.generation), object.generation, XRef::USED)
lastno = object.no
end
xrefsection << XRef::Subsection.new(brange, xrefs)
xrefsection
end | ruby | def build_xrefs(objects) #:nodoc:
lastno = 0
brange = 0
xrefs = [ XRef.new(0, XRef::FIRSTFREE, XRef::FREE) ]
xrefsection = XRef::Section.new
objects.sort_by {|object| object.reference}
.each do |object|
if (object.no - lastno).abs > 1
xrefsection << XRef::Subsection.new(brange, xrefs)
brange = object.no
xrefs.clear
end
xrefs << XRef.new(get_object_offset(object.no, object.generation), object.generation, XRef::USED)
lastno = object.no
end
xrefsection << XRef::Subsection.new(brange, xrefs)
xrefsection
end | [
"def",
"build_xrefs",
"(",
"objects",
")",
"#:nodoc:",
"lastno",
"=",
"0",
"brange",
"=",
"0",
"xrefs",
"=",
"[",
"XRef",
".",
"new",
"(",
"0",
",",
"XRef",
"::",
"FIRSTFREE",
",",
"XRef",
"::",
"FREE",
")",
"]",
"xrefsection",
"=",
"XRef",
"::",
"Section",
".",
"new",
"objects",
".",
"sort_by",
"{",
"|",
"object",
"|",
"object",
".",
"reference",
"}",
".",
"each",
"do",
"|",
"object",
"|",
"if",
"(",
"object",
".",
"no",
"-",
"lastno",
")",
".",
"abs",
">",
"1",
"xrefsection",
"<<",
"XRef",
"::",
"Subsection",
".",
"new",
"(",
"brange",
",",
"xrefs",
")",
"brange",
"=",
"object",
".",
"no",
"xrefs",
".",
"clear",
"end",
"xrefs",
"<<",
"XRef",
".",
"new",
"(",
"get_object_offset",
"(",
"object",
".",
"no",
",",
"object",
".",
"generation",
")",
",",
"object",
".",
"generation",
",",
"XRef",
"::",
"USED",
")",
"lastno",
"=",
"object",
".",
"no",
"end",
"xrefsection",
"<<",
"XRef",
"::",
"Subsection",
".",
"new",
"(",
"brange",
",",
"xrefs",
")",
"xrefsection",
"end"
] | Build a xref section from a set of objects. | [
"Build",
"a",
"xref",
"section",
"from",
"a",
"set",
"of",
"objects",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L1060-L1085 | train |
gdelugre/origami | lib/origami/dictionary.rb | Origami.Dictionary.transform_values | def transform_values(&b)
self.class.new self.map { |k, v|
[ k.to_sym, b.call(v) ]
}.to_h
end | ruby | def transform_values(&b)
self.class.new self.map { |k, v|
[ k.to_sym, b.call(v) ]
}.to_h
end | [
"def",
"transform_values",
"(",
"&",
"b",
")",
"self",
".",
"class",
".",
"new",
"self",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"[",
"k",
".",
"to_sym",
",",
"b",
".",
"call",
"(",
"v",
")",
"]",
"}",
".",
"to_h",
"end"
] | Returns a new Dictionary object with values modified by given block. | [
"Returns",
"a",
"new",
"Dictionary",
"object",
"with",
"values",
"modified",
"by",
"given",
"block",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/dictionary.rb#L131-L135 | train |
gdelugre/origami | lib/origami/dictionary.rb | Origami.Dictionary.transform_values! | def transform_values!(&b)
self.each_pair do |k, v|
self[k] = b.call(unlink_object(v))
end
end | ruby | def transform_values!(&b)
self.each_pair do |k, v|
self[k] = b.call(unlink_object(v))
end
end | [
"def",
"transform_values!",
"(",
"&",
"b",
")",
"self",
".",
"each_pair",
"do",
"|",
"k",
",",
"v",
"|",
"self",
"[",
"k",
"]",
"=",
"b",
".",
"call",
"(",
"unlink_object",
"(",
"v",
")",
")",
"end",
"end"
] | Modifies the values of the Dictionary, leaving keys unchanged. | [
"Modifies",
"the",
"values",
"of",
"the",
"Dictionary",
"leaving",
"keys",
"unchanged",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/dictionary.rb#L140-L144 | train |
gdelugre/origami | lib/origami/xreftable.rb | Origami.PDF.remove_xrefs | def remove_xrefs
@revisions.reverse_each do |rev|
if rev.xrefstm?
delete_object(rev.xrefstm.reference)
end
if rev.trailer.XRefStm.is_a?(Integer)
xrefstm = get_object_by_offset(rev.trailer.XRefStm)
delete_object(xrefstm.reference) if xrefstm.is_a?(XRefStream)
end
rev.xrefstm = rev.xreftable = nil
end
end | ruby | def remove_xrefs
@revisions.reverse_each do |rev|
if rev.xrefstm?
delete_object(rev.xrefstm.reference)
end
if rev.trailer.XRefStm.is_a?(Integer)
xrefstm = get_object_by_offset(rev.trailer.XRefStm)
delete_object(xrefstm.reference) if xrefstm.is_a?(XRefStream)
end
rev.xrefstm = rev.xreftable = nil
end
end | [
"def",
"remove_xrefs",
"@revisions",
".",
"reverse_each",
"do",
"|",
"rev",
"|",
"if",
"rev",
".",
"xrefstm?",
"delete_object",
"(",
"rev",
".",
"xrefstm",
".",
"reference",
")",
"end",
"if",
"rev",
".",
"trailer",
".",
"XRefStm",
".",
"is_a?",
"(",
"Integer",
")",
"xrefstm",
"=",
"get_object_by_offset",
"(",
"rev",
".",
"trailer",
".",
"XRefStm",
")",
"delete_object",
"(",
"xrefstm",
".",
"reference",
")",
"if",
"xrefstm",
".",
"is_a?",
"(",
"XRefStream",
")",
"end",
"rev",
".",
"xrefstm",
"=",
"rev",
".",
"xreftable",
"=",
"nil",
"end",
"end"
] | Tries to strip any xrefs information off the document. | [
"Tries",
"to",
"strip",
"any",
"xrefs",
"information",
"off",
"the",
"document",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/xreftable.rb#L27-L41 | train |
gdelugre/origami | lib/origami/xreftable.rb | Origami.XRefStream.each_with_number | def each_with_number
return enum_for(__method__) unless block_given?
load! if @xrefs.nil?
ranges = object_ranges
xrefs = @xrefs.to_enum
ranges.each do |range|
range.each do |no|
begin
yield(xrefs.next, no)
rescue StopIteration
raise InvalidXRefStreamObjectError, "Range is bigger than number of entries"
end
end
end
end | ruby | def each_with_number
return enum_for(__method__) unless block_given?
load! if @xrefs.nil?
ranges = object_ranges
xrefs = @xrefs.to_enum
ranges.each do |range|
range.each do |no|
begin
yield(xrefs.next, no)
rescue StopIteration
raise InvalidXRefStreamObjectError, "Range is bigger than number of entries"
end
end
end
end | [
"def",
"each_with_number",
"return",
"enum_for",
"(",
"__method__",
")",
"unless",
"block_given?",
"load!",
"if",
"@xrefs",
".",
"nil?",
"ranges",
"=",
"object_ranges",
"xrefs",
"=",
"@xrefs",
".",
"to_enum",
"ranges",
".",
"each",
"do",
"|",
"range",
"|",
"range",
".",
"each",
"do",
"|",
"no",
"|",
"begin",
"yield",
"(",
"xrefs",
".",
"next",
",",
"no",
")",
"rescue",
"StopIteration",
"raise",
"InvalidXRefStreamObjectError",
",",
"\"Range is bigger than number of entries\"",
"end",
"end",
"end",
"end"
] | Iterates over each XRef present in the stream, passing the XRef and its object number. | [
"Iterates",
"over",
"each",
"XRef",
"present",
"in",
"the",
"stream",
"passing",
"the",
"XRef",
"and",
"its",
"object",
"number",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/xreftable.rb#L447-L464 | train |
gdelugre/origami | lib/origami/xreftable.rb | Origami.XRefStream.find | def find(no)
load! if @xrefs.nil?
ranges = object_ranges
index = 0
ranges.each do |range|
return @xrefs[index + no - range.begin] if range.cover?(no)
index += range.size
end
nil
end | ruby | def find(no)
load! if @xrefs.nil?
ranges = object_ranges
index = 0
ranges.each do |range|
return @xrefs[index + no - range.begin] if range.cover?(no)
index += range.size
end
nil
end | [
"def",
"find",
"(",
"no",
")",
"load!",
"if",
"@xrefs",
".",
"nil?",
"ranges",
"=",
"object_ranges",
"index",
"=",
"0",
"ranges",
".",
"each",
"do",
"|",
"range",
"|",
"return",
"@xrefs",
"[",
"index",
"+",
"no",
"-",
"range",
".",
"begin",
"]",
"if",
"range",
".",
"cover?",
"(",
"no",
")",
"index",
"+=",
"range",
".",
"size",
"end",
"nil",
"end"
] | Returns an XRef matching this object number. | [
"Returns",
"an",
"XRef",
"matching",
"this",
"object",
"number",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/xreftable.rb#L469-L482 | train |
gdelugre/origami | lib/origami/xreftable.rb | Origami.XRefStream.field_widths | def field_widths
widths = self.W
unless widths.is_a?(Array) and widths.length == 3 and widths.all? {|w| w.is_a?(Integer) and w >= 0 }
raise InvalidXRefStreamObjectError, "Invalid W field: #{widths}"
end
widths
end | ruby | def field_widths
widths = self.W
unless widths.is_a?(Array) and widths.length == 3 and widths.all? {|w| w.is_a?(Integer) and w >= 0 }
raise InvalidXRefStreamObjectError, "Invalid W field: #{widths}"
end
widths
end | [
"def",
"field_widths",
"widths",
"=",
"self",
".",
"W",
"unless",
"widths",
".",
"is_a?",
"(",
"Array",
")",
"and",
"widths",
".",
"length",
"==",
"3",
"and",
"widths",
".",
"all?",
"{",
"|",
"w",
"|",
"w",
".",
"is_a?",
"(",
"Integer",
")",
"and",
"w",
">=",
"0",
"}",
"raise",
"InvalidXRefStreamObjectError",
",",
"\"Invalid W field: #{widths}\"",
"end",
"widths",
"end"
] | Check and return the internal field widths. | [
"Check",
"and",
"return",
"the",
"internal",
"field",
"widths",
"."
] | ac1df803517601d486556fd40af5d422a6f4378e | https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/xreftable.rb#L546-L554 | train |
igorkasyanchuk/rails_db | app/helpers/rails_db/application_helper.rb | RailsDb.ApplicationHelper.guess_name | def guess_name(sections)
if sections.size > 1
sections[-1] = 'rails_db'
variable = sections.join("_")
result = eval(variable)
end
rescue NameError
sections.delete_at(-2)
guess_name(sections)
end | ruby | def guess_name(sections)
if sections.size > 1
sections[-1] = 'rails_db'
variable = sections.join("_")
result = eval(variable)
end
rescue NameError
sections.delete_at(-2)
guess_name(sections)
end | [
"def",
"guess_name",
"(",
"sections",
")",
"if",
"sections",
".",
"size",
">",
"1",
"sections",
"[",
"-",
"1",
"]",
"=",
"'rails_db'",
"variable",
"=",
"sections",
".",
"join",
"(",
"\"_\"",
")",
"result",
"=",
"eval",
"(",
"variable",
")",
"end",
"rescue",
"NameError",
"sections",
".",
"delete_at",
"(",
"-",
"2",
")",
"guess_name",
"(",
"sections",
")",
"end"
] | in case engine was added in namespace | [
"in",
"case",
"engine",
"was",
"added",
"in",
"namespace"
] | ecc664670242f032ca4387d9c1ba80c02591b923 | https://github.com/igorkasyanchuk/rails_db/blob/ecc664670242f032ca4387d9c1ba80c02591b923/app/helpers/rails_db/application_helper.rb#L11-L20 | train |
orta/cocoapods-keys | lib/preinstaller.rb | CocoaPodsKeys.PreInstaller.setup | def setup
require 'key_master'
require 'keyring_liberator'
require 'pod/command/keys/set'
require 'cocoapods/user_interface'
require 'dotenv'
ui = Pod::UserInterface
options = @user_options || {}
current_dir = Pathname.pwd
Dotenv.load
project = options.fetch('project') { CocoaPodsKeys::NameWhisperer.get_project_name }
keyring = KeyringLiberator.get_current_keyring(project, current_dir)
unless keyring
check_for_multiple_keyrings(project, current_dir)
end
existing_keyring = !keyring.nil?
keyring = CocoaPodsKeys::Keyring.new(project, current_dir, []) unless keyring
has_shown_intro = false
keys = options.fetch('keys', [])
# Remove keys from the keyring that no longer exist
original_keyring_keys = keyring.keys.clone
original_keyring_keys.each do |key|
keyring.keychain_has_key?(key)
end
# Add keys to the keyring that have been added,
# and prompt for their value if needed.
keys.each do |key|
unless keyring.keychain_has_key?(key)
if ci?
raise Pod::Informative, "CocoaPods-Keys could not find a key named: #{key}"
end
unless has_shown_intro
ui.puts "\n CocoaPods-Keys has detected a keys mismatch for your setup."
has_shown_intro = true
end
ui.puts ' What is the key for ' + key.green
answer = ''
loop do
ui.print ' > '
answer = ui.gets.strip
break unless answer.empty?
end
ui.puts
args = CLAide::ARGV.new([key, answer, keyring.name])
setter = Pod::Command::Keys::Set.new(args)
setter.run
end
end
existing_keyring || !keys.empty?
end | ruby | def setup
require 'key_master'
require 'keyring_liberator'
require 'pod/command/keys/set'
require 'cocoapods/user_interface'
require 'dotenv'
ui = Pod::UserInterface
options = @user_options || {}
current_dir = Pathname.pwd
Dotenv.load
project = options.fetch('project') { CocoaPodsKeys::NameWhisperer.get_project_name }
keyring = KeyringLiberator.get_current_keyring(project, current_dir)
unless keyring
check_for_multiple_keyrings(project, current_dir)
end
existing_keyring = !keyring.nil?
keyring = CocoaPodsKeys::Keyring.new(project, current_dir, []) unless keyring
has_shown_intro = false
keys = options.fetch('keys', [])
# Remove keys from the keyring that no longer exist
original_keyring_keys = keyring.keys.clone
original_keyring_keys.each do |key|
keyring.keychain_has_key?(key)
end
# Add keys to the keyring that have been added,
# and prompt for their value if needed.
keys.each do |key|
unless keyring.keychain_has_key?(key)
if ci?
raise Pod::Informative, "CocoaPods-Keys could not find a key named: #{key}"
end
unless has_shown_intro
ui.puts "\n CocoaPods-Keys has detected a keys mismatch for your setup."
has_shown_intro = true
end
ui.puts ' What is the key for ' + key.green
answer = ''
loop do
ui.print ' > '
answer = ui.gets.strip
break unless answer.empty?
end
ui.puts
args = CLAide::ARGV.new([key, answer, keyring.name])
setter = Pod::Command::Keys::Set.new(args)
setter.run
end
end
existing_keyring || !keys.empty?
end | [
"def",
"setup",
"require",
"'key_master'",
"require",
"'keyring_liberator'",
"require",
"'pod/command/keys/set'",
"require",
"'cocoapods/user_interface'",
"require",
"'dotenv'",
"ui",
"=",
"Pod",
"::",
"UserInterface",
"options",
"=",
"@user_options",
"||",
"{",
"}",
"current_dir",
"=",
"Pathname",
".",
"pwd",
"Dotenv",
".",
"load",
"project",
"=",
"options",
".",
"fetch",
"(",
"'project'",
")",
"{",
"CocoaPodsKeys",
"::",
"NameWhisperer",
".",
"get_project_name",
"}",
"keyring",
"=",
"KeyringLiberator",
".",
"get_current_keyring",
"(",
"project",
",",
"current_dir",
")",
"unless",
"keyring",
"check_for_multiple_keyrings",
"(",
"project",
",",
"current_dir",
")",
"end",
"existing_keyring",
"=",
"!",
"keyring",
".",
"nil?",
"keyring",
"=",
"CocoaPodsKeys",
"::",
"Keyring",
".",
"new",
"(",
"project",
",",
"current_dir",
",",
"[",
"]",
")",
"unless",
"keyring",
"has_shown_intro",
"=",
"false",
"keys",
"=",
"options",
".",
"fetch",
"(",
"'keys'",
",",
"[",
"]",
")",
"# Remove keys from the keyring that no longer exist",
"original_keyring_keys",
"=",
"keyring",
".",
"keys",
".",
"clone",
"original_keyring_keys",
".",
"each",
"do",
"|",
"key",
"|",
"keyring",
".",
"keychain_has_key?",
"(",
"key",
")",
"end",
"# Add keys to the keyring that have been added,",
"# and prompt for their value if needed.",
"keys",
".",
"each",
"do",
"|",
"key",
"|",
"unless",
"keyring",
".",
"keychain_has_key?",
"(",
"key",
")",
"if",
"ci?",
"raise",
"Pod",
"::",
"Informative",
",",
"\"CocoaPods-Keys could not find a key named: #{key}\"",
"end",
"unless",
"has_shown_intro",
"ui",
".",
"puts",
"\"\\n CocoaPods-Keys has detected a keys mismatch for your setup.\"",
"has_shown_intro",
"=",
"true",
"end",
"ui",
".",
"puts",
"' What is the key for '",
"+",
"key",
".",
"green",
"answer",
"=",
"''",
"loop",
"do",
"ui",
".",
"print",
"' > '",
"answer",
"=",
"ui",
".",
"gets",
".",
"strip",
"break",
"unless",
"answer",
".",
"empty?",
"end",
"ui",
".",
"puts",
"args",
"=",
"CLAide",
"::",
"ARGV",
".",
"new",
"(",
"[",
"key",
",",
"answer",
",",
"keyring",
".",
"name",
"]",
")",
"setter",
"=",
"Pod",
"::",
"Command",
"::",
"Keys",
"::",
"Set",
".",
"new",
"(",
"args",
")",
"setter",
".",
"run",
"end",
"end",
"existing_keyring",
"||",
"!",
"keys",
".",
"empty?",
"end"
] | Returns `true` if all keys specified by the user are satisfied by either an existing keyring or environment
variables. | [
"Returns",
"true",
"if",
"all",
"keys",
"specified",
"by",
"the",
"user",
"are",
"satisfied",
"by",
"either",
"an",
"existing",
"keyring",
"or",
"environment",
"variables",
"."
] | bfdaa7be34457539a4cbcd74f907befd179fd4e7 | https://github.com/orta/cocoapods-keys/blob/bfdaa7be34457539a4cbcd74f907befd179fd4e7/lib/preinstaller.rb#L9-L70 | train |
justinfrench/formtastic | lib/formtastic/namespaced_class_finder.rb | Formtastic.NamespacedClassFinder.find_with_const_defined | def find_with_const_defined(class_name)
@namespaces.find do |namespace|
if namespace.const_defined?(class_name)
break namespace.const_get(class_name)
end
end
end | ruby | def find_with_const_defined(class_name)
@namespaces.find do |namespace|
if namespace.const_defined?(class_name)
break namespace.const_get(class_name)
end
end
end | [
"def",
"find_with_const_defined",
"(",
"class_name",
")",
"@namespaces",
".",
"find",
"do",
"|",
"namespace",
"|",
"if",
"namespace",
".",
"const_defined?",
"(",
"class_name",
")",
"break",
"namespace",
".",
"const_get",
"(",
"class_name",
")",
"end",
"end",
"end"
] | Looks up the given class name in the configured namespaces in order,
returning the first one that has the class name constant defined. | [
"Looks",
"up",
"the",
"given",
"class",
"name",
"in",
"the",
"configured",
"namespaces",
"in",
"order",
"returning",
"the",
"first",
"one",
"that",
"has",
"the",
"class",
"name",
"constant",
"defined",
"."
] | f1ddec6efbcf49b88e212249829344c450784195 | https://github.com/justinfrench/formtastic/blob/f1ddec6efbcf49b88e212249829344c450784195/lib/formtastic/namespaced_class_finder.rb#L81-L87 | train |
ruby-grape/grape-swagger | lib/grape-swagger/endpoint.rb | Grape.Endpoint.swagger_object | def swagger_object(target_class, request, options)
object = {
info: info_object(options[:info].merge(version: options[:doc_version])),
swagger: '2.0',
produces: content_types_for(target_class),
authorizations: options[:authorizations],
securityDefinitions: options[:security_definitions],
security: options[:security],
host: GrapeSwagger::DocMethods::OptionalObject.build(:host, options, request),
basePath: GrapeSwagger::DocMethods::OptionalObject.build(:base_path, options, request),
schemes: options[:schemes].is_a?(String) ? [options[:schemes]] : options[:schemes]
}
GrapeSwagger::DocMethods::Extensions.add_extensions_to_root(options, object)
object.delete_if { |_, value| value.blank? }
end | ruby | def swagger_object(target_class, request, options)
object = {
info: info_object(options[:info].merge(version: options[:doc_version])),
swagger: '2.0',
produces: content_types_for(target_class),
authorizations: options[:authorizations],
securityDefinitions: options[:security_definitions],
security: options[:security],
host: GrapeSwagger::DocMethods::OptionalObject.build(:host, options, request),
basePath: GrapeSwagger::DocMethods::OptionalObject.build(:base_path, options, request),
schemes: options[:schemes].is_a?(String) ? [options[:schemes]] : options[:schemes]
}
GrapeSwagger::DocMethods::Extensions.add_extensions_to_root(options, object)
object.delete_if { |_, value| value.blank? }
end | [
"def",
"swagger_object",
"(",
"target_class",
",",
"request",
",",
"options",
")",
"object",
"=",
"{",
"info",
":",
"info_object",
"(",
"options",
"[",
":info",
"]",
".",
"merge",
"(",
"version",
":",
"options",
"[",
":doc_version",
"]",
")",
")",
",",
"swagger",
":",
"'2.0'",
",",
"produces",
":",
"content_types_for",
"(",
"target_class",
")",
",",
"authorizations",
":",
"options",
"[",
":authorizations",
"]",
",",
"securityDefinitions",
":",
"options",
"[",
":security_definitions",
"]",
",",
"security",
":",
"options",
"[",
":security",
"]",
",",
"host",
":",
"GrapeSwagger",
"::",
"DocMethods",
"::",
"OptionalObject",
".",
"build",
"(",
":host",
",",
"options",
",",
"request",
")",
",",
"basePath",
":",
"GrapeSwagger",
"::",
"DocMethods",
"::",
"OptionalObject",
".",
"build",
"(",
":base_path",
",",
"options",
",",
"request",
")",
",",
"schemes",
":",
"options",
"[",
":schemes",
"]",
".",
"is_a?",
"(",
"String",
")",
"?",
"[",
"options",
"[",
":schemes",
"]",
"]",
":",
"options",
"[",
":schemes",
"]",
"}",
"GrapeSwagger",
"::",
"DocMethods",
"::",
"Extensions",
".",
"add_extensions_to_root",
"(",
"options",
",",
"object",
")",
"object",
".",
"delete_if",
"{",
"|",
"_",
",",
"value",
"|",
"value",
".",
"blank?",
"}",
"end"
] | swagger spec2.0 related parts
required keys for SwaggerObject | [
"swagger",
"spec2",
".",
"0",
"related",
"parts"
] | 542511d9ef08f25b587914a4976009fbc95f7dc0 | https://github.com/ruby-grape/grape-swagger/blob/542511d9ef08f25b587914a4976009fbc95f7dc0/lib/grape-swagger/endpoint.rb#L26-L41 | train |
ruby-grape/grape-swagger | lib/grape-swagger/endpoint.rb | Grape.Endpoint.info_object | def info_object(infos)
result = {
title: infos[:title] || 'API title',
description: infos[:description],
termsOfService: infos[:terms_of_service_url],
contact: contact_object(infos),
license: license_object(infos),
version: infos[:version]
}
GrapeSwagger::DocMethods::Extensions.add_extensions_to_info(infos, result)
result.delete_if { |_, value| value.blank? }
end | ruby | def info_object(infos)
result = {
title: infos[:title] || 'API title',
description: infos[:description],
termsOfService: infos[:terms_of_service_url],
contact: contact_object(infos),
license: license_object(infos),
version: infos[:version]
}
GrapeSwagger::DocMethods::Extensions.add_extensions_to_info(infos, result)
result.delete_if { |_, value| value.blank? }
end | [
"def",
"info_object",
"(",
"infos",
")",
"result",
"=",
"{",
"title",
":",
"infos",
"[",
":title",
"]",
"||",
"'API title'",
",",
"description",
":",
"infos",
"[",
":description",
"]",
",",
"termsOfService",
":",
"infos",
"[",
":terms_of_service_url",
"]",
",",
"contact",
":",
"contact_object",
"(",
"infos",
")",
",",
"license",
":",
"license_object",
"(",
"infos",
")",
",",
"version",
":",
"infos",
"[",
":version",
"]",
"}",
"GrapeSwagger",
"::",
"DocMethods",
"::",
"Extensions",
".",
"add_extensions_to_info",
"(",
"infos",
",",
"result",
")",
"result",
".",
"delete_if",
"{",
"|",
"_",
",",
"value",
"|",
"value",
".",
"blank?",
"}",
"end"
] | building info object | [
"building",
"info",
"object"
] | 542511d9ef08f25b587914a4976009fbc95f7dc0 | https://github.com/ruby-grape/grape-swagger/blob/542511d9ef08f25b587914a4976009fbc95f7dc0/lib/grape-swagger/endpoint.rb#L44-L57 | train |
ruby-grape/grape-swagger | lib/grape-swagger/endpoint.rb | Grape.Endpoint.license_object | def license_object(infos)
{
name: infos.delete(:license),
url: infos.delete(:license_url)
}.delete_if { |_, value| value.blank? }
end | ruby | def license_object(infos)
{
name: infos.delete(:license),
url: infos.delete(:license_url)
}.delete_if { |_, value| value.blank? }
end | [
"def",
"license_object",
"(",
"infos",
")",
"{",
"name",
":",
"infos",
".",
"delete",
"(",
":license",
")",
",",
"url",
":",
"infos",
".",
"delete",
"(",
":license_url",
")",
"}",
".",
"delete_if",
"{",
"|",
"_",
",",
"value",
"|",
"value",
".",
"blank?",
"}",
"end"
] | sub-objects of info object
license | [
"sub",
"-",
"objects",
"of",
"info",
"object",
"license"
] | 542511d9ef08f25b587914a4976009fbc95f7dc0 | https://github.com/ruby-grape/grape-swagger/blob/542511d9ef08f25b587914a4976009fbc95f7dc0/lib/grape-swagger/endpoint.rb#L61-L66 | train |
ruby-grape/grape-swagger | lib/grape-swagger/endpoint.rb | Grape.Endpoint.path_and_definition_objects | def path_and_definition_objects(namespace_routes, options)
@paths = {}
@definitions = {}
namespace_routes.each_key do |key|
routes = namespace_routes[key]
path_item(routes, options)
end
add_definitions_from options[:models]
[@paths, @definitions]
end | ruby | def path_and_definition_objects(namespace_routes, options)
@paths = {}
@definitions = {}
namespace_routes.each_key do |key|
routes = namespace_routes[key]
path_item(routes, options)
end
add_definitions_from options[:models]
[@paths, @definitions]
end | [
"def",
"path_and_definition_objects",
"(",
"namespace_routes",
",",
"options",
")",
"@paths",
"=",
"{",
"}",
"@definitions",
"=",
"{",
"}",
"namespace_routes",
".",
"each_key",
"do",
"|",
"key",
"|",
"routes",
"=",
"namespace_routes",
"[",
"key",
"]",
"path_item",
"(",
"routes",
",",
"options",
")",
"end",
"add_definitions_from",
"options",
"[",
":models",
"]",
"[",
"@paths",
",",
"@definitions",
"]",
"end"
] | building path and definitions objects | [
"building",
"path",
"and",
"definitions",
"objects"
] | 542511d9ef08f25b587914a4976009fbc95f7dc0 | https://github.com/ruby-grape/grape-swagger/blob/542511d9ef08f25b587914a4976009fbc95f7dc0/lib/grape-swagger/endpoint.rb#L78-L88 | train |
piotrmurach/tty-tree | lib/tty/tree.rb | TTY.Tree.node | def node(name, type = Node, &block)
parent = @nodes_stack.empty? ? Node::ROOT : @nodes_stack.last
level = [0, @nodes_stack.size - 1].max
prefix = ':pipe' * level
if parent.class == LeafNode
prefix = ':space' * level
end
node = type.new(name, parent.full_path, prefix, @nodes_stack.size)
@nodes << node
return unless block_given?
@nodes_stack << node
if block.arity.zero?
instance_eval(&block)
else
instance_eval(&(->(*_args) { block[node] }))
end
@nodes_stack.pop
end | ruby | def node(name, type = Node, &block)
parent = @nodes_stack.empty? ? Node::ROOT : @nodes_stack.last
level = [0, @nodes_stack.size - 1].max
prefix = ':pipe' * level
if parent.class == LeafNode
prefix = ':space' * level
end
node = type.new(name, parent.full_path, prefix, @nodes_stack.size)
@nodes << node
return unless block_given?
@nodes_stack << node
if block.arity.zero?
instance_eval(&block)
else
instance_eval(&(->(*_args) { block[node] }))
end
@nodes_stack.pop
end | [
"def",
"node",
"(",
"name",
",",
"type",
"=",
"Node",
",",
"&",
"block",
")",
"parent",
"=",
"@nodes_stack",
".",
"empty?",
"?",
"Node",
"::",
"ROOT",
":",
"@nodes_stack",
".",
"last",
"level",
"=",
"[",
"0",
",",
"@nodes_stack",
".",
"size",
"-",
"1",
"]",
".",
"max",
"prefix",
"=",
"':pipe'",
"*",
"level",
"if",
"parent",
".",
"class",
"==",
"LeafNode",
"prefix",
"=",
"':space'",
"*",
"level",
"end",
"node",
"=",
"type",
".",
"new",
"(",
"name",
",",
"parent",
".",
"full_path",
",",
"prefix",
",",
"@nodes_stack",
".",
"size",
")",
"@nodes",
"<<",
"node",
"return",
"unless",
"block_given?",
"@nodes_stack",
"<<",
"node",
"if",
"block",
".",
"arity",
".",
"zero?",
"instance_eval",
"(",
"block",
")",
"else",
"instance_eval",
"(",
"(",
"->",
"(",
"*",
"_args",
")",
"{",
"block",
"[",
"node",
"]",
"}",
")",
")",
"end",
"@nodes_stack",
".",
"pop",
"end"
] | Create a Tree
@param [String,Dir,Hash] data
@api public
Add node to this tree.
@param [Symbol,String] name
the name for the node
@param [Node, LeafNode] type
the type of node to add
@example
TTY::Tree.new do
node '...' do
node '...'
end
end
@api public | [
"Create",
"a",
"Tree"
] | 8e7e3bfc84a3bf3a2d325eae2fb5bfca2f7a5a8c | https://github.com/piotrmurach/tty-tree/blob/8e7e3bfc84a3bf3a2d325eae2fb5bfca2f7a5a8c/lib/tty/tree.rb#L58-L77 | train |
yosiat/panko_serializer | lib/panko/serialization_descriptor.rb | Panko.SerializationDescriptor.apply_filters | def apply_filters(options)
return unless options.key?(:only) || options.key?(:except)
attributes_only_filters, associations_only_filters = resolve_filters(options, :only)
attributes_except_filters, associations_except_filters = resolve_filters(options, :except)
self.attributes = apply_attribute_filters(
attributes,
attributes_only_filters,
attributes_except_filters
)
self.method_fields = apply_attribute_filters(
method_fields,
attributes_only_filters,
attributes_except_filters
)
unless has_many_associations.empty?
self.has_many_associations = apply_association_filters(
has_many_associations,
{ attributes: attributes_only_filters, associations: associations_only_filters },
attributes: attributes_except_filters, associations: associations_except_filters
)
end
unless has_one_associations.empty?
self.has_one_associations = apply_association_filters(
has_one_associations,
{ attributes: attributes_only_filters, associations: associations_only_filters },
attributes: attributes_except_filters, associations: associations_except_filters
)
end
end | ruby | def apply_filters(options)
return unless options.key?(:only) || options.key?(:except)
attributes_only_filters, associations_only_filters = resolve_filters(options, :only)
attributes_except_filters, associations_except_filters = resolve_filters(options, :except)
self.attributes = apply_attribute_filters(
attributes,
attributes_only_filters,
attributes_except_filters
)
self.method_fields = apply_attribute_filters(
method_fields,
attributes_only_filters,
attributes_except_filters
)
unless has_many_associations.empty?
self.has_many_associations = apply_association_filters(
has_many_associations,
{ attributes: attributes_only_filters, associations: associations_only_filters },
attributes: attributes_except_filters, associations: associations_except_filters
)
end
unless has_one_associations.empty?
self.has_one_associations = apply_association_filters(
has_one_associations,
{ attributes: attributes_only_filters, associations: associations_only_filters },
attributes: attributes_except_filters, associations: associations_except_filters
)
end
end | [
"def",
"apply_filters",
"(",
"options",
")",
"return",
"unless",
"options",
".",
"key?",
"(",
":only",
")",
"||",
"options",
".",
"key?",
"(",
":except",
")",
"attributes_only_filters",
",",
"associations_only_filters",
"=",
"resolve_filters",
"(",
"options",
",",
":only",
")",
"attributes_except_filters",
",",
"associations_except_filters",
"=",
"resolve_filters",
"(",
"options",
",",
":except",
")",
"self",
".",
"attributes",
"=",
"apply_attribute_filters",
"(",
"attributes",
",",
"attributes_only_filters",
",",
"attributes_except_filters",
")",
"self",
".",
"method_fields",
"=",
"apply_attribute_filters",
"(",
"method_fields",
",",
"attributes_only_filters",
",",
"attributes_except_filters",
")",
"unless",
"has_many_associations",
".",
"empty?",
"self",
".",
"has_many_associations",
"=",
"apply_association_filters",
"(",
"has_many_associations",
",",
"{",
"attributes",
":",
"attributes_only_filters",
",",
"associations",
":",
"associations_only_filters",
"}",
",",
"attributes",
":",
"attributes_except_filters",
",",
"associations",
":",
"associations_except_filters",
")",
"end",
"unless",
"has_one_associations",
".",
"empty?",
"self",
".",
"has_one_associations",
"=",
"apply_association_filters",
"(",
"has_one_associations",
",",
"{",
"attributes",
":",
"attributes_only_filters",
",",
"associations",
":",
"associations_only_filters",
"}",
",",
"attributes",
":",
"attributes_except_filters",
",",
"associations",
":",
"associations_except_filters",
")",
"end",
"end"
] | Applies attributes and association filters | [
"Applies",
"attributes",
"and",
"association",
"filters"
] | bbd23293b33cd8c25efc7609382139716b1b9ec7 | https://github.com/yosiat/panko_serializer/blob/bbd23293b33cd8c25efc7609382139716b1b9ec7/lib/panko/serialization_descriptor.rb#L56-L89 | train |
FooBarWidget/default_value_for | lib/default_value_for.rb | DefaultValueFor.ClassMethods.default_value_for | def default_value_for(attribute, options = {}, &block)
value = options
allows_nil = true
if options.is_a?(Hash)
opts = options.stringify_keys
value = opts.fetch('value', options)
allows_nil = opts.fetch('allows_nil', true)
end
if !method_defined?(:set_default_values)
include(InstanceMethods)
after_initialize :set_default_values
class_attribute :_default_attribute_values
class_attribute :_default_attribute_values_not_allowing_nil
extend(DelayedClassMethods)
init_hash = true
else
init_hash = !singleton_methods(false).include?(:_default_attribute_values)
end
if init_hash
self._default_attribute_values = {}
self._default_attribute_values_not_allowing_nil = []
end
if block_given?
container = BlockValueContainer.new(block)
else
container = NormalValueContainer.new(value)
end
_default_attribute_values[attribute.to_s] = container
_default_attribute_values_not_allowing_nil << attribute.to_s unless allows_nil
end | ruby | def default_value_for(attribute, options = {}, &block)
value = options
allows_nil = true
if options.is_a?(Hash)
opts = options.stringify_keys
value = opts.fetch('value', options)
allows_nil = opts.fetch('allows_nil', true)
end
if !method_defined?(:set_default_values)
include(InstanceMethods)
after_initialize :set_default_values
class_attribute :_default_attribute_values
class_attribute :_default_attribute_values_not_allowing_nil
extend(DelayedClassMethods)
init_hash = true
else
init_hash = !singleton_methods(false).include?(:_default_attribute_values)
end
if init_hash
self._default_attribute_values = {}
self._default_attribute_values_not_allowing_nil = []
end
if block_given?
container = BlockValueContainer.new(block)
else
container = NormalValueContainer.new(value)
end
_default_attribute_values[attribute.to_s] = container
_default_attribute_values_not_allowing_nil << attribute.to_s unless allows_nil
end | [
"def",
"default_value_for",
"(",
"attribute",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"value",
"=",
"options",
"allows_nil",
"=",
"true",
"if",
"options",
".",
"is_a?",
"(",
"Hash",
")",
"opts",
"=",
"options",
".",
"stringify_keys",
"value",
"=",
"opts",
".",
"fetch",
"(",
"'value'",
",",
"options",
")",
"allows_nil",
"=",
"opts",
".",
"fetch",
"(",
"'allows_nil'",
",",
"true",
")",
"end",
"if",
"!",
"method_defined?",
"(",
":set_default_values",
")",
"include",
"(",
"InstanceMethods",
")",
"after_initialize",
":set_default_values",
"class_attribute",
":_default_attribute_values",
"class_attribute",
":_default_attribute_values_not_allowing_nil",
"extend",
"(",
"DelayedClassMethods",
")",
"init_hash",
"=",
"true",
"else",
"init_hash",
"=",
"!",
"singleton_methods",
"(",
"false",
")",
".",
"include?",
"(",
":_default_attribute_values",
")",
"end",
"if",
"init_hash",
"self",
".",
"_default_attribute_values",
"=",
"{",
"}",
"self",
".",
"_default_attribute_values_not_allowing_nil",
"=",
"[",
"]",
"end",
"if",
"block_given?",
"container",
"=",
"BlockValueContainer",
".",
"new",
"(",
"block",
")",
"else",
"container",
"=",
"NormalValueContainer",
".",
"new",
"(",
"value",
")",
"end",
"_default_attribute_values",
"[",
"attribute",
".",
"to_s",
"]",
"=",
"container",
"_default_attribute_values_not_allowing_nil",
"<<",
"attribute",
".",
"to_s",
"unless",
"allows_nil",
"end"
] | Declares a default value for the given attribute.
Sets the default value to the given options parameter unless the given options equal { :value => ... }
The <tt>options</tt> can be used to specify the following things:
* <tt>value</tt> - Sets the default value.
* <tt>allows_nil (default: true)</tt> - Sets explicitly passed nil values if option is set to true. | [
"Declares",
"a",
"default",
"value",
"for",
"the",
"given",
"attribute",
"."
] | d5fe8f13aed6e63df5e5128c7625ccf46f66eea8 | https://github.com/FooBarWidget/default_value_for/blob/d5fe8f13aed6e63df5e5128c7625ccf46f66eea8/lib/default_value_for.rb#L58-L94 | train |
zendesk/zendesk_apps_support | lib/zendesk_apps_support/package.rb | ZendeskAppsSupport.Package.compile | def compile(options)
begin
app_id = options.fetch(:app_id)
asset_url_prefix = options.fetch(:assets_dir)
name = options.fetch(:app_name)
rescue KeyError => e
raise ArgumentError, e.message
end
locale = options.fetch(:locale, 'en')
source = manifest.iframe_only? ? nil : app_js
app_class_name = "app-#{app_id}"
# if no_template is an array, we still need the templates
templates = manifest.no_template == true ? {} : compiled_templates(app_id, asset_url_prefix)
SRC_TEMPLATE.result(
name: name,
version: manifest.version,
source: source,
app_class_properties: manifest.app_class_properties,
asset_url_prefix: asset_url_prefix,
logo_asset_hash: generate_logo_hash(manifest.products),
location_icons: location_icons,
app_class_name: app_class_name,
author: manifest.author,
translations: manifest.iframe_only? ? nil : runtime_translations(translations_for(locale)),
framework_version: manifest.framework_version,
templates: templates,
modules: commonjs_modules,
iframe_only: manifest.iframe_only?
)
end | ruby | def compile(options)
begin
app_id = options.fetch(:app_id)
asset_url_prefix = options.fetch(:assets_dir)
name = options.fetch(:app_name)
rescue KeyError => e
raise ArgumentError, e.message
end
locale = options.fetch(:locale, 'en')
source = manifest.iframe_only? ? nil : app_js
app_class_name = "app-#{app_id}"
# if no_template is an array, we still need the templates
templates = manifest.no_template == true ? {} : compiled_templates(app_id, asset_url_prefix)
SRC_TEMPLATE.result(
name: name,
version: manifest.version,
source: source,
app_class_properties: manifest.app_class_properties,
asset_url_prefix: asset_url_prefix,
logo_asset_hash: generate_logo_hash(manifest.products),
location_icons: location_icons,
app_class_name: app_class_name,
author: manifest.author,
translations: manifest.iframe_only? ? nil : runtime_translations(translations_for(locale)),
framework_version: manifest.framework_version,
templates: templates,
modules: commonjs_modules,
iframe_only: manifest.iframe_only?
)
end | [
"def",
"compile",
"(",
"options",
")",
"begin",
"app_id",
"=",
"options",
".",
"fetch",
"(",
":app_id",
")",
"asset_url_prefix",
"=",
"options",
".",
"fetch",
"(",
":assets_dir",
")",
"name",
"=",
"options",
".",
"fetch",
"(",
":app_name",
")",
"rescue",
"KeyError",
"=>",
"e",
"raise",
"ArgumentError",
",",
"e",
".",
"message",
"end",
"locale",
"=",
"options",
".",
"fetch",
"(",
":locale",
",",
"'en'",
")",
"source",
"=",
"manifest",
".",
"iframe_only?",
"?",
"nil",
":",
"app_js",
"app_class_name",
"=",
"\"app-#{app_id}\"",
"# if no_template is an array, we still need the templates",
"templates",
"=",
"manifest",
".",
"no_template",
"==",
"true",
"?",
"{",
"}",
":",
"compiled_templates",
"(",
"app_id",
",",
"asset_url_prefix",
")",
"SRC_TEMPLATE",
".",
"result",
"(",
"name",
":",
"name",
",",
"version",
":",
"manifest",
".",
"version",
",",
"source",
":",
"source",
",",
"app_class_properties",
":",
"manifest",
".",
"app_class_properties",
",",
"asset_url_prefix",
":",
"asset_url_prefix",
",",
"logo_asset_hash",
":",
"generate_logo_hash",
"(",
"manifest",
".",
"products",
")",
",",
"location_icons",
":",
"location_icons",
",",
"app_class_name",
":",
"app_class_name",
",",
"author",
":",
"manifest",
".",
"author",
",",
"translations",
":",
"manifest",
".",
"iframe_only?",
"?",
"nil",
":",
"runtime_translations",
"(",
"translations_for",
"(",
"locale",
")",
")",
",",
"framework_version",
":",
"manifest",
".",
"framework_version",
",",
"templates",
":",
"templates",
",",
"modules",
":",
"commonjs_modules",
",",
"iframe_only",
":",
"manifest",
".",
"iframe_only?",
")",
"end"
] | this is not really compile_js, it compiles the whole app including scss for v1 apps | [
"this",
"is",
"not",
"really",
"compile_js",
"it",
"compiles",
"the",
"whole",
"app",
"including",
"scss",
"for",
"v1",
"apps"
] | d744af677c8d05706a63a25c2aee0203d2a3f102 | https://github.com/zendesk/zendesk_apps_support/blob/d744af677c8d05706a63a25c2aee0203d2a3f102/lib/zendesk_apps_support/package.rb#L108-L140 | train |
cldwalker/hirb | lib/hirb/helpers/table.rb | Hirb.Helpers::Table.default_field_lengths | def default_field_lengths
field_lengths = @headers ? @headers.inject({}) {|h,(k,v)| h[k] = String.size(v); h} :
@fields.inject({}) {|h,e| h[e] = 1; h }
@rows.each do |row|
@fields.each do |field|
len = String.size(row[field])
field_lengths[field] = len if len > field_lengths[field].to_i
end
end
field_lengths
end | ruby | def default_field_lengths
field_lengths = @headers ? @headers.inject({}) {|h,(k,v)| h[k] = String.size(v); h} :
@fields.inject({}) {|h,e| h[e] = 1; h }
@rows.each do |row|
@fields.each do |field|
len = String.size(row[field])
field_lengths[field] = len if len > field_lengths[field].to_i
end
end
field_lengths
end | [
"def",
"default_field_lengths",
"field_lengths",
"=",
"@headers",
"?",
"@headers",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"h",
",",
"(",
"k",
",",
"v",
")",
"|",
"h",
"[",
"k",
"]",
"=",
"String",
".",
"size",
"(",
"v",
")",
";",
"h",
"}",
":",
"@fields",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"h",
",",
"e",
"|",
"h",
"[",
"e",
"]",
"=",
"1",
";",
"h",
"}",
"@rows",
".",
"each",
"do",
"|",
"row",
"|",
"@fields",
".",
"each",
"do",
"|",
"field",
"|",
"len",
"=",
"String",
".",
"size",
"(",
"row",
"[",
"field",
"]",
")",
"field_lengths",
"[",
"field",
"]",
"=",
"len",
"if",
"len",
">",
"field_lengths",
"[",
"field",
"]",
".",
"to_i",
"end",
"end",
"field_lengths",
"end"
] | find max length for each field; start with the headers | [
"find",
"max",
"length",
"for",
"each",
"field",
";",
"start",
"with",
"the",
"headers"
] | 264f72c7c0f0966001e802414a5b0641036c7860 | https://github.com/cldwalker/hirb/blob/264f72c7c0f0966001e802414a5b0641036c7860/lib/hirb/helpers/table.rb#L322-L332 | train |
cldwalker/hirb | lib/hirb/helpers/table.rb | Hirb.Helpers::Table.array_to_indices_hash | def array_to_indices_hash(array)
array.inject({}) {|hash,e| hash[hash.size] = e; hash }
end | ruby | def array_to_indices_hash(array)
array.inject({}) {|hash,e| hash[hash.size] = e; hash }
end | [
"def",
"array_to_indices_hash",
"(",
"array",
")",
"array",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"hash",
",",
"e",
"|",
"hash",
"[",
"hash",
".",
"size",
"]",
"=",
"e",
";",
"hash",
"}",
"end"
] | Converts an array to a hash mapping a numerical index to its array value. | [
"Converts",
"an",
"array",
"to",
"a",
"hash",
"mapping",
"a",
"numerical",
"index",
"to",
"its",
"array",
"value",
"."
] | 264f72c7c0f0966001e802414a5b0641036c7860 | https://github.com/cldwalker/hirb/blob/264f72c7c0f0966001e802414a5b0641036c7860/lib/hirb/helpers/table.rb#L371-L373 | train |
cldwalker/hirb | lib/hirb/formatter.rb | Hirb.Formatter.format_output | def format_output(output, options={}, &block)
output_class = determine_output_class(output)
options = parse_console_options(options) if options.delete(:console)
options = Util.recursive_hash_merge(klass_config(output_class), options)
_format_output(output, options, &block)
end | ruby | def format_output(output, options={}, &block)
output_class = determine_output_class(output)
options = parse_console_options(options) if options.delete(:console)
options = Util.recursive_hash_merge(klass_config(output_class), options)
_format_output(output, options, &block)
end | [
"def",
"format_output",
"(",
"output",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"output_class",
"=",
"determine_output_class",
"(",
"output",
")",
"options",
"=",
"parse_console_options",
"(",
"options",
")",
"if",
"options",
".",
"delete",
"(",
":console",
")",
"options",
"=",
"Util",
".",
"recursive_hash_merge",
"(",
"klass_config",
"(",
"output_class",
")",
",",
"options",
")",
"_format_output",
"(",
"output",
",",
"options",
",",
"block",
")",
"end"
] | This method looks for an output object's view in Formatter.config and then Formatter.dynamic_config.
If a view is found, a stringified view is returned based on the object. If no view is found, nil is returned. The options this
class takes are a view hash as described in Formatter.config. These options will be merged with any existing helper
config hash an output class has in Formatter.config. Any block given is passed along to a helper class. | [
"This",
"method",
"looks",
"for",
"an",
"output",
"object",
"s",
"view",
"in",
"Formatter",
".",
"config",
"and",
"then",
"Formatter",
".",
"dynamic_config",
".",
"If",
"a",
"view",
"is",
"found",
"a",
"stringified",
"view",
"is",
"returned",
"based",
"on",
"the",
"object",
".",
"If",
"no",
"view",
"is",
"found",
"nil",
"is",
"returned",
".",
"The",
"options",
"this",
"class",
"takes",
"are",
"a",
"view",
"hash",
"as",
"described",
"in",
"Formatter",
".",
"config",
".",
"These",
"options",
"will",
"be",
"merged",
"with",
"any",
"existing",
"helper",
"config",
"hash",
"an",
"output",
"class",
"has",
"in",
"Formatter",
".",
"config",
".",
"Any",
"block",
"given",
"is",
"passed",
"along",
"to",
"a",
"helper",
"class",
"."
] | 264f72c7c0f0966001e802414a5b0641036c7860 | https://github.com/cldwalker/hirb/blob/264f72c7c0f0966001e802414a5b0641036c7860/lib/hirb/formatter.rb#L52-L57 | train |
cldwalker/hirb | lib/hirb/dynamic_view.rb | Hirb.DynamicView.dynamic_options | def dynamic_options(obj)
view_methods.each do |meth|
if obj.class.ancestors.map {|e| e.to_s }.include?(method_to_class(meth))
begin
return send(meth, obj)
rescue
raise "View failed to generate for '#{method_to_class(meth)}' "+
"while in '#{meth}' with error:\n#{$!.message}"
end
end
end
nil
end | ruby | def dynamic_options(obj)
view_methods.each do |meth|
if obj.class.ancestors.map {|e| e.to_s }.include?(method_to_class(meth))
begin
return send(meth, obj)
rescue
raise "View failed to generate for '#{method_to_class(meth)}' "+
"while in '#{meth}' with error:\n#{$!.message}"
end
end
end
nil
end | [
"def",
"dynamic_options",
"(",
"obj",
")",
"view_methods",
".",
"each",
"do",
"|",
"meth",
"|",
"if",
"obj",
".",
"class",
".",
"ancestors",
".",
"map",
"{",
"|",
"e",
"|",
"e",
".",
"to_s",
"}",
".",
"include?",
"(",
"method_to_class",
"(",
"meth",
")",
")",
"begin",
"return",
"send",
"(",
"meth",
",",
"obj",
")",
"rescue",
"raise",
"\"View failed to generate for '#{method_to_class(meth)}' \"",
"+",
"\"while in '#{meth}' with error:\\n#{$!.message}\"",
"end",
"end",
"end",
"nil",
"end"
] | Returns a hash of options based on dynamic views defined for the object's ancestry. If no config is found returns nil. | [
"Returns",
"a",
"hash",
"of",
"options",
"based",
"on",
"dynamic",
"views",
"defined",
"for",
"the",
"object",
"s",
"ancestry",
".",
"If",
"no",
"config",
"is",
"found",
"returns",
"nil",
"."
] | 264f72c7c0f0966001e802414a5b0641036c7860 | https://github.com/cldwalker/hirb/blob/264f72c7c0f0966001e802414a5b0641036c7860/lib/hirb/dynamic_view.rb#L69-L81 | train |
cldwalker/hirb | lib/hirb/pager.rb | Hirb.Pager.activated_by? | def activated_by?(string_to_page, inspect_mode=false)
inspect_mode ? (String.size(string_to_page) > @height * @width) : (string_to_page.count("\n") > @height)
end | ruby | def activated_by?(string_to_page, inspect_mode=false)
inspect_mode ? (String.size(string_to_page) > @height * @width) : (string_to_page.count("\n") > @height)
end | [
"def",
"activated_by?",
"(",
"string_to_page",
",",
"inspect_mode",
"=",
"false",
")",
"inspect_mode",
"?",
"(",
"String",
".",
"size",
"(",
"string_to_page",
")",
">",
"@height",
"*",
"@width",
")",
":",
"(",
"string_to_page",
".",
"count",
"(",
"\"\\n\"",
")",
">",
"@height",
")",
"end"
] | Determines if string should be paged based on configured width and height. | [
"Determines",
"if",
"string",
"should",
"be",
"paged",
"based",
"on",
"configured",
"width",
"and",
"height",
"."
] | 264f72c7c0f0966001e802414a5b0641036c7860 | https://github.com/cldwalker/hirb/blob/264f72c7c0f0966001e802414a5b0641036c7860/lib/hirb/pager.rb#L88-L90 | train |
cldwalker/hirb | lib/hirb/util.rb | Hirb.Util.recursive_hash_merge | def recursive_hash_merge(hash1, hash2)
hash1.merge(hash2) {|k,o,n| (o.is_a?(Hash)) ? recursive_hash_merge(o,n) : n}
end | ruby | def recursive_hash_merge(hash1, hash2)
hash1.merge(hash2) {|k,o,n| (o.is_a?(Hash)) ? recursive_hash_merge(o,n) : n}
end | [
"def",
"recursive_hash_merge",
"(",
"hash1",
",",
"hash2",
")",
"hash1",
".",
"merge",
"(",
"hash2",
")",
"{",
"|",
"k",
",",
"o",
",",
"n",
"|",
"(",
"o",
".",
"is_a?",
"(",
"Hash",
")",
")",
"?",
"recursive_hash_merge",
"(",
"o",
",",
"n",
")",
":",
"n",
"}",
"end"
] | Recursively merge hash1 with hash2. | [
"Recursively",
"merge",
"hash1",
"with",
"hash2",
"."
] | 264f72c7c0f0966001e802414a5b0641036c7860 | https://github.com/cldwalker/hirb/blob/264f72c7c0f0966001e802414a5b0641036c7860/lib/hirb/util.rb#L21-L23 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.