_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q17900 | OoxmlParser.DocxShapeProperties.parse | train | def parse(node)
@fill_color = DocxColor.new(parent: self).parse(node)
node.xpath('*').each do |node_child|
case node_child.name
when 'xfrm'
@shape_size = DocxShapeSize.new(parent: self).parse(node_child)
when 'prstGeom'
@preset_geometry = PresetGeometry.new(parent: self).parse(node_child)
when 'txbx'
@text_box = TextBox.parse_list(node_child)
when 'ln'
@line = DocxShapeLine.new(parent: self).parse(node_child)
when 'blipFill'
@blip_fill = BlipFill.new(parent: self).parse(node_child)
when 'custGeom'
@preset_geometry = PresetGeometry.new(parent: self).parse(node_child)
@preset_geometry.name = :custom
@custom_geometry = OOXMLCustomGeometry.new(parent: self).parse(node_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17901 | OoxmlParser.ColorProperties.parse | train | def parse(node)
node.xpath('*').each do |node_child|
case node_child.name
when 'alpha'
@alpha = (node_child.attribute('val').value.to_f / 1_000.0).round
when 'lumMod'
@luminance_modulation = node_child.attribute('val').value.to_f / 100_000.0
when 'lumOff'
@luminance_offset = node_child.attribute('val').value.to_f / 100_000.0
when 'tint'
@tint = node_child.attribute('val').value.to_f / 100_000.0
end
end
self
end | ruby | {
"resource": ""
} |
q17902 | OoxmlParser.DocxShapeLine.parse | train | def parse(node)
node.attributes.each do |key, value|
case key
when 'w'
@width = OoxmlSize.new(value.value.to_f, :emu)
when 'cap'
@cap = value_to_symbol(value)
end
end
node.xpath('*').each do |node_child|
case node_child.name
when 'solidFill'
@color_scheme = DocxColorScheme.new(parent: self).parse(node_child)
when 'noFill'
@width = OoxmlSize.new(0)
when 'headEnd'
@head_end = LineEnd.new(parent: self).parse(node_child)
when 'tailEnd'
@tail_end = LineEnd.new(parent: self).parse(node_child)
when 'prstDash'
@dash = ValuedChild.new(:symbol, parent: self).parse(node_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17903 | OoxmlParser.TableProperties.parse | train | def parse(node)
node.xpath('*').each do |node_child|
case node_child.name
when 'tableStyleId'
@table_style_id = node_child.text
when 'tblBorders'
@table_borders = TableBorders.new(parent: self).parse(node_child)
when 'tblStyle'
# TODO: Incorrect but to keep compatibility
@table_style_element = TableStyle.new(parent: self).parse(node_child)
when 'tblW'
@table_width = OoxmlSize.new.parse(node_child)
when 'jc'
@jc = node_child.attribute('val').text.to_sym
when 'shd'
@shade = Shade.new(parent: self).parse(node_child)
when 'solidFill'
@fill = PresentationFill.new(parent: self).parse(node)
when 'tblLook'
@table_look = TableLook.new(parent: self).parse(node_child)
when 'tblInd'
@table_indent = OoxmlSize.new(node_child.attribute('w').text.to_f)
when 'tblpPr'
@table_positon = TablePosition.new(parent: self).parse(node_child)
when 'tblCellMar'
@table_cell_margin = TableMargins.new(parent: table_properties).parse(node_child)
when 'tblStyleColBandSize'
@table_style_column_band_size = TableStyleColumnBandSize.new(parent: self).parse(node_child)
when 'tblStyleRowBandSize'
@table_style_row_band_size = TableStyleRowBandSize.new(parent: self).parse(node_child)
when 'tblLayout'
@table_layout = TableLayout.new(parent: self).parse(node_child)
when 'tblCellSpacing'
@table_cell_spacing = OoxmlSize.new.parse(node_child)
when 'tblCaption'
@caption = ValuedChild.new(:string, parent: self).parse(node_child)
when 'tblDescription'
@description = ValuedChild.new(:string, parent: self).parse(node_child)
end
end
@table_look = TableLook.new(parent: self).parse(node) if @table_look.nil?
self
end | ruby | {
"resource": ""
} |
q17904 | OoxmlParser.CommonSlideData.parse | train | def parse(node)
node.xpath('*').each do |node_child|
case node_child.name
when 'spTree'
@shape_tree = ShapeTree.new(parent: self).parse(node_child)
when 'bg'
@background = Background.new(parent: self).parse(node_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17905 | OoxmlParser.TableCellLine.parse | train | def parse(node)
@fill = PresentationFill.new(parent: self).parse(node)
@line_join = LineJoin.new(parent: self).parse(node)
node.attributes.each do |key, value|
case key
when 'w'
@width = OoxmlSize.new(value.value.to_f, :emu)
when 'algn'
@align = value_to_symbol(value)
end
end
node.xpath('*').each do |node_child|
case node_child.name
when 'headEnd'
@head_end = LineEnd.new(parent: self).parse(node_child)
when 'tailEnd'
@tail_end = LineEnd.new(parent: self).parse(node_child)
when 'ln'
return TableCellLine.new(parent: self).parse(node_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17906 | OoxmlParser.DocxShape.parse | train | def parse(node)
node.xpath('*').each do |node_child|
case node_child.name
when 'nvSpPr'
@non_visual_properties = NonVisualShapeProperties.new(parent: self).parse(node_child)
when 'spPr'
@properties = DocxShapeProperties.new(parent: self).parse(node_child)
when 'txbx'
@text_body = OOXMLTextBox.new(parent: self).parse(node_child)
when 'txBody'
@text_body = TextBody.new(parent: self).parse(node_child)
when 'bodyPr'
@body_properties = OOXMLShapeBodyProperties.new(parent: self).parse(node_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17907 | OoxmlParser.SDTContent.parse | train | def parse(node)
node.xpath('*').each do |node_child|
case node_child.name
when 'p'
@elements << DocxParagraph.new(parent: self).parse(node_child)
when 'r'
@elements << ParagraphRun.new(parent: self).parse(node_child)
when 'tbl'
@elements << Table.new(parent: self).parse(node_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17908 | OoxmlParser.CommonTiming.parse | train | def parse(node)
node.attributes.each do |key, value|
case key
when 'dur'
@duration = value.value
when 'restart'
@restart = value.value
when 'id'
@id = value.value
end
end
node.xpath('*').each do |node_child|
case node_child.name
when 'stCondLst'
@start_conditions = ConditionList.new(parent: self).parse(node_child)
when 'endCondLst'
@end_conditions = ConditionList.new(parent: self).parse(node_child)
when 'childTnLst'
@children = TimeNode.parse_list(node_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17909 | OoxmlParser.OOXMLCustomGeometry.parse | train | def parse(node)
node.xpath('*').each do |node_child|
case node_child.name
when 'pathLst'
node_child.xpath('a:path', 'xmlns:a' => 'http://schemas.openxmlformats.org/drawingml/2006/main').each do |path_node|
@paths_list << DocxShapeLinePath.new(parent: self).parse(path_node)
end
end
end
self
end | ruby | {
"resource": ""
} |
q17910 | OoxmlParser.OldDocxPicture.parse | train | def parse(node)
node.xpath('*').each do |node_child|
case node_child.name
when 'shape'
@type = :shape
@data = OldDocxShape.new(parent: self).parse(node_child)
when 'group'
@type = :group
@data = OldDocxGroup.new(parent: self).parse(node_child)
when 'style'
@style_number = node_child.attribute('val').value.to_i
end
end
self
end | ruby | {
"resource": ""
} |
q17911 | OoxmlParser.DocxFormula.parse | train | def parse(node)
node.xpath('*').each do |node_child|
case node_child.name
when 'r'
@formula_run << MathRun.new(parent: self).parse(node_child)
when 'box', 'borderBox'
@formula_run << Box.new(parent: self).parse(node_child)
when 'func'
@formula_run << Function.new(parent: self).parse(node_child)
when 'rad'
@formula_run << Radical.new(parent: self).parse(node_child)
when 'e', 'eqArr'
@formula_run << DocxFormula.new(parent: self).parse(node_child)
when 'nary'
@formula_run << Nary.new(parent: self).parse(node_child)
when 'd'
@formula_run << Delimiter.new(parent: self).parse(node_child)
when 'sSubSup', 'sSup', 'sSub'
@formula_run << Index.new(parent: self).parse(node_child)
when 'f'
@formula_run << Fraction.new(parent: self).parse(node_child)
when 'm'
@formula_run << Matrix.new(parent: self).parse(node_child)
when 'bar'
@formula_run << Bar.new(parent: self).parse(node_child)
when 'acc'
@formula_run << Accent.new(parent: self).parse(node_child)
when 'groupChr'
@formula_run << GroupChar.new(parent: self).parse(node_child)
when 'argPr'
@argument_properties = ArgumentProperties.new(parent: self).parse(node_child)
when 'sPre'
@formula_run << PreSubSuperscript.new(parent: self).parse(node_child)
when 'limUpp', 'limLow'
@formula_run << Limit.new(parent: self).parse(node_child)
end
end
return nil if @formula_run.empty?
self
end | ruby | {
"resource": ""
} |
q17912 | OoxmlParser.NonVisualShapeProperties.parse | train | def parse(node)
node.xpath('*').each do |node_child|
case node_child.name
when 'cNvPr'
@common_properties = CommonNonVisualProperties.new(parent: self).parse(node_child)
when 'nvPr'
@non_visual_properties = NonVisualProperties.new(parent: self).parse(node_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17913 | OoxmlParser.XlsxColumnProperties.parse | train | def parse(node)
node.attributes.each do |key, value|
case key
when 'min'
@from = value.value.to_i
when 'max'
@to = value.value.to_i
when 'style'
@style = root_object.style_sheet.cell_xfs.xf_array[value.value.to_i]
when 'width'
@width = value.value.to_f - 0.7109375
when 'customWidth'
@custom_width = option_enabled?(node, 'customWidth')
when 'bestFit'
@best_fit = attribute_enabled?(value)
when 'hidden'
@hidden = attribute_enabled?(value)
end
end
self
end | ruby | {
"resource": ""
} |
q17914 | OoxmlParser.OOXMLTextBox.parse | train | def parse(node)
text_box_content_node = node.xpath('w:txbxContent').first
text_box_content_node.xpath('*').each_with_index do |node_child, index|
case node_child.name
when 'p'
@elements << DocxParagraph.new(parent: self).parse(node_child, index)
when 'tbl'
@elements << Table.new(parent: self).parse(node_child, index)
when 'bodyPr'
@properties = OOXMLShapeBodyProperties.new(parent: self).parse(node_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17915 | OoxmlParser.DocumentStyleHelper.document_style_by_name | train | def document_style_by_name(name)
root_object.document_styles.each do |style|
return style if style.name == name
end
nil
end | ruby | {
"resource": ""
} |
q17916 | OoxmlParser.DocumentStyleHelper.document_style_by_id | train | def document_style_by_id(id)
root_object.document_styles.each do |style|
return style if style.style_id == id
end
nil
end | ruby | {
"resource": ""
} |
q17917 | OoxmlParser.Box.parse | train | def parse(node)
@borders = true if node.name == 'borderBox'
@element = MathRun.new(parent: self).parse(node)
self
end | ruby | {
"resource": ""
} |
q17918 | OoxmlParser.ImageFill.parse | train | def parse(node)
node.xpath('*').each do |node_child|
case node_child.name
when 'blip'
@file_reference = FileReference.new(parent: self).parse(node_child)
when 'tile'
@tile = Tile.new(OOXMLCoordinates.parse(node_child, x_attr: 'tx', y_attr: 'ty'),
OOXMLCoordinates.parse(node_child, x_attr: 'sx', y_attr: 'sy'),
parent: self).parse(node_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17919 | OoxmlParser.Timing.parse | train | def parse(node)
node.xpath('*').each do |node_child|
case node_child.name
when 'tnLst'
@time_node_list = TimeNode.parse_list(node_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17920 | OoxmlParser.StyleParametres.parse | train | def parse(node)
node.xpath('*').each do |node_child|
case node_child.name
when 'name'
@name = node_child.attribute('val').value
when 'qFormat'
@q_format = option_enabled?(node_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17921 | OoxmlParser.Spacing.parse | train | def parse(node)
node.xpath('*').each do |spacing_node_child|
case spacing_node_child.name
when 'lnSpc'
self.line = Spacing.parse_spacing_value(spacing_node_child)
self.line_rule = Spacing.parse_spacing_rule(spacing_node_child)
when 'spcBef'
self.before = Spacing.parse_spacing_value(spacing_node_child)
when 'spcAft'
self.after = Spacing.parse_spacing_value(spacing_node_child)
end
end
end | ruby | {
"resource": ""
} |
q17922 | OoxmlParser.GradientStop.parse | train | def parse(node)
node.attributes.each do |key, value|
case key
when 'pos'
@position = value.value.to_i / 1_000
end
end
node.xpath('*').each do |node_child|
@color = case node_child.name
when 'prstClr'
ValuedChild.new(:string, parent: self).parse(node_child)
else
Color.new(parent: self).parse_color(node_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17923 | OoxmlParser.AlphaModFix.parse | train | def parse(node)
node.attributes.each do |key, value|
case key
when 'amt'
@amount = OoxmlSize.new(value.value.to_f, :one_1000th_percent)
end
end
self
end | ruby | {
"resource": ""
} |
q17924 | OoxmlParser.TablePart.parse | train | def parse(node)
link_to_table_part_xml = OOXMLDocumentObject.get_link_from_rels(node.attribute('id').value)
doc = parse_xml(OOXMLDocumentObject.path_to_folder + link_to_table_part_xml.gsub('..', 'xl'))
table_node = doc.xpath('xmlns:table').first
table_node.attributes.each do |key, value|
case key
when 'name'
@name = value.value.to_s
when 'displayName'
@display_name = value.value.to_s
when 'ref'
@reference = Coordinates.parser_coordinates_range value.value.to_s
end
end
table_node.xpath('*').each do |node_child|
case node_child.name
when 'autoFilter'
@autofilter = Autofilter.new(parent: self).parse(node_child)
when 'extLst'
@extension_list = ExtensionList.new(parent: self).parse(node_child)
when 'tableColumns'
@table_columns = TableColumns.new(parent: self).parse(node_child)
when 'tableStyleInfo'
@table_style_info = TableStyleInfo.new(parent: self).parse(node_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17925 | OoxmlParser.SheetView.parse | train | def parse(node)
node.attributes.each_key do |key|
case key
when 'showGridLines'
@show_gridlines = attribute_enabled?(node, key)
when 'showRowColHeaders'
@show_row_column_headers = attribute_enabled?(node, key)
end
end
node.xpath('*').each do |node_child|
case node_child.name
when 'pane'
@pane = Pane.new(parent: self).parse(node_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17926 | OoxmlParser.DocxDrawingPosition.parse | train | def parse(node)
node.attributes.each do |key, value|
case key
when 'relativeFrom'
@relative_from = value_to_symbol(value)
end
end
node.xpath('*').each do |node_child|
case node_child.name
when 'posOffset', 'pctPosHOffset', 'pctPosVOffset'
@offset = OoxmlSize.new(node_child.text.to_f, :emu)
when 'align'
@align = node_child.text.to_sym
end
end
self
end | ruby | {
"resource": ""
} |
q17927 | OoxmlParser.OldDocxShape.parse | train | def parse(node)
@properties = OldDocxShapeProperties.new(parent: self).parse(node)
node.xpath('*').each do |node_child|
case node_child.name
when 'textbox'
@text_box = TextBox.parse_list(node_child, parent: self)
when 'imagedata'
@file_reference = FileReference.new(parent: self).parse(node_child)
when 'fill'
@fill = OldDocxShapeFill.new(parent: self).parse(node_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17928 | OoxmlParser.Formula.parse | train | def parse(node)
node.attributes.each do |key, value|
case key
when 'ref'
@reference = Coordinates.parser_coordinates_range(value.value.to_s)
when 'si'
@string_index = value.value.to_i
when 't'
@type = value.value.to_s
end
end
@value = node.text unless node.text.empty?
self
end | ruby | {
"resource": ""
} |
q17929 | OoxmlParser.Relationships.parse_file | train | def parse_file(file_path)
node = parse_xml(file_path)
node.xpath('*').each do |node_child|
case node_child.name
when 'Relationships'
parse(node_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17930 | OoxmlParser.Relationships.target_by_type | train | def target_by_type(type)
result = []
@relationship.each do |cur_rels|
result << cur_rels.target if cur_rels.type.include?(type)
end
result
end | ruby | {
"resource": ""
} |
q17931 | OoxmlParser.NumberingLevel.parse | train | def parse(node)
node.attributes.each do |key, value|
case key
when 'ilvl'
@ilvl = value.value.to_f
end
end
node.xpath('*').each do |num_level_child|
case num_level_child.name
when 'start'
@start = ValuedChild.new(:integer, parent: self).parse(num_level_child)
when 'numFmt'
@numbering_format = NumberingFormat.new(parent: self).parse(num_level_child)
when 'lvlText'
@text = LevelText.new(parent: self).parse(num_level_child)
when 'lvlJc'
@justification = LevelJustification.new(parent: self).parse(num_level_child)
when 'pPr'
@paragraph_properties = ParagraphProperties.new(parent: self).parse(num_level_child)
when 'rPr'
@run_properties = RunProperties.new(parent: self).parse(num_level_child)
when 'suff'
@suffix = @suffix.parse(num_level_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17932 | OoxmlParser.CellXfs.parse | train | def parse(node)
node.attributes.each do |key, value|
case key
when 'count'
@count = value.value.to_i
end
end
node.xpath('*').each do |node_child|
case node_child.name
when 'xf'
@xf_array << Xf.new(parent: self).parse(node_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17933 | OoxmlParser.DocxBlip.parse | train | def parse(node)
blip_node = node.xpath('a:blip', 'xmlns:a' => 'http://schemas.openxmlformats.org/drawingml/2006/main').first
return self if blip_node.nil?
@file_reference = FileReference.new(parent: self).parse(blip_node)
self
end | ruby | {
"resource": ""
} |
q17934 | OoxmlParser.GraphicFrame.parse | train | def parse(node)
node.xpath('*').each do |node_child|
case node_child.name
when 'xfrm'
@transform = DocxShapeSize.new(parent: self).parse(node_child)
when 'graphic'
graphic_data = []
node_child.xpath('*').each do |node_child_child|
case node_child_child.name
when 'graphicData'
node_child_child.xpath('*').each do |graphic_node_child|
case graphic_node_child.name
when 'tbl'
graphic_data << Table.new(parent: self).parse(graphic_node_child)
when 'chart'
OOXMLDocumentObject.add_to_xmls_stack(OOXMLDocumentObject.get_link_from_rels(graphic_node_child.attribute('id').value))
graphic_data << Chart.parse(parent: self)
OOXMLDocumentObject.xmls_stack.pop
when 'oleObj'
graphic_data << OleObject.new(parent: self).parse(graphic_node_child)
end
end
end
end
@graphic_data = graphic_data
when 'nvGraphicFramePr'
@non_visual_properties = NonVisualShapeProperties.new(parent: self).parse(node_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17935 | OoxmlParser.DocxShapeSize.parse | train | def parse(node)
node.attributes.each do |key, value|
case key
when 'rot'
@rotation = value.value.to_f
when 'flipH'
@flip_horizontal = attribute_enabled?(value)
when 'flipV'
@flip_vertical = attribute_enabled?(value)
end
end
node.xpath('*').each do |node_child|
case node_child.name
when 'off'
@offset = OOXMLCoordinates.parse(node_child, unit: :emu)
when 'ext'
@extent = OOXMLCoordinates.parse(node_child, x_attr: 'cx', y_attr: 'cy', unit: :emu)
when 'chOff'
@child_offset = OOXMLCoordinates.parse(node_child, unit: :emu)
when 'chExt'
@child_extent = OOXMLCoordinates.parse(node_child, x_attr: 'cx', y_attr: 'cy', unit: :emu)
end
end
self
end | ruby | {
"resource": ""
} |
q17936 | OoxmlParser.DocxWrapDrawing.parse | train | def parse(node)
unless node.attribute('behindDoc').nil?
@wrap_text = :behind if node.attribute('behindDoc').value == '1'
@wrap_text = :infront if node.attribute('behindDoc').value == '0'
end
node.xpath('*').each do |node_child|
case node_child.name
when 'wrapSquare'
@wrap_text = :square
@distance_from_text = DocxDrawingDistanceFromText.new(parent: self).parse(node_child)
break
when 'wrapTight'
@wrap_text = :tight
@distance_from_text = DocxDrawingDistanceFromText.new(parent: self).parse(node_child)
break
when 'wrapThrough'
@wrap_text = :through
@distance_from_text = DocxDrawingDistanceFromText.new(parent: self).parse(node_child)
break
when 'wrapTopAndBottom'
@wrap_text = :topbottom
@distance_from_text = DocxDrawingDistanceFromText.new(parent: self).parse(node_child)
break
end
end
self
end | ruby | {
"resource": ""
} |
q17937 | OoxmlParser.DocxShapeLinePath.parse | train | def parse(node)
node.attributes.each do |key, value|
case key
when 'w'
@width = value.value.to_f
when 'h'
@height = value.value.to_f
when 'stroke'
@stroke = value.value.to_f
end
end
node.xpath('*').each do |node_child|
@elements << DocxShapeLineElement.new(parent: self).parse(node_child)
end
self
end | ruby | {
"resource": ""
} |
q17938 | OoxmlParser.PresentationFill.parse | train | def parse(node)
return nil if node.xpath('*').empty?
node.xpath('*').each do |node_child|
case node_child.name
when 'gradFill'
@type = :gradient
@color = GradientColor.new(parent: self).parse(node_child)
when 'solidFill'
@type = :solid
@color = Color.new(parent: self).parse_color(node_child.xpath('*').first)
when 'blipFill'
@type = :image
@image = ImageFill.new(parent: self).parse(node_child)
when 'pattFill'
@type = :pattern
@pattern = PresentationPattern.new(parent: self).parse(node_child)
when 'noFill'
@type = :noneColor
@color = :none
end
end
return nil if @type.nil?
self
end | ruby | {
"resource": ""
} |
q17939 | OoxmlParser.ParagraphProperties.parse | train | def parse(node)
@spacing.parse(node)
node.attributes.each do |key, value|
case key
when 'algn'
@align = value_to_symbol(value)
when 'lvl'
@level = value.value.to_i
when 'indent'
@indent = OoxmlSize.new(value.value.to_f, :emu)
when 'marR'
@margin_right = OoxmlSize.new(value.value.to_f, :emu)
when 'marL'
@margin_left = OoxmlSize.new(value.value.to_f, :emu)
end
end
node.xpath('*').each do |node_child|
case node_child.name
when 'buSzPct'
@numbering.size = node_child.attribute('val').value
when 'buFont'
@numbering.font = node_child.attribute('typeface').value
when 'buChar'
@numbering.symbol = node_child.attribute('char').value
when 'buAutoNum'
@numbering.type = node_child.attribute('type').value.to_sym
@numbering.start_at = node_child.attribute('startAt').value if node_child.attribute('startAt')
when 'framePr'
@frame_properties = FrameProperties.new(parent: self).parse(node_child)
when 'tabs'
@tabs = Tabs.new(parent: self).parse(node_child)
when 'tabLst'
@tabs = Tabs.new(parent: self).parse(node_child)
when 'ind'
@indent = Indents.new(parent: self).parse(node_child)
when 'rPr'
@run_properties = RunProperties.new(parent: self).parse(node_child)
when 'pBdr'
@paragraph_borders = ParagraphBorders.new(parent: self).parse(node_child)
when 'keepNext'
@keep_next = true
when 'sectPr'
@section_properties = PageProperties.new(parent: self).parse(node_child, @parent, DocxParagraphRun.new)
when 'spacing'
@spacing = ParagraphSpacing.new(parent: self).parse(node_child)
when 'jc'
@justification = value_to_symbol(node_child.attribute('val'))
when 'contextualSpacing'
@contextual_spacing = option_enabled?(node_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17940 | OoxmlParser.TableRow.parse | train | def parse(node)
root_object.default_font_style = FontStyle.new(true) # TODO: Add correct parsing of TableStyle.xml file and use it
node.attributes.each do |key, value|
case key
when 'h'
@height = OoxmlSize.new(value.value.to_f, :emu)
end
end
node.xpath('*').each do |node_child|
case node_child.name
when 'trPr'
@table_row_properties = TableRowProperties.new(parent: self).parse(node_child)
when 'tc'
@cells << TableCell.new(parent: self).parse(node_child)
end
end
root_object.default_font_style = FontStyle.new
self
end | ruby | {
"resource": ""
} |
q17941 | OoxmlParser.XlsxDrawingPositionParameters.parse | train | def parse(node)
node.xpath('*').each do |node_child|
case node_child.name
when 'col'
@column = Coordinates.get_column_name(node_child.text.to_i + 1)
when 'colOff'
@column_offset = OoxmlSize.new(node_child.text.to_f, :emu)
when 'row'
@row = node_child.text.to_i + 1
when 'rowOff'
@row_offset = OoxmlSize.new(node_child.text.to_f, :emu)
end
end
self
end | ruby | {
"resource": ""
} |
q17942 | OoxmlParser.Fill.parse | train | def parse(node)
node.attributes.each do |key, value|
case key
when 'color2'
@color2 = Color.new(parent: self).parse_hex_string(value.value.split(' ').first.delete('#'))
when 'id'
@id = value.value.to_s
@file = FileReference.new(parent: self).parse(node)
when 'type'
@type = value_to_symbol(value)
end
end
node.xpath('*').each do |node_child|
case node_child.name
when 'patternFill'
@pattern_fill = PatternFill.new(parent: self).parse(node_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17943 | OoxmlParser.DocumentDefaults.parse | train | def parse(node)
node.xpath('*').each do |node_child|
case node_child.name
when 'rPrDefault'
@run_properties_default = RunPropertiesDefault.new(parent: self).parse(node_child)
when 'pPrDefault'
@paragraph_properties_default = ParagraphPropertiesDefault.new(parent: self).parse(node_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17944 | OoxmlParser.PatternFill.parse | train | def parse(node)
node.attributes.each do |key, value|
case key
when 'patternType'
@pattern_type = value.value.to_sym
end
end
node.xpath('*').each do |node_child|
case node_child.name
when 'fgColor'
@foreground_color = OoxmlColor.new(parent: self).parse(node_child)
when 'bgColor'
@background_color = OoxmlColor.new(parent: self).parse(node_child)
end
end
self
end | ruby | {
"resource": ""
} |
q17945 | CobwebModule.Crawl.set_base_url | train | def set_base_url(redis)
if redis.get("base_url").nil?
unless !defined?(content.redirect_through) || content.redirect_through.empty? || !@options[:first_page_redirect_internal]
uri = Addressable::URI.parse(content.redirect_through.last)
redis.sadd("internal_urls", [uri.scheme, "://", uri.host, "/*"].join)
end
redis.set("base_url", content.url)
end
end | ruby | {
"resource": ""
} |
q17946 | EmojiForJekyll.EmojiGenerator.convert | train | def convert(key, block = nil)
if block.nil? or block.call(key)
img_tag(key)
else
":#{key}:"
end
end | ruby | {
"resource": ""
} |
q17947 | Stretcher.IndexType.get | train | def get(id, options={}, raw=false)
if options == true || options == false # Support raw as second argument, legacy API
raw = true
options = {}
end
res = request(:get, id, options)
raw ? res : (res["_source"] || res["fields"])
end | ruby | {
"resource": ""
} |
q17948 | Stretcher.IndexType.delete | train | def delete(id, options={})
request :delete, id, options
rescue Stretcher::RequestError => e
raise e if e.http_response.status != 404
false
end | ruby | {
"resource": ""
} |
q17949 | Stretcher.IndexType.exists? | train | def exists?(id=nil)
request :head, id
true
rescue Stretcher::RequestError::NotFound => e
false
end | ruby | {
"resource": ""
} |
q17950 | Stretcher.EsComponent.do_search | train | def do_search(generic_opts={}, explicit_body=nil)
query_opts = {}
body = nil
if explicit_body
query_opts = generic_opts
body = explicit_body
else
body = generic_opts
end
response = request(:get, "_search", query_opts, nil, {}, :mashify => false) do |req|
req.body = body
end
SearchResults.new(response)
end | ruby | {
"resource": ""
} |
q17951 | Stretcher.Server.check_response | train | def check_response(res, options)
if res.status >= 200 && res.status <= 299
if(options[:mashify] && res.body.instance_of?(Hash))
Hashie::Mash.new(res.body)
else
res.body
end
elsif [404, 410].include? res.status
err_str = "Error processing request: (#{res.status})! #{res.env[:method]} URL: #{res.env[:url]}"
err_str << "\n Resp Body: #{res.body}"
raise RequestError::NotFound.new(res), err_str
else
err_str = "Error processing request (#{res.status})! #{res.env[:method]} URL: #{res.env[:url]}"
err_str << "\n Resp Body: #{res.body}"
raise RequestError.new(res), err_str
end
end | ruby | {
"resource": ""
} |
q17952 | Stretcher.Alias.create | train | def create(options = {})
request(:put) do |req|
req.body = {
actions: [
add: options.merge(:alias => @name)
]
}
end
end | ruby | {
"resource": ""
} |
q17953 | Flo.Task.call | train | def call(args=[])
raise ArgumentError.new("Expected Array") unless args.is_a? Array
@provider.public_send(method_sym, *merged_evaluated_args(args.dup))
end | ruby | {
"resource": ""
} |
q17954 | Flo.Task.evaluate_proc_values | train | def evaluate_proc_values(args=[])
args.collect do |arg|
case arg
when Proc
arg.call
when Hash
hsh = {}
arg.each do |k, v|
hsh[k] = v.is_a?(Proc) ? v.call : v
end
hsh
else
arg
end
end
end | ruby | {
"resource": ""
} |
q17955 | MnoEnterprise.SmtpClient.deliver | train | def deliver(template, from, to, vars={}, opts={})
@info = vars
@info[:company] = from[:name]
mail(
from: format_sender(from),
to: to[:email],
subject: humanize(template),
template_path: 'system_notifications',
template_name: template
)
end | ruby | {
"resource": ""
} |
q17956 | MnoEnterprise.IntercomEventsListener.tag_user | train | def tag_user(user)
if user.meta_data && user.meta_data[:source].present?
intercom.tags.tag(name: user.meta_data[:source], users: [{user_id: user.id}])
end
end | ruby | {
"resource": ""
} |
q17957 | MnoEnterprise::Jpi::V1::Admin.InvitesController.send_org_invite | train | def send_org_invite(user, invite)
# Generate token if not generated
user.send(:generate_confirmation_token!) if !user.confirmed? && user.confirmation_token.blank?
MnoEnterprise::SystemNotificationMailer.organization_invite(invite).deliver_later
# Update staged invite status
invite.status = 'pending' if invite.status == 'staged'
invite.notification_sent_at = Time.now unless invite.notification_sent_at.present?
invite.save
end | ruby | {
"resource": ""
} |
q17958 | MnoEnterprise.Jpi::V1::BaseResourceController.check_authorization | train | def check_authorization
unless current_user
render nothing: true, status: :unauthorized
return false
end
if params[:organization_id] && !parent_organization
render nothing: true, status: :forbidden
return false
end
true
end | ruby | {
"resource": ""
} |
q17959 | MnoEnterprise.BaseResource.save! | train | def save!(options={})
if perform_validations(options)
ret = super()
process_response_errors
raise_record_invalid if self.errors.any?
ret
else
raise_record_invalid
end
end | ruby | {
"resource": ""
} |
q17960 | MnoEnterprise.User.role | train | def role(organization = nil)
# Return cached version if available
return self.read_attribute(:role) if !organization
# Find in arrays if organizations have been fetched
# already. Perform remote query otherwise
org = begin
if self.organizations.loaded?
self.organizations.to_a.find { |e| e.id == organization.id }
else
self.organizations.where(id: organization.id).first
end
end
org ? org.role : nil
end | ruby | {
"resource": ""
} |
q17961 | MnoEnterprise.ApplicationController.after_sign_in_path_for | train | def after_sign_in_path_for(resource)
previous_url = session.delete(:previous_url)
default_url = if resource.respond_to?(:admin_role) && resource.admin_role.present?
MnoEnterprise.router.admin_path
else
MnoEnterprise.router.dashboard_path || main_app.root_url
end
return (return_to_url(resource) || previous_url || default_url)
end | ruby | {
"resource": ""
} |
q17962 | MnoEnterprise.Impac::Dashboard.organizations | train | def organizations(org_list = nil)
if org_list
return org_list if dashboard_type == 'template'
org_list.to_a.select { |e| organization_ids.include?(e.uid) || organization_ids.include?(e.id) }
else
MnoEnterprise::Organization.where('uid.in' => organization_ids).to_a
end
end | ruby | {
"resource": ""
} |
q17963 | MnoEnterprise.Impac::Dashboard.filtered_widgets_templates | train | def filtered_widgets_templates
if MnoEnterprise.widgets_templates_listing
return self.widgets_templates.select do |t|
MnoEnterprise.widgets_templates_listing.include?(t[:path])
end
else
return self.widgets_templates
end
end | ruby | {
"resource": ""
} |
q17964 | Flo.Command.call | train | def call(args={})
evaluate_command_definition(args)
response = tasks.map do |task|
response = task.call(args)
# bail early if the task failed
return response unless response.success?
response
end.last
end | ruby | {
"resource": ""
} |
q17965 | Flo.Command.optional_parameters | train | def optional_parameters
definition_lambda.parameters.select { |key,_value| key == :key }.map { |_key,value| value }
end | ruby | {
"resource": ""
} |
q17966 | MnoEnterprise.Jpi::V1::Admin::ThemeController.save_previewer_style | train | def save_previewer_style(theme)
target = Rails.root.join('frontend', 'src','app','stylesheets','theme-previewer-tmp.less')
File.open(target, 'w') { |f| f.write(theme_to_less(theme)) }
end | ruby | {
"resource": ""
} |
q17967 | MnoEnterprise.Jpi::V1::Admin::ThemeController.apply_previewer_style | train | def apply_previewer_style(theme)
target = Rails.root.join('frontend', 'src','app','stylesheets','theme-previewer-published.less')
File.open(target, 'w') { |f| f.write(theme_to_less(theme)) }
reset_previewer_style
end | ruby | {
"resource": ""
} |
q17968 | MnoEnterprise.Jpi::V1::Admin::ThemeController.theme_to_less | train | def theme_to_less(theme)
out = "// Generated by the Express Theme Previewer\n"
if theme[:branding]
out += "\n//----------------------------------------\n"
out += "// General Branding\n"
out += "//----------------------------------------\n"
out += theme[:branding].map { |k,v| "#{k}: #{v};" }.join("\n")
out += "\n"
end
if theme[:variables]
out += "\n//----------------------------------------\n"
out += "// Theme Variables\n"
out += "//----------------------------------------\n"
theme[:variables].each do |section,vars|
out += "// #{section}\n"
out += vars.map { |k,v| "#{k}: #{v};" }.join("\n")
out += "\n\n"
end
end
return out
end | ruby | {
"resource": ""
} |
q17969 | MnoEnterprise.InvoicePdf.generate_content | train | def generate_content
@pdf = Prawn::Document.new(
info: self.metadata,
top_margin: @format[:header_size] + @format[:top_margin],
bottom_margin: @format[:footer_size] + @format[:bottom_margin]
)
add_page_body
add_page_header
add_page_footer
add_page_numbering
end | ruby | {
"resource": ""
} |
q17970 | MnoEnterprise.InvoicePdf.add_page_header | train | def add_page_header
title = Settings.payment.disabled ? 'Account Statement - ' : 'Monthly Invoice - '
@pdf.repeat :all do
@pdf.bounding_box([0, @pdf.bounds.top+@format[:header_size]], width: 540, height: @format[:footer_size]) do
@pdf.float do
@pdf.image main_logo_white_bg_path(true), fit: [135, (@format[:footer_size])]
end
@pdf.move_down 52
@pdf.font_size(20) { @pdf.text "#{title} #{@data[:period_month]}", style: :bold, align: :right }
end
end
end | ruby | {
"resource": ""
} |
q17971 | MnoEnterprise.InvoicePdf.add_page_footer | train | def add_page_footer
@pdf.repeat :all do
@pdf.bounding_box([0, @pdf.bounds.bottom], width: 540, height: @format[:footer_size]) do
@pdf.move_down 50
@pdf.stroke_color '999999'
@pdf.stroke_horizontal_rule
@pdf.move_down 10
@pdf.font_size(8) do
@pdf.text "<color rgb='999999'>This invoice has been generated by Maestrano Pty Ltd on behalf of the #{MnoEnterprise.app_name} platform (the \"Service\").</color>", inline_format: true
@pdf.text "<color rgb='999999'>All charges in this invoice are in #{@data[:invoice_currency_name]} (#{@data[:invoice_currency]}). Credit card payments will be processed by Maestrano Pty Ltd.</color>", inline_format: true
@pdf.text " ", inline_format: true
@pdf.text "<color rgb='999999'>Maestrano Pty Ltd | Suite 504, 46 Market Street, Sydney, NSW 2000, Australia | ABN: 80 152 564 424</color>", inline_format: true
end
end
end
end | ruby | {
"resource": ""
} |
q17972 | MnoEnterprise.InvoicePdf.add_page_numbering | train | def add_page_numbering
numbering_options = {
at: [@pdf.bounds.right - 150, 0-@format[:footer_size]],
width: 150,
align: :right,
start_count_at: 1,
color: "999999",
size: 8
}
@pdf.number_pages "Page <page> of <total>", numbering_options
end | ruby | {
"resource": ""
} |
q17973 | QuickSearch.BestBetsSearcher.search_best_bets_index | train | def search_best_bets_index
response = @http.get(query_url)
parsed_response = JSON.parse(response.body)
if parsed_response['response']['numFound'].to_s == '0'
return nil
else
resp = parsed_response['response']['docs'][0]
result = OpenStruct.new
result.title = title(resp)
result.link = link(resp)
result.id = id(resp)
result.description = description(resp)
result.best_bets_type = 'best-bets-regular'
@response = result
end
end | ruby | {
"resource": ""
} |
q17974 | QuickSearch.TypeaheadController.typeahead | train | def typeahead
# :searcher param expected to be name of a searcher with underscores, ie: ematrix_journal
searcher = params[:searcher]
query = params[:q] or ''
total = params[:total] or 3
if searcher.blank?
logger.error "Typeahead request: no searcher param provided"
head :bad_request
return nil
end
searcher_string = "QuickSearch::#{searcher.camelize}Searcher"
begin
klass = searcher_string.constantize
rescue NameError
logger.error "Typeahead request: searcher #{searcher} does not exist"
head :bad_request
return nil
end
if klass.method_defined? :typeahead
typeahead_result = klass.new(HTTPClient.new, query, total).typeahead
if params.has_key? 'callback'
render json: typeahead_result, callback: params['callback']
else
render json: typeahead_result
end
else
logger.error "Typeahead request: searcher #{searcher} has no typeahead method"
head :bad_request
return nil
end
end | ruby | {
"resource": ""
} |
q17975 | QuickSearch.LoggingController.log_search | train | def log_search
if params[:query].present? && params[:page].present?
@session.searches.create(query: params[:query], page: params[:page])
head :ok
else
head :bad_request
end
end | ruby | {
"resource": ""
} |
q17976 | QuickSearch.LoggingController.log_event | train | def log_event
if params[:category].present? && params[:event_action].present? && params[:label].present?
# if an action isn't passed in, assume that it is a click
action = params.fetch(:action_type, 'click')
# create a new event on the current session
@session.events.create(category: params[:category], item: params[:event_action], query: params[:label][0..250], action: action)
if params[:ga].present? and params[:ga]
send_event_to_ga(params[:category], params[:event_action], params[:label])
end
# check whether this is a jsonp request
if params[:callback].present?
render :json => { 'response': 'success' }, :callback => params[:callback]
else
render :json => { 'response': 'success' }
end
else
head :bad_request
end
end | ruby | {
"resource": ""
} |
q17977 | QuickSearch.LoggingController.new_session | train | def new_session
on_campus = on_campus?(request.remote_ip)
is_mobile = is_mobile?
session_expiry = 5.minutes.from_now
session_uuid = SecureRandom.uuid
# create session in db
@session = Session.create(session_uuid: session_uuid, expiry: session_expiry, on_campus: on_campus, is_mobile: is_mobile)
# set cookie
cookies[:session_id] = { :value => session_uuid, :expires => session_expiry }
end | ruby | {
"resource": ""
} |
q17978 | QuickSearch.LoggingController.update_session | train | def update_session
# update session expiry in the database
session_id = cookies[:session_id]
@session = Session.find_by session_uuid: session_id
@session.expiry = 5.minutes.from_now
@session.save
# update session expiry on cookie
cookies[:session_id] = { :value => session_id, :expires => @session.expiry }
end | ruby | {
"resource": ""
} |
q17979 | QuickSearch.Searcher.no_results_link | train | def no_results_link(service_name, i18n_key, default_i18n_key = nil)
if (i18n_key.present? && I18n.exists?(i18n_key)) ||
(default_i18n_key.present? && I18n.exists?(default_i18n_key))
locale_result = I18n.t(i18n_key, default: I18n.t(default_i18n_key))
return locale_result if locale_result
end
begin
config_class = "QuickSearch::Engine::#{service_name.upcase}_CONFIG".constantize
config_class['no_results_link']
rescue NameError
nil
end
end | ruby | {
"resource": ""
} |
q17980 | QuickSearch.SearchController.xhr_search | train | def xhr_search
endpoint = params[:endpoint]
if params[:template] == 'with_paging'
template = 'xhr_response_with_paging'
else
template = 'xhr_response'
end
@query = params_q_scrubbed
@page = page
@per_page = per_page(endpoint)
@offset = offset(@page,@per_page)
http_client = HTTPClient.new
update_searcher_timeout(http_client, endpoint, true)
benchmark "%s xhr #{endpoint}" % CGI.escape(@query.to_str) do
klass = "QuickSearch::#{endpoint.camelize}Searcher".constantize
searcher = klass.new(http_client,
extracted_query(params_q_scrubbed),
@per_page,
@offset,
@page,
on_campus?(ip),
extracted_scope(params_q_scrubbed))
searcher.search
searcher_partials = {}
searcher_cfg = searcher_config(endpoint)
unless searcher_cfg.blank?
services = searcher_cfg['services'].blank? ? [] : searcher_cfg['services']
else
services = []
end
services << endpoint
respond_to do |format|
format.html {
services.each do |service|
service_template = render_to_string(
:partial => "quick_search/search/#{template}",
:layout => false,
:locals => { module_display_name: t("#{endpoint}_search.display_name"),
searcher: searcher,
search: '',
service_name: service
})
searcher_partials[service] = service_template
end
render :json => searcher_partials
}
format.json {
# prevents openstruct object from results being nested inside tables
# See: http://stackoverflow.com/questions/7835047/collecting-hashes-into-openstruct-creates-table-entry
result_list = []
searcher.results.each do |result|
result_list << result.to_h
end
render :json => { :endpoint => endpoint,
:per_page => @per_page.to_s,
:page => @page.to_s,
:total => searcher.total,
:results => result_list
}
}
end
end
end | ruby | {
"resource": ""
} |
q17981 | Surrounded.Context.private_const_set | train | def private_const_set(name, const)
unless role_const_defined?(name)
const = const_set(name, const)
private_constant name.to_sym
end
const
end | ruby | {
"resource": ""
} |
q17982 | Fourflusher.Executable.executable | train | def executable(name)
define_method(name) do |*command|
Executable.execute_command(name, Array(command).flatten, false)
end
define_method(name.to_s + '!') do |*command|
Executable.execute_command(name, Array(command).flatten, true)
end
end | ruby | {
"resource": ""
} |
q17983 | Fourflusher.SimControl.fetch_sims | train | def fetch_sims
device_list = JSON.parse(list(['-j', 'devices']))['devices']
unless device_list.is_a?(Hash)
msg = "Expected devices to be of type Hash but instated found #{device_list.class}"
fail Fourflusher::Informative, msg
end
device_list.flat_map do |runtime_str, devices|
# This format changed with Xcode 10.2.
if runtime_str.start_with?('com.apple.CoreSimulator.SimRuntime.')
# Sample string: com.apple.CoreSimulator.SimRuntime.iOS-12-2
_unused, os_info = runtime_str.split 'com.apple.CoreSimulator.SimRuntime.'
os_name, os_major_version, os_minor_version = os_info.split '-'
os_version = "#{os_major_version}.#{os_minor_version}"
else
# Sample string: iOS 9.3
os_name, os_version = runtime_str.split ' '
end
devices.map do |device|
if device['availability'] == '(available)' || device['isAvailable'] == 'YES'
Simulator.new(device, os_name, os_version)
end
end
end.compact.sort(&:sim_list_compare)
end | ruby | {
"resource": ""
} |
q17984 | JsonSchema.Validator.get_extra_keys | train | def get_extra_keys(schema, data)
extra = data.keys - schema.properties.keys
if schema.pattern_properties
schema.pattern_properties.keys.each do |pattern|
extra -= extra.select { |k| k =~ pattern }
end
end
extra
end | ruby | {
"resource": ""
} |
q17985 | JsonPointer.Evaluator.split | train | def split(path)
parts = []
last_index = 0
while index = path.index("/", last_index)
if index == last_index
parts << ""
else
parts << path[last_index...index]
end
last_index = index + 1
end
# and also get that last segment
parts << path[last_index..-1]
# it should begin with a blank segment from the leading "/"; kill that
parts.shift
parts
end | ruby | {
"resource": ""
} |
q17986 | ReportBuilder.Builder.build_report | train | def build_report
options = ReportBuilder.options
groups = get_groups options[:input_path]
json_report_path = options[:json_report_path] || options[:report_path]
if options[:report_types].include? 'JSON'
File.open(json_report_path + '.json', 'w') do |file|
file.write JSON.pretty_generate(groups.size > 1 ? groups : groups.first['features'])
end
end
if options[:additional_css] and Pathname.new(options[:additional_css]).file?
options[:additional_css] = File.read(options[:additional_css])
end
if options[:additional_js] and Pathname.new(options[:additional_js]).file?
options[:additional_js] = File.read(options[:additional_js])
end
html_report_path = options[:html_report_path] || options[:report_path]
if options[:report_types].include? 'HTML'
File.open(html_report_path + '.html', 'w') do |file|
file.write get(groups.size > 1 ? 'group_report' : 'report').result(binding).gsub(' ', '').gsub("\n\n", '')
end
end
retry_report_path = options[:retry_report_path] || options[:report_path]
if options[:report_types].include? 'RETRY'
File.open(retry_report_path + '.retry', 'w') do |file|
groups.each do |group|
group['features'].each do |feature|
if feature['status'] == 'broken'
feature['elements'].each do |scenario|
file.puts "#{feature['uri']}:#{scenario['line']}" if scenario['status'] == 'failed'
end
end
end
end
end
end
[json_report_path, html_report_path, retry_report_path]
end | ruby | {
"resource": ""
} |
q17987 | Methadone.ExitNow.exit_now! | train | def exit_now!(exit_code,message=nil)
if exit_code.kind_of?(String) && message.nil?
raise Methadone::Error.new(1,exit_code)
else
raise Methadone::Error.new(exit_code,message)
end
end | ruby | {
"resource": ""
} |
q17988 | Methadone.CLI.check_and_prepare_basedir! | train | def check_and_prepare_basedir!(basedir,force)
if File.exists? basedir
if force
rm_rf basedir, :verbose => true, :secure => true
else
exit_now! 1,"error: #{basedir} exists, use --force to override"
end
end
mkdir_p basedir
end | ruby | {
"resource": ""
} |
q17989 | Methadone.CLI.add_to_file | train | def add_to_file(file,lines,options = {})
new_lines = []
found_line = false
File.open(file).readlines.each do |line|
line.chomp!
if options[:before] && options[:before] === line
found_line = true
new_lines += lines
end
new_lines << line
end
raise "No line matched #{options[:before]}" if options[:before] && !found_line
new_lines += lines unless options[:before]
File.open(file,'w') do |fp|
new_lines.each { |line| fp.puts line }
end
end | ruby | {
"resource": ""
} |
q17990 | Methadone.CLI.copy_file | train | def copy_file(relative_path,options = {})
options[:from] ||= :full
relative_path = File.join(relative_path.split(/\//))
template_path = File.join(template_dir(options[:from]),relative_path + ".erb")
template = ERB.new(File.open(template_path).readlines.join(''))
relative_path_parts = File.split(relative_path)
relative_path_parts[-1] = options[:as] if options[:as]
erb_binding = options[:binding] or binding
File.open(File.join(relative_path_parts),'w') do |file|
file.puts template.result(erb_binding)
file.chmod(0755) if options[:executable]
end
end | ruby | {
"resource": ""
} |
q17991 | Methadone.ARGVParser.parse_string_for_argv | train | def parse_string_for_argv(string) #:nodoc:
return [] if string.nil?
args = [] # return value we are building up
current = 0 # pointer to where we are in +string+
next_arg = '' # the next arg we are building up to ultimatley put into args
inside_quote = nil # quote character we are "inside" of
last_char = nil # the last character we saw
while current < string.length
char = string.chars.to_a[current]
case char
when /["']/
if inside_quote.nil? # eat the quote, but remember we are now "inside" one
inside_quote = char
elsif inside_quote == char # we closed the quote we were "inside"
inside_quote = nil
else # we got a different quote, so it goes in literally
next_arg << char
end
when /\s/
if last_char == "\\" # we have an escaped space, replace the escape char
next_arg[-1] = char
elsif inside_quote # we are inside a quote so keep the space
next_arg << char
else # new argument
args << next_arg
next_arg = ''
end
else
next_arg << char
end
current += 1
last_char = char
end
args << next_arg unless next_arg == ''
args
end | ruby | {
"resource": ""
} |
q17992 | Methadone.Main.go! | train | def go!
setup_defaults
opts.post_setup
opts.parse!
opts.check_args!
result = call_main
if result.kind_of? Integer
exit result
else
exit 0
end
rescue OptionParser::ParseError => ex
logger.error ex.message
puts
puts opts.help
exit 64 # Linux standard for bad command line
end | ruby | {
"resource": ""
} |
q17993 | Methadone.Main.normalize_defaults | train | def normalize_defaults
new_options = {}
options.each do |key,value|
unless value.nil?
new_options[key.to_s] = value
new_options[key.to_sym] = value
end
end
options.merge!(new_options)
end | ruby | {
"resource": ""
} |
q17994 | Methadone.Main.call_main | train | def call_main
@leak_exceptions = nil unless defined? @leak_exceptions
@main_block.call(*ARGV)
rescue Methadone::Error => ex
raise ex if ENV['DEBUG']
logger.error ex.message unless no_message? ex
ex.exit_code
rescue OptionParser::ParseError
raise
rescue => ex
raise ex if ENV['DEBUG']
raise ex if @leak_exceptions
logger.error ex.message unless no_message? ex
70 # Linux sysexit code for internal software error
end | ruby | {
"resource": ""
} |
q17995 | Methadone.OptionParserProxy.check_args! | train | def check_args!
::Hash[@args.zip(::ARGV)].each do |arg_name,arg_value|
if @arg_options[arg_name].include? :required
if arg_value.nil?
message = "'#{arg_name.to_s}' is required"
message = "at least one " + message if @arg_options[arg_name].include? :many
raise ::OptionParser::ParseError,message
end
end
end
end | ruby | {
"resource": ""
} |
q17996 | Methadone.OptionParserProxy.arg | train | def arg(arg_name,*options)
options << :optional if options.include?(:any) && !options.include?(:optional)
options << :required unless options.include? :optional
options << :one unless options.include?(:any) || options.include?(:many)
@args << arg_name
@arg_options[arg_name] = options
options.select(&STRINGS_ONLY).each do |doc|
@arg_documentation[arg_name] = doc + (options.include?(:optional) ? " (optional)" : "")
end
set_banner
end | ruby | {
"resource": ""
} |
q17997 | Methadone.SH.sh | train | def sh(command,options={},&block)
sh_logger.debug("Executing '#{command}'")
stdout,stderr,status = execution_strategy.run_command(command)
process_status = Methadone::ProcessStatus.new(status,options[:expected])
sh_logger.warn("stderr output of '#{command}': #{stderr}") unless stderr.strip.length == 0
if process_status.success?
sh_logger.debug("stdout output of '#{command}': #{stdout}") unless stdout.strip.length == 0
call_block(block,stdout,stderr,process_status.exitstatus) unless block.nil?
else
sh_logger.info("stdout output of '#{command}': #{stdout}") unless stdout.strip.length == 0
sh_logger.warn("Error running '#{command}'")
end
process_status.exitstatus
rescue *exception_meaning_command_not_found => ex
sh_logger.error("Error running '#{command}': #{ex.message}")
127
end | ruby | {
"resource": ""
} |
q17998 | Methadone.SH.call_block | train | def call_block(block,stdout,stderr,exitstatus)
# blocks that take no arguments have arity -1. Or 0. Ugh.
if block.arity > 0
case block.arity
when 1
block.call(stdout)
when 2
block.call(stdout,stderr)
else
# Let it fail for lambdas
block.call(stdout,stderr,exitstatus)
end
else
block.call
end
end | ruby | {
"resource": ""
} |
q17999 | Ooor.Associations.relationnal_result | train | def relationnal_result(method_name, *arguments)
self.class.reload_fields_definition(false)
if self.class.many2one_associations.has_key?(method_name)
load_m2o_association(method_name, *arguments)
elsif self.class.polymorphic_m2o_associations.has_key?(method_name)# && @associations[method_name]
load_polymorphic_m2o_association(method_name, *arguments)
# values = @associations[method_name].split(',')
# self.class.const_get(values[0]).find(values[1], arguments.extract_options!)
else # o2m or m2m
load_x2m_association(method_name, *arguments)
end
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.