Prints an xml based receipt definition
341110
def receipt(self,xml):
        

        def strclean(string):
            if not string:
                string = ''
            string = string.strip()
            string = re.sub('\s+',' ',string)
            return string

        def format_value(value, decimals=3, width=0, decimals_separator='.', thousands_separator=',', autoint=False, symbol='', position='after'):
            decimals = max(0,int(decimals))
            width    = max(0,int(width))
            value    = float(value)

            if autoint and math.floor(value) == value:
                decimals = 0
            if width == 0:
                width = ''

            if thousands_separator:
                formatstr = "{:"+str(width)+",."+str(decimals)+"f}"
            else:
                formatstr = "{:"+str(width)+"."+str(decimals)+"f}"


            ret = formatstr.format(value)
            ret = ret.replace(',','COMMA')
            ret = ret.replace('.','DOT')
            ret = ret.replace('COMMA',thousands_separator)
            ret = ret.replace('DOT',decimals_separator)

            if symbol:
                if position == 'after':
                    ret = ret + symbol
                else:
                    ret = symbol + ret
            return ret

        def print_elem(stylestack, serializer, elem, indent=0):

            elem_styles = {
                'h1': {'bold': 'on', 'size':'double'},
                'h2': {'size':'double'},
                'h3': {'bold': 'on', 'size':'double-height'},
                'h4': {'size': 'double-height'},
                'h5': {'bold': 'on'},
                'em': {'font': 'b'},
                'b':  {'bold': 'on'},
            }

            stylestack.push()
            if elem.tag in elem_styles:
                stylestack.set(elem_styles[elem.tag])
            stylestack.set(elem.attrib)

            if elem.tag in ('p','div','section','article','receipt','header','footer','li','h1','h2','h3','h4','h5'):
                serializer.start_block(stylestack)
                serializer.text(elem.text)
                for child in elem:
                    print_elem(stylestack,serializer,child)
                    serializer.start_inline(stylestack)
                    serializer.text(child.tail)
                    serializer.end_entity()
                serializer.end_entity()

            elif elem.tag in ('span','em','b','left','right'):
                serializer.start_inline(stylestack)
                serializer.text(elem.text)
                for child in elem:
                    print_elem(stylestack,serializer,child)
                    serializer.start_inline(stylestack)
                    serializer.text(child.tail)
                    serializer.end_entity()
                serializer.end_entity()

            elif elem.tag == 'value':
                serializer.start_inline(stylestack)
                serializer.pre(format_value( 
                                              elem.text,
                                              decimals=stylestack.get('value-decimals'),
                                              width=stylestack.get('value-width'),
                                              decimals_separator=stylestack.get('value-decimals-separator'),
                                              thousands_separator=stylestack.get('value-thousands-separator'),
                                              autoint=(stylestack.get('value-autoint') == 'on'),
                                              symbol=stylestack.get('value-symbol'),
                                              position=stylestack.get('value-symbol-position') 
                                            ))
                serializer.end_entity()

            elif elem.tag == 'line':
                width = stylestack.get('width')
                if stylestack.get('size') in ('double', 'double-width'):
                    width = width / 2

                lineserializer = XmlLineSerializer(stylestack.get('indent')+indent,stylestack.get('tabwidth'),width,stylestack.get('line-ratio'))
                serializer.start_block(stylestack)
                for child in elem:
                    if child.tag == 'left':
                        print_elem(stylestack,lineserializer,child,indent=indent)
                    elif child.tag == 'right':
                        lineserializer.start_right()
                        print_elem(stylestack,lineserializer,child,indent=indent)
                serializer.pre(lineserializer.get_line())
                serializer.end_entity()

            elif elem.tag == 'ul':
                serializer.start_block(stylestack)
                bullet = stylestack.get('bullet')
                for child in elem:
                    if child.tag == 'li':
                        serializer.style(stylestack)
                        serializer.raw(' ' * indent * stylestack.get('tabwidth') + bullet)
                    print_elem(stylestack,serializer,child,indent=indent+1)
                serializer.end_entity()

            elif elem.tag == 'ol':
                cwidth = len(str(len(elem))) + 2
                i = 1
                serializer.start_block(stylestack)
                for child in elem:
                    if child.tag == 'li':
                        serializer.style(stylestack)
                        serializer.raw(' ' * indent * stylestack.get('tabwidth') + ' ' + (str(i)+')').ljust(cwidth))
                        i = i + 1
                    print_elem(stylestack,serializer,child,indent=indent+1)
                serializer.end_entity()

            elif elem.tag == 'pre':
                serializer.start_block(stylestack)
                serializer.pre(elem.text)
                serializer.end_entity()

            elif elem.tag == 'hr':
                width = stylestack.get('width')
                if stylestack.get('size') in ('double', 'double-width'):
                    width = width / 2
                serializer.start_block(stylestack)
                serializer.text('-'*width)
                serializer.end_entity()

            elif elem.tag == 'br':
                serializer.linebreak()

            elif elem.tag == 'img':
                if 'src' in elem.attrib and 'data:' in elem.attrib['src']:
                    self.print_base64_image(elem.attrib['src'])

            elif elem.tag == 'barcode' and 'encoding' in elem.attrib:
                serializer.start_block(stylestack)
                self.barcode(strclean(elem.text),elem.attrib['encoding'])
                serializer.end_entity()

            elif elem.tag == 'cut':
                self.cut()
            elif elem.tag == 'partialcut':
                self.cut(mode='part')
            elif elem.tag == 'cashdraw':
                self.cashdraw(2)
                self.cashdraw(5)

            stylestack.pop()

        try:
            stylestack      = StyleStack() 
            serializer      = XmlSerializer(self)
            root            = ET.fromstring(xml.encode('utf-8'))
            if 'sheet' in root.attrib and root.attrib['sheet'] == 'slip':
                self._raw(SHEET_SLIP_MODE)
                self.slip_sheet_mode = True
            else:
                self._raw(SHEET_ROLL_MODE)

            self._raw(stylestack.to_escpos())

            print_elem(stylestack,serializer,root)

            if 'open-cashdrawer' in root.attrib and root.attrib['open-cashdrawer'] == 'true':
                self.cashdraw(2)
                self.cashdraw(5)
            if not 'cut' in root.attrib or root.attrib['cut'] == 'true' :
                if self.slip_sheet_mode:
                    self._raw(CTL_FF)
                else:
                    self.cut()

        except Exception as e:
            errmsg = str(e)+'\n'+'-'*48+'\n'+traceback.format_exc() + '-'*48+'\n'
            self.text(errmsg)
            self.cut()

            raise e
1336910
def __PrintDocstring(self, printer, method_info, method_name, name):
        """"""
        if method_info.description:
            description = util.CleanDescription(method_info.description)
            first_line, newline, remaining = method_info.description.partition(
                '\n')
            if not first_line.endswith('.'):
                first_line = '%s.' % first_line
            description = '%s%s%s' % (first_line, newline, remaining)
        else:
            description = '%s method for the %s service.' % (method_name, name)
        with printer.CommentContext():
            printer('r"""%s' % description)
        printer()
        printer('Args:')
        printer('  request: (%s) input message', method_info.request_type_name)
        printer('  global_params: (StandardQueryParameters, default: None) '
                'global arguments')
        if method_info.upload_config:
            printer('  upload: (Upload, default: None) If present, upload')
            printer('      this stream with the request.')
        if method_info.supports_download:
            printer(
                '  download: (Download, default: None) If present, download')
            printer('      data from the request via this stream.')
        printer('Returns:')
        printer('  (%s) The response message.', method_info.response_type_name)
        printer('"""')
164540
public function validate($receipt)
    {
        // Load the receipt that needs to verified as an XML document.
        $dom = new \DOMDocument;
        if (@$dom->loadXML($receipt) === false) {
            throw new RunTimeException('Invalid XML');
        }

        // The certificateId attribute is present in the document root, retrieve it.
        $certificateId = $dom->documentElement->getAttribute('CertificateId');
        if (empty($certificateId)) {
            throw new RunTimeException('Missing CertificateId in receipt');
        }

        // Retrieve the certificate from the official site.
        $certificate = $this->retrieveCertificate($certificateId);

        return $this->validateXml($dom, $certificate);
    }
1079218
def create_xml_string(self):
        
        root = self.create_xml()

        xml = '<?xml version="1.0" encoding="UTF-8"?>\n' + tostring(
            root, pretty_print=True
        )
        return xml
854040
public function xml()
    {
        foreach ($this->_result as $printer=>$markersupplies_item) {
            $xmlsnmppinfo_printer = $this->xml->addChild("Printer");
            $xmlsnmppinfo_printer->addAttribute("Device", $printer);
            if (isset($markersupplies_item[1]) &&
                isset($markersupplies_item[1]['prtMarkerSuppliesDescriptionRicoh']) &&
                isset($markersupplies_item[1]['prtMarkerSuppliesLevelRicoh'])) {
                $ricoh = true;
            } else {
                $ricoh = false;
            }

            foreach ($markersupplies_item as $marker=>$snmppinfo_item) {
                if ($marker==0) {
                    $xmlsnmppinfo_printer->addAttribute("Name", $snmppinfo_item['prtMarkerSuppliesDescription']);
                } elseif ($marker==99) {
                    foreach ($snmppinfo_item as $item=>$iarr) {
                        if (isset($iarr["message"]) && $iarr["message"] != "") {
                            $xmlsnmppinfo_errors = $xmlsnmppinfo_printer->addChild("PrinterMessage");
                            $xmlsnmppinfo_errors->addAttribute("Message", $iarr["message"]);
                            $xmlsnmppinfo_errors->addAttribute("Severity", $iarr["severity"]);
                        }
                    }
                } else {
                    if ($ricoh) {
                        if (isset($snmppinfo_item['prtMarkerSuppliesDescriptionRicoh'])) {
                            $xmlsnmppinfo = $xmlsnmppinfo_printer->addChild("MarkerSupplies");

                            $xmlsnmppinfo->addAttribute("Description", $snmppinfo_item['prtMarkerSuppliesDescriptionRicoh']);
                            $xmlsnmppinfo->addAttribute("SupplyUnit", "19");
                            $xmlsnmppinfo->addAttribute("MaxCapacity", "100");
                            $xmlsnmppinfo->addAttribute("Level", isset($snmppinfo_item['prtMarkerSuppliesLevelRicoh']) ? $snmppinfo_item['prtMarkerSuppliesLevelRicoh'] : "");
                        }
                    } else {
                        $xmlsnmppinfo = $xmlsnmppinfo_printer->addChild("MarkerSupplies");

                        $xmlsnmppinfo->addAttribute("Description", isset($snmppinfo_item['prtMarkerSuppliesDescription']) ? $snmppinfo_item['prtMarkerSuppliesDescription'] : "");
                        $xmlsnmppinfo->addAttribute("SupplyUnit", isset($snmppinfo_item['prtMarkerSuppliesSupplyUnit']) ? $snmppinfo_item['prtMarkerSuppliesSupplyUnit'] : "");
                        $xmlsnmppinfo->addAttribute("MaxCapacity", isset($snmppinfo_item['prtMarkerSuppliesMaxCapacity']) ? $snmppinfo_item['prtMarkerSuppliesMaxCapacity'] : "");
                        $xmlsnmppinfo->addAttribute("Level", isset($snmppinfo_item['prtMarkerSuppliesLevel']) ? $snmppinfo_item['prtMarkerSuppliesLevel'] : "");
                    }
                }
            }
        }

        return $this->xml->getSimpleXmlElement();
    }
1240094
def get_result_xml(result):
    
    result_xml = Element('result')
    for name, value in [('name', result['name']),
                        ('type', ResultType.get_str(result['type'])),
                        ('severity', result['severity']),
                        ('host', result['host']),
                        ('test_id', result['test_id']),
                        ('port', result['port']),
                        ('qod', result['qod'])]:
        result_xml.set(name, str(value))
    result_xml.text = result['value']
    return result_xml
1316198
private void printNamespaces(NodeTypeData nodeTypeData, OutputStreamWriter out) throws RepositoryException,
      IOException
   {

      /**
       * Using set to store all prefixes found in node types to avoid
       * duplication
       */
      Set<String> namespaces = new HashSet<String>();
      /** Scanning nodeType definition for used namespaces */
      printNameNamespace(nodeTypeData.getName(), namespaces);
      printNameNamespace(nodeTypeData.getPrimaryItemName(), namespaces);
      if (nodeTypeData.getDeclaredSupertypeNames() != null)
      {
         for (InternalQName reqType : nodeTypeData.getDeclaredSupertypeNames())
         {
            printNameNamespace(reqType, namespaces);
         }
      }
      /** Scanning property definitions for used namespaces */
      if (nodeTypeData.getDeclaredPropertyDefinitions() != null)
      {
         for (PropertyDefinitionData property : nodeTypeData.getDeclaredPropertyDefinitions())
         {
            printNameNamespace(property.getName(), namespaces);
         }
      }
      /** Scanning child definitions for used namespaces */
      if (nodeTypeData.getDeclaredChildNodeDefinitions() != null)
      {
         for (NodeDefinitionData child : nodeTypeData.getDeclaredChildNodeDefinitions())
         {
            printNameNamespace(child.getName(), namespaces);
            printNameNamespace(child.getDefaultPrimaryType(), namespaces);
            if (child.getRequiredPrimaryTypes() != null)
            {
               for (InternalQName reqType : child.getRequiredPrimaryTypes())
               {
                  printNameNamespace(reqType, namespaces);
               }
            }
         }
      }
      for (String prefix : namespaces)
      {
         String uri = namespaceRegistry.getURI(prefix);
         out.write("<" + prefix + "='" + uri + "'>\r\n");
      }
   }
86645
def xml(self, indent = ""):
        """"""
        xml = "\n" + indent + "<profile>\n"
        xml += indent + " <input>\n"
        for inputtemplate in self.input:
            xml += inputtemplate.xml(indent +"    ") + "\n"
        xml += indent + " </input>\n"
        xml += indent + " <output>\n"
        for outputtemplate in self.output:
            xml += outputtemplate.xml(indent +"    ") + "\n" #works for ParameterCondition as well!
        xml += indent + " </output>\n"
        xml += indent + "</profile>\n"
        return xml
192623
void asPresentationML(XmlPrintStream out) {
    out.openElement(getMessageMLTag(), getAttributes());

    for (Element child : getChildren()) {
      child.asPresentationML(out);
    }

    out.closeElement();
  }
12851
def XmlRawQuery(self, xml, dumpXml=None):
		

		if (dumpXml == None):
			dumpXml = self._dumpXml

		uri = self.Uri() + '/nuova'
		if (dumpXml in _AffirmativeList):
			print '%s ====> %s' % (self._ucs, xml)
		# req = urllib2.Request(url=uri,data=xml)
		# f = urllib2.urlopen(req)
		w = xml.dom.minidom.Document()

		if (self._noSsl):
			req = urllib2.Request(url=uri, data=w.toxml())
			opener = urllib2.build_opener(SmartRedirectHandler())
			f = opener.open(req)
			# print "##", f , "##"

			if type(f) is list:
				if (len(f) == 2 and f[0] == 302):
					# self._noSsl = False
					# uri = self.Uri() + '/nuova'
					uri = f[1]
					req = urllib2.Request(url=uri, data=w.toxml())
					f = urllib2.urlopen(req)
				# print "status code is:",f[0]
				# print "location is:", f[1]
		else:
			req = urllib2.Request(url=uri, data=w.toxml())
			f = urllib2.urlopen(req)

		rsp = f.read()
		if (dumpXml in _AffirmativeList):
			print '%s <==== %s' % (self._ucs, rsp)
		return rsp
231285
public void dumpXml(PrintStream out) {
        out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        out.println("<history>");
        String startData = "    <data ";
        String stop = "/>";
        for (int i = 0; i < versionList.length; ++i) {
            Version version = versionList[i];
            AppVersion appVersion = sequenceToAppVersionMap.get(version.getSequence());
            out.print("  <historyItem ");
            out.print("seq=\"");
            out.print(i);
            out.print("\" ");
            out.print("version=\"");
            out.print(appVersion != null ? appVersion.getReleaseName() : "");
            out.print("\" ");
            out.print("time=\"");
            if (formatDates) {
                out.print((appVersion != null ? new Date(appVersion.getTimestamp()).toString() : ""));
            } else {
                out.print(appVersion != null ? appVersion.getTimestamp() : 0L);
            }
            out.print("\"");
            out.println(">");

            String attributeName[] = new String[TUPLE_SIZE];
            attributeName[0] = "added";
            attributeName[1] = "newCode";
            attributeName[2] = "fixed";
            attributeName[3] = "removed";
            attributeName[4] = "retained";
            attributeName[5] = "dead";
            attributeName[6] = "active";
            for (int j = 0; j < TUPLE_SIZE; ++j) {
                // newCode and retained are already comprised within active
                // so we skip tehm
                if (j == 1 || j == 4) {
                    continue;
                }
                out.print(startData + " name=\"" + attributeName[j] + "\" value=\"");
                out.print(version.get(j));
                out.print("\"");
                out.println(stop);
            }
            out.println("  </historyItem>");
        }
        out.print("</history>");
    }
706958
public function toXLIFF($pretty_print = FALSE) {
    $this->doc->formatOutput = $pretty_print;

    // Do not use getElementById to comply with older versions of libxml.
    // getElementById doesn't work properly on libxml 2.7.6 (CentOS)
    $xpath = new \DOMXPath($this->doc);
    $wrapper_div = $xpath->query("//*[@id='eggs-n-cereal-dont-ever-use-this-id']")->item(0);

    $out = $this->doc->createDocumentFragment();

    $domNodeList = array();
    for ($i = 0; $i < $wrapper_div->childNodes->length; ++$i) {
      $domNodeList[] = $wrapper_div->childNodes->item($i);
    }

    $this->sanitizeMixedDomNodeList($this->doc, $domNodeList);

    foreach($domNodeList as $domNode){
      if ($output = $this->convert($domNode)) {
        $out->appendChild($output);
      }
    }

    return $this->doc->saveXML($out);
  }
418734
def to_xml
      raise RuntimeError, "Empty cart" if self.empty?

      xml = Builder::XmlMarkup.new
      xml.instruct!
      @xml = xml.tag!('checkout-shopping-cart', :xmlns => "http://checkout.google.com/schema/2") {
        xml.tag!("shopping-cart") {
          xml.items {
            @contents.each { |item|
              xml.item {
                if item.key?(:item_id)
                  xml.tag!('merchant-item-id', item[:item_id])
                end
                xml.tag!('item-name') {
                  xml.text! item[:name].to_s
                }
                xml.tag!('item-description') {
                  xml.text! item[:description].to_s
                }
                xml.tag!('unit-price', :currency => (item[:currency] || 'USD')) {
                  xml.text! item[:price].to_s
                }
                xml.quantity {
                  xml.text! item[:quantity].to_s
                }
              }
            }
          }
          unless @merchant_private_data.empty?
            xml.tag!("merchant-private-data") {
              @merchant_private_data.each do |key, value|
                xml.tag!(key, value)
              end
            }
          end
        }
        xml.tag!('checkout-flow-support') {
          xml.tag!('merchant-checkout-flow-support') {
            xml.tag!('edit-cart-url', @edit_cart_url) if @edit_cart_url
            xml.tag!('continue-shopping-url', @continue_shopping_url) if @continue_shopping_url

            xml.tag!("request-buyer-phone-number", false)

            # TODO tax-tables
            xml.tag!("tax-tables") {
              xml.tag!("default-tax-table") {
                xml.tag!("tax-rules") {
                  xml.tag!("default-tax-rule") {
                    xml.tag!("shipping-taxed", false)
                    xml.tag!("rate", "0.00")
                    xml.tag!("tax-area") {
                      xml.tag!("world-area")
                    }
                  }
                }
              }
            }

            xml.tag!('shipping-methods') {
              if @shipping_methods
                @shipping_methods.each { |method|
                  xml.tag!("pickup", :name => method[:name]) {
                    xml.tag!('price', method[:price], :currency => method[:currency] || 'USD')
                  }
                }
              end
            }
            
            
          }
        }
      }
      @xml.dup
    end
694773
private void printReport() {
		System.out.println("Processed " + this.countItems + " items:");
		System.out.println(" * Properties encountered: "
				+ this.propertyRecords.size());
		System.out.println(" * Property documents: " + this.countProperties);
		System.out.println(" * Classes encountered: "
				+ this.classRecords.size());
		System.out.println(" * Class documents: " + this.countClasses);
	}
887640
public void printElement(String elementName, String value, Map<String, String> attributes) {
    print("<" + elementName);

    for (Entry<String, String> entry : attributes.entrySet()) {
      print(" " + entry.getKey() + "=\"" + escape(entry.getValue()) + "\"");
    }

    if (value != null) {
      println(">" + escape(value) + "</" + elementName + ">");
    } else {
      println("/>");
    }
  }
61184
private void printClassRecord(PrintStream out, ClassRecord classRecord,
			EntityIdValue entityIdValue) {
		printTerms(out, classRecord.itemDocument, entityIdValue, "\""
				+ getClassLabel(entityIdValue) + "\"");
		printImage(out, classRecord.itemDocument);

		out.print("," + classRecord.itemCount + "," + classRecord.subclassCount);

		printClassList(out, classRecord.superClasses);

		HashSet<EntityIdValue> superClasses = new HashSet<>();
		for (EntityIdValue superClass : classRecord.superClasses) {
			addSuperClasses(superClass, superClasses);
		}

		printClassList(out, superClasses);

		printRelatedProperties(out, classRecord);

		out.println("");
	}
573168
def to_xml
			result_string = String.new
			result_string << "<results>\n"
			@results.each do |result|
				result_string << "\t<vtresult>\n"
				RESULT_FIELDS.each{|field|
					result_string << "\t\t<#{field.to_s}>#{result[field]}</#{field.to_s}>\n" unless field == :permalink and result['permalink'].nil?
				}
				result_string << "\t</vtresult>\n"
			end if @results != nil
			result_string << "</results>\n"

			result_string
		end